Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jquery: Append div only once 'on click'

I am trying to append a section to a div on the click of a button.

I want the section to be appended only on the first click, the code that I use below appends a section every time I click the div.

How should I go about this?

$("#nextractorapply").click(function () {
    $("#main").append('<section id="nextractor" class="five"> </section>');  
});
like image 881
Tauseef Hussain Avatar asked Dec 27 '15 00:12

Tauseef Hussain


3 Answers

You could use one(), which fires only once

$("#nextractorapply").one('click', function () { 
    // executes only once

     $("#main").append('<section id="nextractor" class="five"> </section>');  
});

$("#nextractorapply").on('click', function () { 
    // executes every time

    // do other stuff
});
like image 185
adeneo Avatar answered Oct 29 '22 13:10

adeneo


Use a conditional to determine if it's there.

$("#nextractorapply").click(function () {
    if($('#nextractor').length < 0){
        $("#main").append('<section id="nextractor" class="five"> </section>');
    }  
});
like image 38
Donnie D'Amato Avatar answered Oct 29 '22 14:10

Donnie D'Amato


You can use some kind of a condition that prevents its appending multiple times.

var counter=0;
$("#nextractorapply").click(function () {
    if(counter<=0){
        $("#main").append('<section id="nextractor" class="five"> </section>');  
        counter++;
    }

    //YOUR OTHER STUFF THAT YOU NEED TO EXECUTE ON EVERY CLICK
});
like image 8
Hemal Avatar answered Oct 29 '22 15:10

Hemal