I'm trying to click add and the content of add will appear for the first time.
After it's added, I want to click add and it will only toggle "added", instead of adding "added" on each click
Jquery:
$(function(){
    var NewContent='<div class="added">Added</div>'
    $(".add").click(function(){
        $("#spin").after(NewContent);
    });
});
HTML:
<span class="add">add</span>
<span id="spin"></span>
Here's a Fiddle: http://jsfiddle.net/Abgec/
$(function(){
    //start with `NewContent` being the HTML to add to the page
    var NewContent='<div class="added">Added</div>'
    $(".add").click(function(){
        //check if `NewContent` is empty or not
        if (NewContent != '') {
            //if `NewContent` is not empty then add it to the DOM
            $("#spin").after(NewContent);
            //now that `NewContent` has been added to the DOM, reset it's value to an empty string so this doesn't happen again
            NewContent = '';
        } else {
            //this is not the first click, so just toggle the appearance of the element that has already been added to the DOM
            //since we injected the element just after the `#spin` element we can select it relatively to that element by using `.next()`
            $('#spin').next().toggle();
        }
    });
});
Here is a demo: http://jsfiddle.net/7yU3n/
Docs for .toggle(): http://api.jquery.com/toggle/
I little different approach, replacing the click event after its first firing,
$(function(){
    var NewContent='<div class="added">Added</div>'
    $(".add").one('click', function(){
        var $content = $(NewContent).insertAfter('#spin');
        $(this).click(function(){
            $content.toggle();
        });
    });
});
http://jsfiddle.net/Abgec/3/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With