Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add div on click, then toggle it on every click after that

  1. I'm trying to click add and the content of add will appear for the first time.

  2. 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/

like image 694
Wonka Avatar asked Dec 22 '22 01:12

Wonka


2 Answers

$(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/

like image 123
Jasper Avatar answered Feb 01 '23 23:02

Jasper


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/

like image 26
Andrew Avatar answered Feb 02 '23 01:02

Andrew