I want remove .bg-light from nav element at 400px and more scrolls
<nav id="my-nav" class="bg-light navbar text-info"> change my background color</nav>
I know it's an easy task with jQuery but is it possible to do it with vanilla js?
Thanks for spending time on my question I will be glad to see opinion
First, we start by grabbing the "nav" element using the ID.
Then setting our Y-axis's offset.
Attach a listener to the window object.
On scroll, compare the current position to our desired offset.
const navBar = document.getElementById("my-nav");
const offset = 400;
window.addEventListener("scroll", () => {
if (window.scrollY >= offset){
navBar.classList.remove("bg-light")
} else {
navBar.classList.add("bg-light")
}
})
Yes, its possible with Vanilla JavaScript, use the "scroll" event handler to get the info. As the users moves through the site it will return the Y axis position in pixels. By using an if statement remove or add the bg-light class, like so:
let nav = document.getElementById("my-nav");
window.addEventListener("scroll", (e) => {
if(this.scrollY > 400){ nav.classList.remove('bg-light') }
else{
nav.classList.add('bg-light')
}
});
*{padding:5px}
html{height:3000px;font-size:20px}
.bg-light{background-color: #F8F8F8!important; color:black!important;}
.navbar{position:fixed;background-color:blue; color:white;}
<nav id="my-nav" class="bg-light navbar text-info"> Change my background color at scrollY 400px</nav>
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 got a problem figuring out how to make a button onClick scroll down for example 30px per click.
say i got two divs with icons like this
<div className="info-container">
<div className="scroll-icon-container" onClick={scrollUp(30)}>
<ScrollUpIcon />
</div>
<div className="scroll-icon-container" onClick={scrollDown(30)}>
<ScrollDownIcon />
</div>
<p>"Huge amount of text that will need scrolling"</p>
</div>
Then two functions like
scrollUp(number: amountToScroll){
//Scroll the "info-container" up amountToScroll pixels
}
scrollDown(number: amountToScroll){
//Scroll the "info-container" down amountToScroll pixels
}
All i could find so far is either in jquery or how to make it scroll to a specific element but i am looking for a set amount to scroll down in pixels % or whatever works.
First of all you can either define a variable or state for maintaining the scroll position.
Let us take state as scrollPosition and initialize it to 0.
Now in the scrollUp function:
scrollUp(amountToScroll){
this.setState({
scrollPosition : this.state.scrollPosition + amountToScroll
})
window.scrollTo(0, this.state.scrollPosition)
}
Now in scrollDown function:
scrollDown(amountToScroll){
this.setState({
scrollPosition : this.state.scrollPosition - amountToScroll
})
window.scrollTo(0, this.state.scrollPosition)
}
Use window.scrollBy( pixelsToScrollRight, pixelsToScrollDown ) method.
So instead of scrollUp() and scrollDown() methods you can have something like this:
scroll(number: amountToScroll){
//amount to scroll is negative to scroll up
window.scrollBy(0 , amountToScroll)
}
If you want to look at scrolling inside a div: How to scroll to an element inside a div?
What I'm trying to achieve is relatively simple after a set height I'm looking to collapse a div using Bootstrap default attributes. Below I have written the javascript to trigger after a set height but what I'm unsure on is how to trigger the collapse with the id of #more.
function testScroll(ev) {
if (window.pageYOffset > 1100) alert('User has scrolled at least 400 px!');
}
<div id="more" class="collapse">test</div>
You can use the collapse function as defined in the bootstrap docs, by providing it the element id. You can also read more about it here.
function testScroll(ev){
if(window.pageYOffset>1100) {
alert('User has scrolled at least 400 px!');
$('more').collapse('hide');
} else {
alert('User has not scrolled at least 400 px!');
$('more').collapse('show');
}
}
<div id="more" class="collapse">test</div>
If I understand you don't know how to select and change the class of the item #more
var collapse = function() {
// select the element that has the id #more
var element = document.getElementById('more');
// now you can, for exemple change its class
// that's where you can apply a different css class to collapse the div
element.setAttribute('class','anotherClass');
}
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've found a great tutorial to detach a navigation from the page to keep it static when you scroll using Javascript (http://code.stephenmorley.org/javascript/detachable-navigation/).
However, I'd like to implement this on more than one nav div.
I assume it's adding another class name to document.getElementById('navigation').className but I can't get the right syntax
Here is the code:
/* Handles the page being scrolled by ensuring the navigation is always in
* view.*/
function handleScroll(){
// check that this is a relatively modern browser
if (window.XMLHttpRequest){
// determine the distance scrolled down the page
var offset = window.pageYOffset
? window.pageYOffset
: document.documentElement.scrollTop;
// set the appropriate class on the navigation
document.getElementById('navigation').className =
(offset > 104 ? 'fixed' : '');
}
}
// add the scroll event listener
if (window.addEventListener){
window.addEventListener('scroll', handleScroll, false);
}else{
window.attachEvent('onscroll', handleScroll);
}
You will have to call getElementById() for each ID. The Method is only designed to get exactly one element (or zero, if the ID isn't found).
Assuming, you have two navigation divs, left and right, like this:
<div id="navigationLeft">
<ul>
<!-- Navigation entries -->
</ul>
</div>
<!-- Maybe some content or whatever? -->
<div id="navigationRight">
<ul>
<!-- Navigation entries -->
</ul>
</div>
Then your Javascript line in question would look like this:
// set the appropriate class on the navigation
document.getElementById('navigationLeft').className = (offset > 104 ? 'fixed' : '');
document.getElementById('navigationRight').className = (offset > 104 ? 'fixed' : '');
// or, shorter but less readable (i think)
document.getElementById('navigationLeft').className
= document.getElementById('navigationRight').className
= (offset > 104 ? 'fixed' : '');
If this does not yet answer your question, please feel free to add some relevant HTML-Code to your question.
[Update: Example]
This is not recommended you should replace id with classes and use that in a loop to set the value:
HTML:
<div class="navigation">
<p>test 1</p>
</div>
<div class="navigation">
<p>test 2</p>
</div>
Javascript:
divs = document.getElementsByClassName('navigation');
for(i = 0; i < divs.length; i++) {
var div = divs[i];
var divClassName = div.className;
if(divClassName.indexOf('fixed') != -1 && offset > 104) {
divClassName.replace(' fixed','');
} else {
divClassName += ' fixed';
}
}
I think that will do the trick :-)
Greetings!
Gonzalo G.
you shouldnt have multiple items on a page with the same ID, ID's are meant to be unique...if you want to capture multiple items you should use:
<div class="navigation"></div>
var nodes = document.getElementsByClassName('navigation')
...if not using jquery, otherwise do something like
var nodes = $('.navigation')
which will get you yor nav bars, then check to see if that node is also "fixed" ( a node can have more than one css class )
(nodes[i].indexOf("navigation") >= 0)
if using jquery, you can use .hasClass('fixed') )
nodes[i].hasClass('fixed')
...your current problem is that it cant add className to navigation because there are two of them and youre not specifying which one you'd like to use.
If you want this to happen in two navigation div's, consider putting them both into one div and call it nav and set a style on it (this depends on your design)
All id's on an element must be unique.
One solution so that you can do a simple change would be to change the CSS file to something like this:
.navigation{
position:absolute;
top:120px;
left:0;
}
.navigationFixed{
position:fixed;
top:16px;
}
And define the Div's vis this:
<div class="navigation">
<!-- your navigation code -->
</div>
And then edit the JavaScript to something along the lines of this:
/* Handles the page being scrolled by ensuring the navigation is always in
* view.
*/
function handleScroll(){
// check that this is a relatively modern browser
if (window.XMLHttpRequest){
divs = document.getElementsByClassName('navigation');
for(i = 0; i < divs.length; i++) {
// determine the distance scrolled down the page
var offset = window.pageYOffset
? window.pageYOffset
: document.documentElement.scrollTop;
divs[i].className =
(offset > 104 ? 'navigationFixed' : 'navigation');
}
}
}
// add the scroll event listener
if (window.addEventListener){
window.addEventListener('scroll', handleScroll, false);
}else{
window.attachEvent('onscroll', handleScroll);
}