Labanino Labanino - 2 years ago 52
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".

<div class="nav-one">
<div class="nav-two">


$(function() {
$(window).scroll(function() {
if ($(this).scrollTop() >= 1) {
} else {

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

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download