Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I Emulate a click, on document ready, 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 id.

Now, I'd like, on document ready, "handle" automatically the link with id=2, without "clicking" on it.

So, having a sort of emulation on that link. Is it possible with jQuery?

like image 377
markzzz Avatar asked Dec 16 '22 06:12

markzzz


1 Answers

To trigger an event simply call the relevant event function in jQuery on the element, with no handler function defined, like this:

$("#2").click();

Or there is also trigger(), which accepts the event type as a parameter:

$("#2").trigger('click');

However it's worth noting that Id attributes beginning with numbers are invalid, so you will most likely have to change your Ids for them to work properly.

I've updated your fiddle to fix the IDs and show the above code working here

like image 113
Rory McCrossan Avatar answered Dec 18 '22 19:12

Rory McCrossan