Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery trigger click on first child

I'm trying to invoke a click on first .loader child when document is ready, but no success:

html:

<a class="loader" data-target="david-boy" title="Danny Boy-Rivera">
    <span class="img"><span class="play"></span><img src="img/gallery-image1.jpg" alt="" /></span>
    <h2>Danny Boy</h2>
</a>

jQuery:

//Does not work
$('a.loader:first-child').bind('click');
$('a.loader:first-child').trigger('click');
$('a.loader:first-child').click();
//Works
$('a.loader:first-child').css("background", "red");

Any ideas why?

Update

Handler:

$('.loader').click(function(){
    var name=$(this).data("target");
    callVideo(name);
});

Update2

So the problem was that I had declared the :first-child action before the handler. I changed their places and everything ok

like image 891
Alex Avatar asked May 10 '12 14:05

Alex


People also ask

How to click first child in jQuery?

The :first-child selector selects all elements that are the first child of their parent. Tip: Use the :last-child selector to select elements that are the last child of their parent.

Is first child jQuery?

It is a jQuery Selector used to select every element that is the first child of its parent. Return Value: It selects and returns the first child element of its parent.


1 Answers

Did you define the handler before you initiated the triggered 'click'?

Here's the EXACT same code from your fiddle except I put the handler BEFORE the trigger

$(document).ready(function(){
    $('.loader').click(function(){
       alert($(this).data("target")); 
    });
    $('.loader:first-child').click();
    $('.loader:first-child').css("background", "red");
});​

This will pop the alert you're looking for

like image 53
Likwid_T Avatar answered Oct 09 '22 16:10

Likwid_T