jQuery changed ID won't run function

css, html, javascript, jquery

Solution

You need to use event delegation -- your `click` handlers are bound to the matching elements at the time the code is first run, and only then. Since there's no `#Red` element at that point in time, that second click handler isn't bound to anything.

$(document).on('click',"#Blue", function(){
    $("#Blue").attr("id","Red");
});

$(document).on('click',"#Red", function(){
    $("#Red").attr("id","Blue");
});

http://jsfiddle.net/mblase75/HDFyn/

http://api.jquery.com/on

That said, the "proper" way to do this would be to add and remove a class, not change the ID:

$('#btn').on('click', function(){
    $(this).toggleClass("red blue");
});

http://jsfiddle.net/mblase75/mKMW6/

Problem

I'm trying to make a blue div that turns red when clicking on it and the red div turns back to blue ( so I can add more events on the click after clicking, so .css isn't really an option) When clicking on the div when it's blue, it turns red. But when I click the red div it doesn't respond, even when I add a simple alert() Does anyone know what I'm doing wrong? This is my current code and a JSFiddle code: ``` $("#Blue").click(function(){ $("#Blue").attr("id","Red"); }); $("#Red").click(function(){ $("Red").attr("id","Blue"); }); ``` If anyone could tell me what Exactly I'm doing wrong that would be great, thank you in advance

Original source