Martijn Zwanenburg
Martijn Zwanenburg

Reputation: 96

Run function after .append

I'm having the following html code:

<div>
   <div id="a"></div>
</div>

When the div with id="a" is clicked, I want to replace this div with the following div:

<div id="b"></div>

I managed to create the following fiddle: http://jsfiddle.net/ucant5uy/ In this fiddle, you can see that the first function (#a is clicked) runs perfect, but the second function (#b is clicked) doesn't run, because the div #b doesn't exist when the page is loaded.

Then I decided to put the second function inside the first function: http://jsfiddle.net/ucant5uy/2/. As you can see, you can click #a once, and #b once, and then the code stops working. I want to be able to click #a and #b as many times as I would like to. I know you can achieve this with some simple CSS tricks (adding both divs to the HTML and using display:none;), but I'm wondering wether it's possible to achieve the same thing using .append().

Thanks in advance!

Upvotes: 2

Views: 3284

Answers (2)

A.B
A.B

Reputation: 20445

use .on() for future elements event handler

$("div").on('click','div#b',function() {

        $(this).parent().append('<div id="a"></div>');
        $(this).remove();
    })

Demo:

$(document).ready(function() {
     $("div").on('click','div#a',function() {
        $(this).parent().append('<div id="b"></div>');
        $(this).remove();
    })
    
    $("div").on('click','div#b',function() {
       
        $(this).parent().append('<div id="a"></div>');
        $(this).remove();
    })
});
div {
    width:200px;
    height:200px;
    background:red;
}

#a, #b {
    width:100px;
    height:100px;
}

#a {
    background-color:green;
}

#b {
    background-color:blue;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
    <div id="a"></div>
</div>

Upvotes: 2

nicael
nicael

Reputation: 18997

You should bind the function to the parent div (and it is as main), which exist in the DOM and will exist, otherwise you can assign the function only to the elements, which already exist in DOM.

$(document).ready(function() {
        $('#main').on("click","#a",function() {
            $(this).parent().append('<div id="b"></div>');
            $(this).remove();
        })
        
        $('#main').on("click","#b",function() {
            $(this).parent().append('<div id="a"></div>');
            $(this).remove();
        })
    });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="main">
    <div id="a"></div>
</div>

Upvotes: 2

Related Questions