Sunday, May 19, 2024
 Popular · Latest · Hot · Upcoming
124
rated 0 times [  131] [ 7]  / answers: 1 / hits: 25643  / 9 Years ago, tue, october 20, 2015, 12:00:00

I want to add a class .custom-menu-bg to sticky menu .custom-menu on scroll, while having overflow: hidden on body. Here's my code :



<script type=text/javascript src=css/jquery-1.7.2.min.js></script>
<script type=text/javascript>
var _rys = jQuery.noConflict();
_rys(document).ready(function() {
_rys(window).scroll(function() {
if (_rys(this).scrollTop() > 1) {
_rys('.custom-menu').addClass(custom-menu-bg);
} else {
_rys('.custom-menu').removeClass(custom-menu-bg);
}
});
});
</script>


But this code doesn't work with overflow: hidden on body tag
so I tried :



$('html').on('DOMMouseScroll', function(e) {
var delta = e.originalEvent.detail;
if (delta < 0) {
if ($('body').hasClass('section-element-1'))
$('.custom-menu').addClass(custom-menu-bg);
} else if (delta > 0) {
$('.custom-menu').removeClass(custom-menu-bg);
}
});


But this code only works for Mozilla and it's not a solution even, it's just a temp fix or work-around.



What I want is when I scroll down $('.custom-menu').addClass(custom-menu-bg); i.e. custom-menu-bg class gets added to custom-menu.



And when I scroll up to the top $('.custom-menu').removeClass(custom-menu-bg); i.e. custom-menu-bg class gets removed from custom-menu.



The top of body,document,window etcetera is always 0.
And top of my div with class custom-menu also has top: 0 always.



I'm looking for a permanent solution which works on all browsers.


More From » jquery

 Answers
217

I've reproduced the same effect you wanted HERE.



The only change that I've brought in comparison to your code is that I've made a makeshift body div and applied overflow: hidden on it.



Then, using jQuery, you'll be checking for the scroll event triggered by a wrapper inside the body div - which is in charge of holding the content) - and not by itself (or even document).



$('.wrapper').scroll(function () {
if ($(this).scrollTop() > 0) {
$('.custom-menu').addClass(custom-menu-bg);
} else {
$('.custom-menu').removeClass(custom-menu-bg);
}
});


This is because the makeshift body div has an overflow property set to hidden, and therefore won't generate that particular scroll event (maybe it would if you had the handler registered using browser-specific scroll events). Whereas the inner wrapper div will always have it's height property determined by it's content and is therefore scrollable.



NOTE: jQuery's scroll() is cross-browser, and hence a permanent solution.


[#64679] Friday, October 16, 2015, 9 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
yosefleod

Total Points: 113
Total Questions: 100
Total Answers: 115

Location: Egypt
Member since Tue, May 3, 2022
2 Years ago
;