Adding Event to jQuery

Can someone tell me why I cannot add the handler separately and instead I have to do something like below to make it work ?

My question is why I should add the code for hiding the paragraph inside the $(document).ready() to make it work.

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
    alert('test');
});
</script>
<script>
$("p").click(function(){
        $(this).hide();
    });
    </script>
</head>
<body>

<p>If you click on me, I will disappear.</p>
<p>Click me away!</p>
<p>Click me too!</p>

</body>
</html>

Working code-

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
    $("p").click(function(){
        $(this).hide();
    });
});
</script>
</head>
<body>

<p>If you click on me, I will disappear.</p>
<p>Click me away!</p>
<p>Click me too!</p>

</body>
</html>

Answers 1

  • The problem in the first snippet is jQuery code registered before the document is loaded so it will not going to recognize any HTML element. And hence it will not work.

    Solution:-

    1.Either put your code at the bottom of the page (in case of first one).

    2.Or wrap your code inside ($(document).ready(function(){..});) which you have already done in second code.

    In both above cases HTML element are loaded properly and registered before your jQuery code and hence your code will start working


Related Articles