Sarah McLachlane
Sarah McLachlane

Reputation: 537

trigger click on id inside a class in jquery

I'm trying to trigger a click on a id named click once the page loads. My script works fine when I manually click on the divs with the id click however I need the first element with id click to be clicked once the page loads.

HTML:

<ul><li><div id="click"></div></li></ul>

jQuery

$("div[id='click']").click(function() { alert("click detected!"); });

and this is what I've tried:

$(document).ready(function() { $("div[id='click']:eq(1)").click(); });

Upvotes: 0

Views: 2062

Answers (2)

Krish R
Krish R

Reputation: 22711

Try,

$("#click").click(function() { alert("click detected!"); });

Upvotes: 0

adeneo
adeneo

Reputation: 318182

Use trigger()

$('#click').on('click', function() { 
    alert("click detected!"); 
}).trigger('click');

Note that there is no "first element with the ID click", there is ONLY ONE element with that ID, as ID's are unique.

Upvotes: 1

Related Questions