简体   繁体   中英

Show div on scroll 200px but hide it on click

I have a div element #offer that is hidden by default and that is displayed on scrolling 200px from top, the div is being hidden once a user scrolls up again.

The following code does this just alright:

$(document).scroll(function () {
    var y = $(this).scrollTop();   
    if (y > 100) {
        $('#offer').fadeIn();
    } else {
        $('#offer').fadeOut();
    }
});

I would like to add an option to hide the div manually simply by clicking on #hide-now div . I have tried to use the following piece of code. Even though this hides the div #offer, the div is being displayed immediately again (because the scroll distance from top is more than 200px). What tweak in a code do I need to do to get this working?

$(document).ready(function() {
$("#hide-now").live('click', function () { 
$("#offer").slideUp("slow");
});
}); 

Any ideas how to solve this? Thanks in advance for your help.

I'd add a class to the div once it's been hidden, and then check if that class exists inside the scroll event handler. Try this out:

$(document).ready(function() {
  $("#hide-now").live('click', function () { 
    $("#offer").slideUp("slow").addClass("manually_hidden");;
  });
}); 

Then inside the scroll handler:

$(document).scroll(function () {
  var y = $(this).scrollTop();   
  if (!$("#offer").hasClass("manually_hidden")) {
    if (y > 100) {
        $('#offer').fadeIn();
    } else {
        $('#offer').fadeOut();
    }
  }
});   

Hope this helps! Also, I agree w/ the other comment to avoid using .live - .on or just a .click ought to do it.

So create a Boolean (for example, show ) and check that Boolean before you perform the fadeIn action for your scroll handler.

So,

var show = true;
$(document).scroll(function () {
    var y = $(this).scrollTop();   
    if (y > 100) {
      if(show){
        $('#offer').fadeIn();
      }
    } else {
        $('#offer').fadeOut();
    }
});

Then, if they click ,

$(document).ready(function() {
  $("#hide-now").live('click', function () { 
    $("#offer").slideUp("slow");
    show = false;
  });
}); 

As with the others, I recommend using on instead of live .

Set a flag when #offer is manually hidden (say, with a class):

$(function() {
    $("#hide-now").on('click', function () { 
        $("#offer").slideUp("slow").addClass('hidden');
    });
});

Then check for the flag:

$(document).scroll(function () {
    var y = $(this).scrollTop();   
    if ( ! $(this).hasClass('hidden') ) {
        if (y > 100) {
            $('#offer').fadeIn();
        } else {
            $('#offer').fadeOut();
        }
    }
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM