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.
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.
You can bind on any id or on class also . its on you for now demo i
am using window .
This single event works for both if you have scroll or not. i.e overflow:hidden or overflow:scroll
$(window).bind('mousewheel DOMMouseScroll', function(event){
if (event.originalEvent.wheelDelta > 0 || event.originalEvent.detail < 0) {
// scroll up
$('.custom-menu').removeClass("custom-menu-bg");
}
else {
// scroll down
$('.custom-menu').addClass("custom-menu-bg");
}
});
.custom-menu {
background-color: black;
height: 100px;
width: 100%
}
.custom-menu-bg{
background-color: green;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="custom-menu">
</div>
Or you can also use this jQuery mousewheel plugin https://github.com/brandonaaron/jquery-mousewheel.
//toggled is class when mobile menu is opened
let moveScroll = '';
window.onscroll = function (e) {
const navBar = document.getElementById('id-of-your-navigation-bar');
if (moveScroll > 0 && navBar.classList.contains('toggled')) {
navBar.classList.remove('toggled');
moveScroll = 0;
} else if (navBar.classList.contains('toggled')) {
moveScroll = 1;
}
};
Related
I have a custom icon element that is only displayed when its specific row in the table is hovered over, but when I scroll down without moving my mouse it doesn't update the hover and maintains the button on the screen and over my table's header. How can I make sure this doesn't happen?
export const StyleTr = styled.tr`
z-index: ${({ theme }) => theme.zIndex.userMenu};
&:hover {
background-color: ${({ theme, isData }) =>
isData ? theme.colors.primary.lighter : theme.colors.white};
div {
visibility: visible;
}
svg[icon] {
display: initial;
}
}
`;
I was just working on something similar to this for a web scraper recently.
Something like this should work:
function checkIfIconInViewport() {
// define current viewport (maximum browser compatability use both calls)
const viewportHeight =
window.innerHeight || document.documentElement.clientHeight;
//Get our Icon
let icon = document.getElementById('icon');
let iPos = icon.getBoundingClientRect();
//Show if any part of icon is visible:
if (viewportHeight - iPos.top > 0 && iPos.bottom > 0) {
icon.style.visibility = visibile;
}
else { icon.style.visibility = hidden; }
//Show only if all of icon is visible:
if (iPos.bottom > 0 && iPos.top >= 0) {
{
icon.style.visibility = visibile;
}
else { icon.style.visibility = hidden; }
//Add && iPos.bottom <= viewportHeight to the if check above for very large elements.
{
//Run function everytime that the window is scrolled.
document.addEventListener('scroll', checkIfIconInViewport);
Basically, every time a scroll event happens, we just check to see if the top & bottom of our element (the icon in your case) are within the bounds of the viewport.
Negative values, or values greater than the viewport's height mean that the respective portion of the element is outside the viewport's boundary.
Hopefully this helps! If you are dealing with a large quantity of objects, it may make sense to bundle the objects you are tracking together into an array and check each of them in a single function call to avoid saving function definitions for each individual object.
Edit: I just realized that I misunderstood your issue a bit. I think you can get by with just the bottom part of the code, and when a scroll event happens, set the icon's visibility to hidden. Assuming you want to hide it whenever the user scrolls?
Have you tried getting the scroll position of the DOM, then disabling (removing) the element once a certain scroll position is reached?
I'm implementing slide div for creating theme color. It works fine but when I click the outside it's not closing that div and I tried a lot but not working my code so help me out for this..and I research many resources from the internet I got, but don't know how to implement this. here is my code
function clickedThemebtn() {
var ele = document.getElementsByClassName("theme-colors")[0];
if (ele.classList.contains("shown")) {
ele.classList.remove("shown");
} else {
ele.classList.add("shown");
}
}
Here is my fiddle you can Check Here
Please check this fiddle out.
My approach here was to add an fixed positioned div which will occupy the entire screen and it will handle clicking outside.
HTML Outline
<div class='toggleclickoutside' onClick="handleOutsideClick()"></div>
<div id="toggleshown" class="theme-colors">...</div>
JS handler for outside click
function handleOutsideClick() {
var ele = document.getElementsByClassName("theme-colors")[0];
if (ele.classList.contains("shown")) {
ele.classList.remove("shown");
}
}
Css for new div
.toggleclickoutside{
position: fixed;
width: 100vw;
height: 100vh;
top: 0px;
left: 0px;
}
You can attach an event listener to the document, that it triggers the close event. Keep in mind that the following will hide the menu when you click anywhere inside the menu. You need further checks to prevent it.
function clickedThemebtn(e) {
var ele = document.getElementsByClassName("theme-colors")[0];
// If the click is outside of the button, remove the class
if (e.target.id === "slideBtn") {
if (ele.classList.contains("shown")) {
ele.classList.remove("shown");
} else {
ele.classList.add("shown");
}
return;
}
// all other cases: outside the button
ele.classList.remove("shown");
}
document.addEventListener('click', clickedThemebtn);
Updated fiddle
Here's a jQuery solution since the fiddle had jQuery fiddle
You'd have to listen for the click event on the document object, then check if the click was within the theme selector before closing it.
document.addEventListener('click', handleDocumentClick);
function handleDocumentClick(event) {
const themeSelector = getThemeSelector();
if (!themeSelector.contains(event.target)) {
hideThemeSelector();
}
}
function getThemeSelector() {
return document.getElementsByClassName("theme-colors")[0];
}
function hideThemeSelector() {
const themeSelector = getThemeSelector();
themeSelector.classList.remove("shown");
}
function showThemeSelector() {
const themeSelector = getThemeSelector();
themeSelector.classList.add("shown");
}
Note that I added a few handy functions for convenience sake.
I updated your fiddle and now it looks like this: https://jsfiddle.net/0nqzpyko/
I've got two navbars, the second becomes sticky once it hits the top of the viewport, the problem I'm having is getting it to 'unstick' when the div above which contains the original navbar comes back into the viewport so the first navbar can be seen again .
Sorry for the terrible explanation and vague title, had trouble trying to thing of how to describe it.
Here's a jsfiddle which will give you a much better idea of what I mean, any help would be appreciate as I'm pretty poor when it comes to javascript, thanks.
(HTML and CSS in jfiddle)
$('#nav2').attr("attop", false);
var lastScrollTop = 0;
$(window).on('scroll', function() {
var windowScrollTop = $(this).scrollTop();
if (windowScrollTop > lastScrollTop) {
var header = $('#nav2[attop="false"]:first');
if (header && header.length > 0) {
if (windowScrollTop >= header.offset().top) {
header.attr('attop', true);
$('#nav2').addClass('sticky');
}
}
}
lastScrollTop = windowScrollTop;
});
});
````
There is a nice solution in Bootstrap 4 and I use it on a few sites. The only thing you need to do is to add this class to the navbar. Check out the snippet below.
Notice that in order for position sticky to work correctly this class can't be added to an element inside a container, you must add this class to the container itself.
#supports ((position: -webkit-sticky) or (position: sticky)) {
.sticky-top {
position: -webkit-sticky;
position: sticky;
top: 0;
z-index: 1020;
}
}
/*DEMO PURPOSE*/
nav{background:red;padding-top:1rem;padding-bottom:1rem}
.section-1{height:300px}
.section-2{height:1000px}
<div class="section-1">Section 1</div>
<nav class="sticky-top">Lorem Ipsum</nav>
<div class="section-2">Section 1</div>
Im creating a fixed header where on load, the logo is flat white. On scroll, it changes to the full color logo.
However, when scrolling back to the top, it stays the same colored logo instead of going back to white.
Here's the code (and a pen)
$(function() {
$(window).scroll(function() {
var navlogo = $('.nav-logo-before');
var scroll = $(window).scrollTop();
if (scroll >= 1) {
navlogo.removeClass('.nav-logo-before').addClass('nav-logo-after');
} else {
navlogo.removeClass('.nav-logo-after').addClass('nav-logo-before');
}
});
});
http://codepen.io/bradpaulp/pen/gmXOjG
There's a couple of things here:
1) You start with a .nav-logo-before class but when the logo becomes black you remove that class and then try to get the same element using a class selector that doesn't exist anymore
2) removeClass('.nav-logo-before') is different than removeClass('nev-logo-before), notice the "." in the first selector.
3) You get the element using the $('.selector')in every scroll event, this can be a performance issue, it's better to cache them on page load and then use the element stored in memory
4) It's not a good practice to listen to scroll events as this can be too performance demanding, it's usually better to use the requestAnimationFrame and then check if the scroll position has changed. Using the scroll event it could happen that you scroll up really fast and the scroll event doesn't happen at 0, so your logo won't change. With requestAnimationFrame this can't happen
$(function() {
var navlogo = $('.nav-logo');
var $window = $(window);
var oldScroll = 0;
function loop() {
var scroll = $window.scrollTop();
if (oldScroll != scroll) {
oldScroll = scroll;
if (scroll >= 1) {
navlogo.removeClass('nav-logo-before').addClass('nav-logo-after');
} else {
navlogo.removeClass('nav-logo-after').addClass('nav-logo-before');
}
}
requestAnimationFrame(loop);
}
requestAnimationFrame(loop);
});
body {
background-color: rgba(0,0,0,.2);
}
.space {
padding: 300px;
}
.nav-logo-before {
content: url(https://image.ibb.co/kYANyv/logo_test_before.png)
}
.nav-logo-after {
content: url(https://image.ibb.co/jYzFJv/logo_test_after.png)
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<img class="nav-logo nav-logo-before">
</div>
<div class="space">
</div>
Dont need to add the dot . in front of the class name in removeClass and addClass:
Use this:
navlogo.removeClass('nav-logo-before')
Secondly, you are removing the class that you are using to get the element in the first place.
I have an updated codepen, see if this suits your needs: http://codepen.io/anon/pen/ZeaYRO
You are removing the class nav-logo-before, so the second time the function runs, it can't find any element with nav-logo-before.
Just give a second class to your navlogo element and use that on line 3.
Like this:
var navlogo = $('.second-class');
working example:
http://codepen.io/anon/pen/ryYajx
You are getting the navlogo variable using
var navlogo = $('.nav-logo-before');
but then you change the class to be 'nav-logo-after', so next time the function gets called you won't be able to select the logo using jquery as it won't have the '.nav-logo-before'class anymore.
You could add an id to the logo and use that to select it, for example.
Apart from that, removeClass('.nav-logo-before') should be removeClass('nav-logo-before') without the dot before the class name.
The problem is that you removes nav-logo-before and then you want to select element with such class but it doesn't exist.
I've rafactored you code to avert it.
Another problem is that you uses dot in removeClass('.before') while it should be removeClass('before') - without dot
$(function() {
var navlogo = $('.nav-logo');
$(window).scroll(function() {
var scroll = $(window).scrollTop();
if (scroll >= 1) {
navlogo.removeClass('before').addClass('after');
} else {
navlogo.removeClass('after').addClass('before');
}
});
});
body {
background-color: rgba(0,0,0,.2);
}
.space {
padding: 300px;
}
.before {
content: url(https://image.ibb.co/kYANyv/logo_test_before.png)
}
.after {
content: url(https://image.ibb.co/jYzFJv/logo_test_after.png)
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<img class="nav-logo before">
</div>
<div class="space">
</div>
I'm trying to adapt this JSFiddle to make the menu button on my website hide when I'm at the top of the page and show when I start scrolling down.
I modified the JS to match the CSS on my site. Then I placed it in tags in the head of my page
var $scb = $('<div class="toggle-menu-wrap"></div>');
$('.top-header').append($scb);
var $ccol = $('.content');
$ccol.scroll(function(){
$scb.stop(true,true).fadeTo(500, $ccol.scrollTop() > 10 ? 1 : 0);
});
However, it still doesn't work. Am I making a mistake in how I'm modifying the JS to fit my CSS?
You can include the toggle-menu-wrap element in your HTML from the start. There is no need to insert it using JS.
Write the one line of CSS you need, which is to hide the element from the beginning
.toggle-menu-wrap {
display: none;
}
Your version of jQuery uses 'jQuery' instead of '$' to reference itself. I would also re-write your JS like:
jQuery(document).ready(function() {
fadeMenuWrap();
jQuery(window).scroll(fadeMenuWrap);
});
function fadeMenuWrap() {
var scrollPos = window.pageYOffset || document.documentElement.scrollTop;
if (scrollPos > 300) {
jQuery('.toggle-menu-wrap').fadeIn(300);
} else {
jQuery('.toggle-menu-wrap').fadeOut(300);
}
}
Like #murli2308 said in the comments above, you need to attach a scroll event listener to the window:
$(document).ready(function () {
var $scb = $('<div class="scroll-border"></div>');
$('.above').append($scb);
var $ccol = $('.content');
$(window).scroll(function(){
$scb.stop(true,true).fadeTo(500, $ccol.scrollTop() > 10 ? 1 : 0);
});
})
Wrapping your code in $(document).ready() would also be a good idea.
The reason $ccol.scroll(function() { ... works in that fiddle is because of the CSS:
.content{
height: 200px;
width: 200px;
overflow: auto;
}
Notice overflow: auto;. This causes that specific div to be scrollable. However, on your website, you scroll the entire page, not $ccol. This means the event handler will never fire a scroll event (since $ccol will never scroll).
You might have forgotten to link Jquery.
<script type="text/javascript" src="http://code.jquery.com/jquery-1.8.3.min.js"></script>
Link this inside your head tag incase.....
This should do the job:
$(window).scroll(function(e){
if ($(this).scrollTop() > 0) {
$(".your_element").css("display", "block");
} else {
$(".your_element").css("display", "none");
}
});