0

My question: why the function call $("#p1").click() doesn't simulate users to click on "p1"? i.e. the "$(this).hide() is not executed at all.

but if I register the click event in $(document).ready(function() {});, then $("#p1").click() works! Why?

<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>

$("#p1").click(function(){
    $(this).hide();
});  

$(document).ready(function(){
 $("#p1").click();            <== this line doesn't work! why?

});

</script>
</head>
<body>

<p id="p1">If you click on me, I will disappear.</p>

</body>
</html>

2 Answers2

3

That is because element #p1 is not loaded when you are attaching the click event to it.Use:

$(document).ready(function(){
 $("#p1").click(function(){
    $(this).hide();
 });  
 $("#p1").click();         
});
Milind Anantwar
  • 81,290
  • 25
  • 94
  • 125
  • Thanks. actually this part "$("#p1").click(function(){ $(this).hide(); }); " is in another javascript file. So how can i load it dynamically in the $(document).ready callback function? – user1157924 Oct 16 '14 at 15:20
0

For me it works with the following code

$(document).ready(function(){
    $("#p1").click(function(){
        $(this).hide();
    });
});
Kalakuh
  • 41
  • 6
  • Thanks. More questions: how should I write the HTML script if "$("p1").CLICK(function() {...});" part is in another javascript file? Can I just "include" that .js file here? – user1157924 Oct 16 '14 at 15:00
  • For example, if you have put that code into a "script.js" file, you just have to add these tags to your HTML code: "" – Kalakuh Oct 16 '14 at 15:05
  • but you cannot write "" in the $(document).ready(function(){...}) function? People just mentioned, we need to register the "click" event when document is ready... so what should i do? Thanks again – user1157924 Oct 16 '14 at 15:18