Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Click li element programmatically

I would like to click a li tag when page loads but it is not working. HTML:

 <div id="listDiv">
    <ul id="listUL" class="listUL">
        <li id="f1" class="listDynamic">Term1</li>
        <li id="f2" class="listDynamic">Term2</li>
        <li id="f3" class="listDynamic" >Term3</li>  
    </ul>   
</div>     

JavaScript:

$("#listUL").find("li#f1").click(function() {
                alert("clicked:" + this.id);
            });
$("#listUL").find("li#f1").trigger("click");

/*
 I also tried 
 $( document ).ready(function() {
    $("#listUL").find("li#f1").trigger("click");
});

*/

http://jsfiddle.net/hx20d87m/4/

like image 842
user1546784 Avatar asked Oct 01 '15 17:10

user1546784


2 Answers

$(function() {
    $("li#f1").click(function() {
        alert("clicked:" + this.id);
    });

    $("li#f1").trigger("click");
});

https://jsfiddle.net/yz8owa76/

like image 129
Dmytro Shevchenko Avatar answered Sep 23 '22 23:09

Dmytro Shevchenko


If you interest do it via Javascript:

var list = document.getElementById("listUL");
function Alert(){
  console.log(this.id);
  alert(this.id);
  }
console.log(list);
for(i=0;i<=list.childElementCount-1;i++){
  list.children[i].addEventListener("click",Alert);
  }
<div id="listDiv">
    <ul id="listUL" class="listUL">
        <li id="f1" class="listDynamic">Term1</li>
        <li id="f2" class="listDynamic">Term2</li>
        <li id="f3" class="listDynamic" >Term3</li>  
    </ul>   
</div>  
like image 27
Mostafa Avatar answered Sep 25 '22 23:09

Mostafa