Labanino Labanino - 6 months ago 7
Javascript Question

Removing and adding element in jquery not working as expected

I'm adding a sticky menu. The way I'm doing it is removing one and showing the other when scroll. It looked fine at first but then I realize that it is swapping the elements but not the content inside of them. Pay attention to the titles, "This is my red menu".

<nav>
<div class="nav-one">
<p>THIS IS MY RED MENU</p>
</div>
<div class="nav-two">
<p>THIS IS MY GREEN MENU</p>
</div>
</nav>


$('.nav-two').hide();

$(function() {
$(window).scroll(function() {
if ($(this).scrollTop() >= 1) {
$('.nav-one').removeClass('nav-one').addClass('nav-two');
} else {
$('.nav-two').removeClass('nav-two').addClass('nav-one');
}
});
});


What am I doing wrong? If you think it can be done differently, please let me know. This is my jsfiddle.

Answer

All your code is doing is switching around classes on the nav-* elements. It doesn't change the text, nor the visible element at all. From your description of what you want to have happen you should instead be hiding/showing the relevant .nav-* element based on the current scrollTop of the window, which you can achieve using toggle(), like this:

$(window).scroll(function() {
    $('.nav-one').toggle($(this).scrollTop() == 0);
    $('.nav-two').toggle($(this).scrollTop() >= 1);
});
.nav-two {
    /* other styling rules here... */
    display: none;
}

Working example

Note that I moved the hiding of the .nav-two element to the CSS to avoid a FOUC.

Comments