Question

When some div is clicked, a div is appended and ajax loads some data inside the newly created div, problem is that when a second click occurs on the div that causes the append, another div is created which is the duplicate of the previous div which still exists and visible creating clutter and disorder.

How do i stop a second click or destroy the first created div when the second one is created?

Javascript.

$(document).on('click', '.LibSectOpen', function() {
         var LibSect = ($(this).find('.SectionName').html())
         $(this).append('<div class="LibraryBooks BooksHolder"><img height="30" width="30" class="LibraryBooksGIF" src="../images/ic_loading.gif"></div>')
$.ajax({
    type:"POST",
    data: {data:LibSect},
    complete: function(){
    $('.LibraryBooksGIF, #QuickRead').fadeOut('slow')
    },
    url:"../php/books/Library_Load_Books.php"
    }).done(function(feedback){
    $('.LibraryBooks').html(feedback); 
});
});
Was it helpful?

Solution

Use .one()

$(document).one('click', '.LibSectOpen', function () {
    var LibSect = ($(this).find('.SectionName').html())
    $(this).find('.SectionName').empty()
    $(this).append('<div class="LibraryBooks BooksHolder"><img height="30" width="30" class="LibraryBooksGIF" src="../images/ic_loading.gif"></div>').load(function (e) {

    });
    $.ajax({
        type: "POST",
        data: {
            data: LibSect
        },
        complete: function () {
            $('.LibraryBooksGIF, #QuickRead').fadeOut('slow')
        },
        url: "../php/books/Library_Load_Books.php"
    }).done(function (feedback) {
        $('.LibraryBooks').html(feedback);
    });
});

Try a little more cleaner version

$(document).one('click', '.LibSectOpen', function () {
    var LibSect = ($(this).find('.SectionName').html())
    $(this).find('.SectionName').empty()
    var $libraryBooks = $('<div class="LibraryBooks BooksHolder"><img height="30" width="30" class="LibraryBooksGIF" src="../images/ic_loading.gif"></div>').appendTo(this);
    $.ajax({
        type: "POST",
        data: {
            data: LibSect
        },
        complete: function () {
            $('.LibraryBooksGIF, #QuickRead').fadeOut('slow')
        },
        url: "../php/books/Library_Load_Books.php"
    }).done(function (feedback) {
        $libraryBooks.html(feedback);
    });
});
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top