Imad
Imad

Reputation: 7490

JQuery - Event do not fire for element under some other element

I am facing a situation where I want to handle click event of li that is present under another element with class optWrapper. Most of these mark-up is generated due to third party javascript libraries. So, markup is something like

   <div class="optWrapper multiple open">
       <ul class="options">
           <li data-val="7"><span><i></i></span><label>Critical Illness</label></li>
          <li data-val="25"><span><i></i></span><label>Critical Illness Insurance</label></li>
         <li data-val="3"><span><i></i></span><label>Critical Illness Silver</label></li>
      </ul>
  </div>

and my jQuery code is

$(".optWrapper li").click(function () {
     alert();
 });

I can't find why this event is not getting called. Please help.

Edit 1

I am guessing this behavior is due to these element are loaded after jquery has downloaded in browser, is it that? if yes, than how could I tackle with it?

Edit 2 These element are dynamically generated after dropdownlist's select event.

Upvotes: 0

Views: 91

Answers (5)

Rajan Goswami
Rajan Goswami

Reputation: 769

Try this solution:

$(document).ready(function(){
    $(".optWrapper ul li").live('click', function(e){
        alert("eureka");
    });
});

Upvotes: 0

Lukabot
Lukabot

Reputation: 199

These element are dynamically generated after dropdownlist's select event.

Oops, your event listener attached before creation. As javascript event bubbles up target to document, you can handle that event by listening parent of them. See Direct and delegated events section

Attach event listener to the parent which don't generate dynamically.

$('#someparent').on("click","li.your_target",function(){
    alert();
});

Upvotes: 1

Andrew James Ramirez
Andrew James Ramirez

Reputation: 524

The answer of onsubject is correct. Saying to use .on instead of .click.

After jQuery 1.7 the preferred method is .on()

Addition on the answer of @onsubject , because his answer won't work, on dynamically created

".optWrapper li"

Instead of the actual element, use the body or its parent element.

$('body').on('click', '.optWrapper li', function() {
//do something
}

Upvotes: 1

onsubject
onsubject

Reputation: 41

You can use .on instead of .click

$(".optWrapper li").on("click", function () {
     alert();
});

See a working version here: http://codepen.io/ramiror/pen/zGeXPO

Upvotes: 0

Niralee Patel
Niralee Patel

Reputation: 151

Put your jquery code in $(document).ready(function (){}); It will work fine.

Upvotes: 0

Related Questions