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>
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.
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.
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.
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.
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');
}
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