1

I have two simple jQuery functions, one standard dropdown function and another function that appends HTML content on click. The problem is that the dropdown function does not work with the appended HTML.

Here's my HTML:

<a href="#" id="new_line">New Line</a>

<ul class="lines">

   <li>
     <a href="#" class="dropdown-toggle">Popup</a> 
     <ul class="dropdown-menu" style="background: #000; padding: 10px; display:none;">ddd
     </ul>
  </li>

</ul>

And the jQuery functions:

$(function() {

   $('.dropdown-toggle').click(function(){

      $('.dropdown-menu').not($(this).next('.dropdown-menu')).hide();
      $(this).next('.dropdown-menu').toggle();
      });

});

$(document).ready(function() {
   var wrapper = $(".lines");
   var add_button = $("#new_line");

   $(add_button).click(function(){ 

        $(wrapper).append('<li><a href="#" class="dropdown-toggle">Popup</a> <ul class="dropdown-menu" style="background: #000; padding: 10px; display:none;">ddd</ul></li>'); 
   });

});

Please check the following example on codepen. You'll see one "dropdown" link which works. Once you click on "New Line" new dropdown links will appear, but those do not work. Any idea how to make them work?

Thanks!

http://codepen.io/anon/pen/yYgNLM

Frank
  • 584
  • 1
  • 7
  • 30

3 Answers3

3

You need to delegate the events on dynamically loaded elements. Please use this:

$(".lines").on("click", '.dropdown-toggle', function() {
Praveen Kumar Purushothaman
  • 154,660
  • 22
  • 177
  • 226
0

It's not working because you're attaching the event handlers to the controls that exist when you select them and attach the handlers. When you add a new link, the selector is not re-evaluated, so no handler get attached to it.

What you need to do is to use delegated events: the technique consist in handling the event from the container when it bubbles up, instead of handling on the controls themselves. So, when you add new controls to this containers, their events will also be handled.

You can do it with jQuery's .on().

JotaBe
  • 34,736
  • 7
  • 85
  • 109
0

use

$(document).ready(function() {
var wrapper = $(".lines");
var add_button = $("#new_line");

$(add_button).click(function() {

$(wrapper).append('<li><a href="#" class="dropdown-toggle">Popup</a> <ul class="dropdown-menu" style="background: #000; padding: 10px; display:none;">ddd</ul></li>');

$('.dropdown-toggle:last').click(function() {
  $('.dropdown-menu').not($(this).next('.dropdown-menu')).hide();
  $(this).next('.dropdown-menu').toggle();
});
  });

});

check here working exemple

Sebri Zouhaier
  • 725
  • 7
  • 18