Reputation: 37
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>
Upvotes: 0
Views: 129
Reputation: 41
For me it works with the following code
$(document).ready(function(){
$("#p1").click(function(){
$(this).hide();
});
});
Upvotes: 0
Reputation: 82251
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();
});
Upvotes: 3