user1937021
user1937021

Reputation: 10801

How to only append once when loading in html Ajax

I loading in content from a JSON file in a lightbox I have created. The light box opens up another html. In that html I append data loaded in from the JSON file to various elements. However I only want to append once when they open the lightbox, how can I do this?

$(document).on('click', '.mch-overlay-info', function(e){
    e.preventDefault();
    var href = $(this).attr('href');
    $('#mch-overlay-content').html('');
    $('#mch-overlay').fadeIn(300);
    $('#mch-overlay-content').load(href, function() {
        showInfo(); 
    });
});

function showInfo(){

        $(".start .text3").append(data[lang]['startpage']['text3']);
        $(".start .text4").append(data[lang]['startpage']['text4']);
        $(".start .text5").append(data[lang]['startpage']['text5']);

}

Upvotes: 0

Views: 382

Answers (1)

JakeCataford
JakeCataford

Reputation: 141

I'm assuming your problem is that every time they click it appends? Two options:

  1. Don't append it. just use $().html() to set the content and replace the old content.
  2. Control with a variable

    var hasBeenAppended = false;
    
    //etc...
    
    function showInfo(){
        if(!hasBeenAppended) {
            hasBeenAppended = true;
            $(".start .text3").append(data[lang]['startpage']['text3']);
            $(".start .text4").append(data[lang]['startpage']['text4']);
            $(".start .text5").append(data[lang]['startpage']['text5']);
        }
    
    }
    

Upvotes: 2

Related Questions