Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how do fire trigger ? first element

I have this simple script

html code

<div id='div1'>
    <ul>
        <li><a href='#gone'>gone</a></li>
        <li><a href='#gtwo'>gtwo</a></li>
    </ul>
</div>
<div id='div2'>
    <ul>
        <li><a href='#g1'>g1</a></li>
        <li><a href='#g2'>g2</a></li>
    </ul>
</div>

js code

init();
function init(){
    target = $('#div1').find('ul');

    target.on('click','a',function(){
        alert ($(this).attr('href'));
    });

    target.trigger('click');
}

how do fire trigger ? first element that would be with href #gone

like image 729
Omar Makled Avatar asked May 25 '13 15:05

Omar Makled


2 Answers

You can assign a unique id to each anchor tag and can use like

<div id='div1'>
    <ul>
        <li><a href='#gone' id='gone' >gone</a></li>
        <li><a href='#gtwo' id='gtwo'>gtwo</a></li>
    </ul>
</div>

And javascript would be like.

$("#gone").trigger("click");

And binding click event like this

$("#gone").bind("click",function(event){
//your code.
});

If your ul li are dynamic then you can use like :

$('#div1 ul li').first().find("a").trigger("click");
like image 138
Amit Sharma Avatar answered Sep 24 '22 15:09

Amit Sharma


I would use first-child (DEMO):

init();
function init(){
    target = $('#div1 ul');
    target.on('click','a',function(){
        alert ($(this).attr('href'));
    });

    $('li:first-child a', target).trigger('click');
}
like image 22
Marcel Gwerder Avatar answered Sep 22 '22 15:09

Marcel Gwerder