I have a stickUp script that locks the menu on skrule and adds the isStuck class to this menu, which is responsible for position: fixed. I have a task: add a block with arbitrary content to the menu only when the isStuck class appears (when we scroll the page and the menu is fixed).

Tried to do so did not help:

$('.isStuck').html( "<p>Test</p>" ); 

So:

 $('.isStuck').append( "<p>Test</p>" ); 

And even so, but here the content appears endlessly:

 $(window).scroll(function() { if($(this).scrollTop() >= 190) { $('.isStuck').append( "<p>Test</p>" ); } else { $('.isStuck').remove( "<p>Test</p>" ); } }); 

    1 answer 1

    You have if($(this).scrollTop() >= 190) works constantly, and therefore the infinite addition goes.

    If you use your code, then you need to add an indicator that the block already exists.

     var isStuckBlockAdded = false; ... $(window).scroll(function() { if($(this).scrollTop() >= 190) { if (!isStuckBlockAdded) { isStuckBlockAdded = true; $('your-block-selector').append( "<p class="new-block">Test</p>" ); //your-block-selector - селектор для элемента, //в который нужно добавить блок //(убрал .isStuck, т.к. неизвестно к этому моменту будет ли класс уже добавлен) } } else { if (isStuckBlockAdded) { $('your-block-selector .new-block').remove(); //your-block-selector - селектор для элемента, //из которого нужно удалить блок //(убрал .isStuck, т.к. неизвестно к этому моменту не будет ли класс уже удален) isStuckBlockAdded = false; } } }); 

    Although I would suggest using events

     var Events = { StuckClassAdded = "StuckClassAdded" }; ... //Где-то в инициализации $(Events).on(Events.StuckClassAdded, function() { $('.isStuck').append( "<p>Test</p>" ); }); ... // Там где добавляете класс $(Events).trigger(Events.StuckClassAdded); ... 

    Removal is similar.

    • one
      isStuckBlockAdded is not set anywhere in the example - this flag is always false - Grundy
    • @Grundy sorry missed. Thank you for your comment. The result was really grief counselor :-) Corrected. - Evgenii Izhboldin 2:58 pm
    • The first option does not remove. The second option does not work. - Alexander
    • @ Alexander, yes, I apologize, I overlooked it again, of course $('.isStuck') will not work, because by this time you most likely have already deleted the class, try your other selector to use, which can identify the element. According to the second option, you need to look at how you are done, this is just a recommendation. - Evgenii Izhboldin