How do I make jquery click <a href="test.zip" id="mylink">test</a>
<script>
// this wont work
$('#mylink').trigger('click');
</script>
Please can you help
You need to trigger the default click method, not the one by jQuery. This can be done by adding the default click option within a click event of jQuery using this . This is how the JavaScript looks. It basically creates the event when the DOM is ready, and clicks it intermediately, thus following the link.
Answer: Use the jQuery click() Method You can use the click() method to trigger a click on a link programmatically using jQuery.
jQuery trigger() MethodThe trigger() method triggers the specified event and the default behavior of an event (like form submission) for the selected elements. This method is similar to the triggerHandler() method, except that triggerHandler() does not trigger the default behavior of the event.
The HTMLElement. click() method simulates a mouse click on an element. When click() is used with supported elements (such as an <input> ), it fires the element's click event. This event then bubbles up to elements higher in the document tree (or event chain) and fires their click events.
If your intention is to navigate to the specified URL as if the user had clicked the link try calling the DOM .click()
method instead of the jQuery .click()
method:
$('#mylink')[0].click();
The jQuery .click()
will call event handlers that you've bound but not cause the default click behaviour.
$(document).ready(function(){
$('#mylink').trigger('click');
});
You need to trigger the default click
method, not the one by jQuery. This can be done by adding the default click option within a click event of jQuery using this
.
<a href="http://about.com/"></a>
This is how the JavaScript looks. It basically creates the event when the DOM is ready, and clicks it intermediately, thus following the link.
$(function() {
$('a').click(function() {
// 'this' is not a jQuery object, so it will use
// the default click() function
this.click();
}).click();
});
To see a live example (opening about.com), see: http://jsfiddle.net/8H9UX/
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