0

I add an element with its own unique id using jquery and after that i want to chek a click event on that added element using its id.

Here is the code and it doesn't work for some reason.

I'm a new to this programming stuff, so maybe I don't see something obvious.

$(document).ready(function () {
        $("#type").click(function () {
            $(".footer").prepend('<div id="next">
                         <a id="next" href="#">
                         <img class="image" src="#" alt="next"></a></div>');
            $("#next").click(function () {
                $(".current")
                    .removeClass("current")
                    .addClass("done")
                    .next()
                    .removeClass("notdone")
                    .addClass("current");
            });
        }); 
apxcode
  • 7,696
  • 7
  • 30
  • 41
keshet
  • 1,716
  • 5
  • 27
  • 54
  • 1
    Use [**Event Delegation**](http://learn.jquery.com/events/event-delegation/) for dynamically created elements. You have `});` missing at the end your code should work – Satpal May 20 '14 at 07:40
  • 1
    Thanks, that link was helpful. – keshet May 20 '14 at 07:58

3 Answers3

0

USe event delegation for that,

$(document).on("click", "#next", function () {
    $(".current")
        .removeClass("current")
        .addClass("done")
        .next()
        .removeClass("notdone")
        .addClass("current");
});

This will bind events to dynamically created elements.

Anoop Joshi P
  • 25,373
  • 8
  • 32
  • 53
0

As you are dynamically adding the next element, you need event delegation:

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.

also you are prepending element with same id next on each click on type. replace with class as next and use:

  $('.footer').on("click", ".next", function () { 
              $(".current")
              .removeClass("current")
              .addClass("done")
              .next()
              .removeClass("notdone")
              .addClass("current");
          });
Milind Anantwar
  • 81,290
  • 25
  • 94
  • 125
0

try something like this

$("#type").click(function () {
    $(".footer").prepend('<div id="next"><a id="next" href="#"><img class="image" src="#" alt="next"></a></div>');
}); 
$(".footer").on('click','#next',function () {
    $(".current")
        .removeClass("current")
        .addClass("done")
        .next()
        .removeClass("notdone")
        .addClass("current");
});
rajesh kakawat
  • 10,826
  • 1
  • 21
  • 40