How to trigger a click on a link using jQuery
Sorry, but the event handler is really not needed. What you do need is another element within the tag to click on.
<a id="test1" href="javascript:alert('test1')">TEST1</a>
<a id="test2" href="javascript:alert('test2')"><span>TEST2</span></a>
Jquery:
$('#test1').trigger('click'); // Nothing
$('#test2').find('span').trigger('click'); // Works
$('#test2 span').trigger('click'); // Also Works
This is all about what you are clicking and it is not the tag but the thing within it. Unfortunately, bare text does not seem to be recognised by JQuery, but it is by vanilla javascript:
document.getElementById('test1').click(); // Works!
Or by accessing the jQuery object as an array
$('#test1')[0].click(); // Works too!!!
Since this question is ranked #1 in Google for "triggering a click on an <a>
element" and no answer actually mentions how you do that, this is how you do it:
$('#titleee a')[0].click();
Explanation: you trigger a click
on the underlying html-element, not the jQuery-object.
You're welcome googlers :)
If you are trying to trigger an event on the anchor, then the code you have will work I recreated your example in jsfiddle with an added eventHandler so you can see that it works:
$(document).on("click", "a", function(){
$(this).text("It works!");
});
$(document).ready(function(){
$("a").trigger("click");
});
Are you trying to cause the user to navigate to a certain point on the webpage by clicking the anchor, or are you trying to trigger events bound to it? Maybe you haven't actually bound the click event successfully to the event?
Also this:
$('#titleee').find('a').trigger('click');
is the equivalent of this:
$('#titleee a').trigger('click');
No need to call find. :)