jQuery append only once

13,941

Solution 1

just use a boolean,

jQuery("document").ready(function($){

    var nav = $('#nav');
    var logo = '<img id="lilLogo" src="img/logo.png" />';
    var visible = false;

    $(window).scroll(function () {
            if ($(this).scrollTop() > 136) {
                nav.addClass("nav-f");
                if(!visible) {
                    nav.append(logo);
                    visible = true;
                }
            } else {
                nav.removeClass("nav-f");
                if(visible)  {
                    $('#lilLogo').remove();
                    visible = false;
                }
            }
        });
    });

fiddle

The alternative is to check with $('#lilLogoID').is(':visible'), however this would then do a search for img and check visible on every event (which would be slow)

Solution 2

jQuery("document").ready(function($){

var nav = $('#nav');
var logo = '<img id="lilLogo" src="img/logo.png" />';    
$(window).scroll(function () {
    if ($(this).scrollTop() > 136) {
        nav.addClass("nav-f");  
        if (!$(".nav-f").find('#lilLogo').length) {
        nav.append(logo);
        }
    } else {

        nav.removeClass("nav-f");
            nav.remove(logo);

    }
});
});
Share:
13,941

Related videos on Youtube

vjordanov
Author by

vjordanov

www.vjordanov.com

Updated on October 23, 2022

Comments

  • vjordanov
    vjordanov over 1 year

    So I have this:

    jQuery("document").ready(function($){
    
    var nav = $('#nav');
    var logo = '<img src="img/logo.png" />';
    
    $(window).scroll(function () {
        if ($(this).scrollTop() > 136) {
            nav.addClass("nav-f");
            nav.append(logo);
        } else {
            nav.removeClass("nav-f");
            nav.remove(logo);
        }
    });
    
    });
    

    When scrolling I'm trying to make the navigation to be fixed, which works, but I also want to add a tag with the logo image in the #nav div, which also works but it appends on every scroll so when scrolling I get like 100 images of the logo.

    How can I make it to append only once and when it's not scrolled more than 136px to be removed?

    • Karl-André Gagnon
      Karl-André Gagnon
      Instead of var logo = '<img src="img/logo.png" />';, use var logo = $('<img src="img/logo.png" />');