Andrey Drozdov Andrey Drozdov - 2 months ago 7
Javascript Question

JS(jQuery) make div not appear second time when scrolling

I'm only learning JS(jQuery), and so I have a question. I wrote script where div is being showed when user scroll page to bottom and I want to add close button, so the user click on it and it will not appear when user scroll to bottom again. So:

<script>
$(window).scroll(function() {
if($(window).scrollTop() > ($(document).height() - $(window).height() - 200)) {
$('#div-name').css('visibility', 'visible')
}
};

$('#close-button).click(function(){
$('#div-name').css('visibility', 'hidden')
});
</script>


Pretty simple, but I want close-button it hide forever(till refreshed or revisit) and scroll function don't show this div for second time.

So I thought, if I do like this:

<script>
var wasClosed = false;
if(!wasClosed) {
$(window).scroll(function() {
if($(window).scrollTop() > ($(document).height() - $(window).height() - 200)) {
$('#div-name').css('visibility', 'visible')
}
}
};

$('#close-button).click(function(){
wasClosed = true;
$('#div-name').css('visibility', 'hidden');
});
</script>


But I don't understand why it not working, it keep popup again and again after i clicked close button.

Answer

FYI: You have some syntax errors in your code - missing semicolons and a missing parenthesis.

Option 1: You can unregister the scroll listener after clicking the button. Then the function where you put the visibility to visible will not be called anymore at all. Of course this only works if you don't use any other scroll scripts.

$(window).scroll(function() {
   if($(window).scrollTop() > 
   ($(document).height() - $(window).height() - 200) ) {
     $('#div-name').css('visibility', 'visible');
   }
});

$('#close-button').click(function(){
  $('#div-name').css('visibility', 'hidden');
  $(window).off('scroll');
});

Fiddle: https://jsfiddle.net/kx6fkp7n/

Option 2: initialize a variable in which you save the status, if it has been closed already. As soon as the button is pressed, you set the variable to true and in the scroll listener you make sure that the visibility changing does not occur anymore by extending the condition.

var wasClosed = false;
$(window).scroll(function() {
  if(!wasClosed && $(window).scrollTop() > 
     ($(document).height() - $(window).height() - 200) ) {
    $('#div-name').css('visibility', 'visible');
  }
});

$('#close-button').click(function(){
  $('#div-name').css('visibility', 'hidden');
  wasClosed = true;
});

Fiddle: https://jsfiddle.net/6dk443zd/

Why is your code not working: The problem with your solution is that you placed the if-condition before registering the scroll handler. So once it's registered (which is actually always on every page load) you're actually doing nothing with the changed variable. The if condition would need to be placed inside the scroll listener as stated in option 2.

Comments