Click here to Skip to main content
15,886,362 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
the purpose of this question is just to figure something out

i have this html
HTML
<div id='div1'>
<input id='btn1' type='button' value='click here'/>
</div>

and this jquery
JavaScript
$('#btn1').click(function(){
$('#div1').append($("<a id='link1' target='_blank' href='http://www.google.com'>google </a>"));
});
$('#btn1').click();
$('#link1').click();

-the purpose of above example is to open google link automatically to test if i can click elements that created on the fly or not.
the above code not worked as expected
but
if i replace
JavaScript
$('#link1').click();

with
JavaScript
document.getElementById('link1').click();

it works .

So i need explanation , thanks.
Posted

1 solution

I can't see this mentioned in the official documentation, but jQuery's .click() method only triggers the attached event handlers; it doesn't actually click the link.

As you've discovered, the workaround is to call the .click() method on the raw DOM element, rather than the jQuery wrapper object.

However, most browsers will block the navigation, since pop-up windows which aren't initiated by the user are generally a bad thing.
 
Share this answer
 
Comments
Hercal 21-May-15 9:26am    
but u know when i use $('#btn1').click();
it works
when i use this $('#link1').click();
it doesn't work
Richard Deeming 21-May-15 9:29am    
Yes, because it's not clicking the button; it's just triggering the registered event handlers.

You registered an event handler for the button's "click" event on the previous line. When you call .click(), it triggers that event handler.

If you registered an event handler for the link's "click" event, and then used jQuery's .click() method, that event handler would also fire. It's just that the browser would not attempt to follow the link.
Hercal 21-May-15 9:32am    
i can't understand :( , i am beginner , can u use simple way
Richard Deeming 21-May-15 9:36am    
Calling $("selector").click() calls the event handlers, but doesn't click the element.

Calling document.getElementById("id").click() calls the event handlers and clicks the element.
Hercal 21-May-15 9:39am    
good , thanks.
why when calling $.click on button , it click the button
u said that it just triggering the registered event, what do u mean by that ?

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900