Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery .trigger('click')

I am having trouble getting this to work. I would like to trigger the second link. If anyone can help that would be much appreciated.

    $(".links").click(function () {
        alert($(this));
    })


    function someFunction(){
        $(".links").trigger('click');
    }

    someFunction();

    ...
    <a href="1.html" class="links">One</a>
    <a href="2.html" class="links">Two</a>
    <a href="3.html" class="links">Three</a>
like image 864
Chris Chiera Avatar asked Oct 20 '10 14:10

Chris Chiera


People also ask

What is trigger click in jQuery?

jQuery trigger() Method The 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.

What is trigger (' Change ')?

jQuery trigger change event occurs when the value of an element is modified; then, it will trigger the change event. The change method either initiates a change event or attaches a function to execute. The change event occurs when an option in the select menu is selected.

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.

How can set click event in jQuery?

To trigger the onclick function in jQuery, click() method is used. For example, on clicking a paragraph on a document, a click event will be triggered by the $(“p”). click() method. The user can attach a function to a click method whenever an event of a click occurs to run the function.


1 Answers

Have someFunction() accept an argument that is the 0 based index of link you want to click.

function someFunction( n ){
    $(".links:eq(" + n + ")").trigger('click');
}

someFunction( 1 ); // Pass 1 to trigger the second link

This uses the :eq() selector. You could also use the .eq() method if you wanted.

function someFunction( n ){
    $(".links").eq( n ).trigger('click');
}
like image 182
user113716 Avatar answered Oct 25 '22 07:10

user113716