0

I have the follow code in a js file:

    $(".dropmenu").on("click", function(event){
      event.preventDefault();
      $(this).parent().find("ul").slideToggle();
    });

And i have the follow code in my webpage:

var append="<ul>";

$.each(items, function(i, v){
  append += "<li><a class='dropmenu' href='#'> Option </a>" +
              "<ul>" +
                 "<li><a href='somelink'>somelink</a></li>" +
              "</ul></li>";

}

$("div").append(append);

The point is when my ul tag its filled, the click event doesn't fire. I think because the class into anchor is dynamic.

How can I add the click event after the append function?

ngrashia
  • 9,869
  • 5
  • 43
  • 58
elchente23
  • 163
  • 5
  • 13
  • See how delegated event handling works to solve the issue of dynamically created elements: [Adding a click event for dynamic html](http://stackoverflow.com/questions/8752321/jquery-live-vs-on-method-for-adding-a-click-event-after-loading-dynamic-ht/8752376#8752376) and [Does jQuery.on() work for elements that are added after the event handler is created?](http://stackoverflow.com/questions/9814298/does-jquery-on-work-for-elements-that-are-added-after-the-event-handler-is-cre/9814409#9814409). – jfriend00 Jun 05 '14 at 05:25

3 Answers3

2

Use this .on() is used for delegation. Using .delegate() is an alternative.

As your <ul> element is getting appended dynamically, you have to delegate the event using $(document) of any other static parent element.

$(document).on('click','.dropmenu', function(event){
  event.preventDefault();
  $(this).parent().find("ul").slideToggle();
});

Demo Fiddle

Shaunak D
  • 20,588
  • 10
  • 46
  • 79
0

Use event delegation for attaching events to dynamically added DOM.

Event delegation allows us to attach a single event listener, to a parent element, that will fire for all descendants matching a selector, whether those descendants exist now or are added in the future.

 $("body").on('click','.dropmenu', function(event){
  event.preventDefault();
  $(this).parent().find("ul").slideToggle();
});
Milind Anantwar
  • 81,290
  • 25
  • 94
  • 125
-1

do you put your code in $(document).ready i put it into and its working fine DEMO

  • it's working for you cause you attached the click event after appending the elements... that means the element is present already :D – Reigel Gallarde Jun 05 '14 at 05:05