Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

$('a').trigger('click'); not working

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

like image 501
Hello-World Avatar asked Jun 14 '13 09:06

Hello-World


People also ask

Why jQuery trigger is not working?

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.

How to trigger a href click jQuery?

Answer: Use the jQuery click() Method You can use the click() method to trigger a click on a link programmatically using jQuery.

How to work trigger in 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.

How do you trigger a click element?

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.


3 Answers

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.

like image 77
nnnnnn Avatar answered Oct 11 '22 02:10

nnnnnn


$(document).ready(function(){
    $('#mylink').trigger('click');
});
like image 23
maximkou Avatar answered Oct 11 '22 01:10

maximkou


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/

like image 9
Broxzier Avatar answered Oct 11 '22 01:10

Broxzier