1

Im sure this is common problem when dealing with javascript, but I can't seem to find a solution for it.

Im trying to create two functions on a "card", but differentiated by a class of the state of the card.

One function to "start" the card and one function to "remove" the card. But when I start a card, Im not able to remove it with the same function.

jsfiddle example

html

<div class="card started">click to hide</div>
<div class="card not-started">click to start</div>

js

$(".card.not-started").on("click", function () {
    $(this).removeClass("not-started").addClass("started").html("click to hide");
});

$('.card.started').on("click", function () {
    $(this).fadeOut();
});
Tomas Jacobsen
  • 2,368
  • 6
  • 37
  • 81

2 Answers2

3

http://jsfiddle.net/wm99z4sj/1/

$(document).on("click", ".card.not-started", function () {
    $(this).removeClass("not-started").addClass("started").html("click to     hide");
});

$(document).on("click",'.card.started', function () {
    $(this).fadeOut();
});

Try it like this. If you use the document as a parent it will look for elements of that class added at runtime.

DasBeasto
  • 2,082
  • 5
  • 25
  • 65
0

A slight modification will solve this problem.

$(".card").on("click", function () {
    var el = $(this);
    if (el.hasClass("not-started")){
        el.toggleClass("not-started started").html("click to hide");
    } else {
        el.fadeOut();
    }
});

This way you will always delegate a click handler on .card but depending on the class you give it, it changes the functionality.

DEMO

If you want to keep 2 separate functions you can delegate from $(document.body) or $(".card").parent() like so:

var parent = $(".card").parent();
parent.on("click", ".not-started", function () {
    $(this).toggleClass("not-started started").html("click to hide");
});

parent.on("click", ".started", function(){
    $(this).fadeOut();
});

DEMO

Tim Vermaelen
  • 6,869
  • 1
  • 25
  • 39