Can I emulate a click on a finished document with jQuery?
I have this code :
<a href="javascript:void(0)" id="0" class="hp_nav_label">0</a> <a href="javascript:void(0)" id="1" class="hp_nav_label">1</a> <a href="javascript:void(0)" id="2" class="hp_nav_label">2</a> <a href="javascript:void(0)" id="3" class="hp_nav_label">3</a> <a href="javascript:void(0)" id="4" class="hp_nav_label">4</a> $('.hp_nav_label').click(function() { alert($(this).attr('id')); });
When I click on each link, I display its identifier.
Now, I would like to automatically βprocessβ the link with id=2
on the finished document, without βclickingβ it.
So, having a kind of emulation on this link. Is this possible with jQuery?
To trigger an event, simply call the corresponding event function in jQuery on the element, without a specific handler function, for example:
$("#2").click();
Or there is also trigger()
that accepts the type of event as a parameter:
$("#2").trigger('click');
However, it is worth noting that Id
attributes starting with numbers are invalid, so you will most likely have to change your identifiers so that they can work properly.
I updated your script to fix the identifiers and show the above code here
Yes, .click()
methods are also used to trigger the click
event.
$('#2').click();
This is a shorthand for $('#2').trigger('click');
.
Also note that the identifier cannot begin with a digit.