WinterTime
WinterTime

Reputation: 183

Buttons change each other

Good evening!

I have a problem with conversion html code into new one, then go back by pressing new created button to the old one.

Problem is that when you press the button that one will convert into new one, but when I press again (new created code) it is not going back to the old one even when created code is correct (I mean id's).

There is my HTML code:

<div id="me_div">
    <a href="#" id= "me" class="btn btn-success">me</a>
</div>

And JavaScript:

$(function() {
    $('#me').click(function() {
        alert("Here I am!");
        $("#me_div").html('<a href="#" id= "noob" class="btn btn-danger">noob</a>');
        document.getElementById("me_div").setAttribute("id", "noob_div");
    });

    $('#noob').click(function() {
        alert("Im noob with JS.");
        $("#noob_div").html('<a href="#" id= "me" class="btn btn-success">me</a>');
        document.getElementById("noob_div").setAttribute("id", "me_div");
    });
});

Upvotes: 0

Views: 45

Answers (2)

Tom Rees
Tom Rees

Reputation: 671

When that function executes, there is no #noob to bind to. You need to run the bind code every time the DOM is altered, eg.:

$(function() {
    window.bindToMe = function() {
        $('#me').click(function() {
            alert("Here I am!");
            $("#me_div").html('<a href="#" id= "noob" class="btn btn-danger">noob</a>');
            document.getElementById("me_div").setAttribute("id", "noob_div");
            bindToNoob();
        });
    }

    window.bindToNoob = function() {
        $('#noob').click(function() {
            alert("Im noob with JS.");
            $("#noob_div").html('<a href="#" id= "me" class="btn btn-success">me</a>');
            document.getElementById("noob_div").setAttribute("id", "me_div");
            bindToMe();
        });
    }

    bindToMe();
});

Upvotes: 1

Clint Powell
Clint Powell

Reputation: 2398

Tom Rees answer will fix your problem, but consider rethinking your solution. Don't destroy and create new HTML every time a button is clicked and re-assign IDs! Why not show/hide?

http://jsfiddle.net/agmr2ytd/

$(function() {
    $('#me').click(function() {
        alert("Here I am!");
        $("#me_div").hide();
        $("#noob_div").show();
    });

    $('#noob').click(function() {
        alert("Here I am!");
        $("#noob_div").hide();
        $("#me_div").show();
    });
});

Upvotes: 1

Related Questions