I have a link that is on the page and I want to click it programmatically when the page loads.
Something like this:
$(document).ready(function () {
// code to make the page think $('a.tagcloud-link') is clicked
});
The link is an AJAX call that displays the popular tags in Wordpress backend.
The function cannot easily be edited as it's dependent on many things.
So I want to trigger the AJAX link that calls the most popular tags on page load.
This will solve all my problems if it works.
That link is $('a.tagcloud-link')
Please, please help me on this I've spent hours pulling my hair out trying and failing to do this. Thank you.
Use the jQuery click() Method You can use the click() method to trigger a click on a link programmatically using jQuery.
To create a button link to another page in HTML,just add <a> tag and wrap it around the simple Html button. Inside a <a> tag simply use href=“” attribute to give the path of the desired page. The output shows that, after clicking the “Click” button, you will be navigated to “Google” instantly.
Use $('selector')[0] , as $('selector') returns a jQuery object, so $('selector'). click() will fire the click handler, while $('selector')[0]. click() would fire the actual click.
Try this:
$('a.tagcloud-link')[0].click();
Using [0]
gets a reference to the first DOM object in the jQuery object so this calls the DOM object's (non-jQuery) .click()
method which will cause the navigation to the link's specified href
.
Using jQuery's .click()
method would call any click handler that you'd bound to the element, but won't cause the default behaviour to actually follow the link.
Really simple demo: http://jsfiddle.net/mtBav/
If that element owns an event handler which was bound with jQuery too, you might just call .trigger( 'click' )
or short .click()
;
$(function() {
$('a.tagcloud-link').click();
});
Of course, at the time when you invoke .click()
, that event handler must be bound already.
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$("a#tobeclicked").click(function () {
// if it has to be href
var tohref = $(this).attr("href");
alert(tohref);
window.location=tohref;
// else you want add some functions
$("#mydiv").fadeIn();
});
$("a#tobeclicked").trigger('click');
});
</script>
<a id="tobeclicked" href="http://www.google.com">Go!</a>
<div id="mydiv" style="display:none;">Stroam</div>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With