Changing nav-bar color after scrolling? - javascript

How can I set the navbar with no background color?
When scrolling down after a div the nav-bar gets a new background-color (the nav-bar should be fixed at top, I use navbar-fixed-top in Bootstrap)
I've tried some tutorials but I didn't succeed.
This is the website : http://attafothman.olympe.in/
I'm talking about that black nav-bar on top.

Here is simplest way how to change navbar color after window scroll:
Add follow JS to head:
$(function () {
$(document).scroll(function () {
var $nav = $(".navbar-fixed-top");
$nav.toggleClass('scrolled', $(this).scrollTop() > $nav.height());
});
});
and this CSS code
.navbar-fixed-top.scrolled {
background-color: #fff !important;
transition: background-color 200ms linear;
}
Background color of fixed navbar will be change to white when scroll exceeds height of navbar.
See follow JsFiddle

this is a simple pure javascript
var myNav = document.getElementById('mynav');
window.onscroll = function () {
if (document.body.scrollTop >= 200 ) {
myNav.classList.add("nav-colored");
myNav.classList.remove("nav-transparent");
}
else {
myNav.classList.add("nav-transparent");
myNav.classList.remove("nav-colored");
}
};
in some chrome versions there is a bug with:
document.body.scrollTop
so you may add a condition like this:
if (document.body.scrollTop >= 200 || document.documentElement.scrollTop >= 200 )
sure you must have 2 classes
.nav-colored { background-color:#000; }
.nav-transparent { background-color:transparent;}

Here is a jsfiddle example. Using Jquery to change the background color based on scroll pixel position.
Here is a fiddle using bootstrap
$(document).ready(function(){
var scroll_start = 0;
var startchange = $('#startchange');
var offset = startchange.offset();
if (startchange.length){
$(document).scroll(function() {
scroll_start = $(this).scrollTop();
if(scroll_start > offset.top) {
$(".navbar-default").css('background-color', '#f0f0f0');
} else {
$('.navbar-default').css('background-color', 'transparent');
}
});
}
});

i think this solution is shorter and simpler than older answers.
This is Js Code:
const navbar = document.querySelector('.nav-fixed');
window.onscroll = () => {
if (window.scrollY > 300) {
navbar.classList.add('nav-active');
} else {
navbar.classList.remove('nav-active');
}
};
And my css:
header.nav-fixed {
width: 100%;
position: fixed;
transition: 0.3s ease-in-out;
}
.nav-active {
background-color:#fff;
box-shadow: 5px -1px 12px -5px grey;
}

Today I've gone through the same question, how to change navbar background-color as scrolling. And I was seeking for a solution using CSS only, no jquery, no bootstrap nor javascript. But then it turned out couldn't be done with CSS only yet (as of today Dec 2019). And have to choose, I'll stick with the core technology - javascript instead of jquery or bootstrap unless it's far more complicated using js than the others. But luckily it's not.
Here's the code:
- It uses onscroll/ scroll event of window to trigger the event listener.
- In the event listener, use pageYOffset/ scrollY of window to check the scroll status.
Browser support are seemingly the same between both:
- https://caniuse.com/#search=pageYOffset
- https://caniuse.com/#search=scrollY
var navbar = document.querySelector('nav')
window.onscroll = function() {
// pageYOffset or scrollY
if (window.pageYOffset > 0) {
navbar.classList.add('scrolled')
} else {
navbar.classList.remove('scrolled')
}
}
body {
margin: 0;
padding: 0;
background: url(https://occ-0-325-395.1.nflxso.net/dnm/api/v6/6AYY37jfdO6hpXcMjf9Yu5cnmO0/AAAABaKr-dQAdVTt7fuGCgzntgBBrFce2DMW72dF86eO7EnXbFZvzmX2TPnQAg3HwAsvt7ZnDnP0nwuHOtPwpWGGOE22fXq2.webp?r=847) top/contain no-repeat;
}
nav {
position: -webkit-sticky;
position: sticky;
/* sticky or fixed are fine */
position: fixed;
top: 0;
height: 69px;
width: 100%;
background: linear-gradient(to bottom, #000, #0003 70%,#0000); /* background when scroll is in the top */
transition: background .5s; /* control how smooth the background changes */
}
nav.scrolled {
background: #0a0a0a;
}
main {
height: 200vh;
}
<nav></nav>
<main></main>

<script>
$(document).ready(function(){
$(window).scroll(function() { // check if scroll event happened
if ($(document).scrollTop() > 50) { // check if user scrolled more than 50 from top of the browser window
$(".navbar-fixed-top").css("background-color", "#f8f8f8"); // if yes, then change the color of class "navbar-fixed-top" to white (#f8f8f8)
} else {
$(".navbar-fixed-top").css("background-color", "transparent"); // if not, change it back to transparent
}
});
});
</script>

This can be done using jQuery.
Here is a link to a fiddle.
When the window scrolls, the distance between the top of the window and the height of the window is compared. When the if statement is true, the background color is set to transparent. And when you scroll back to the top the color comes back to white.
$(document).ready(function(){
$(window).scroll(function(){
if($(window).scrollTop() > $(window).height()){
$(".menu").css({"background-color":"transparent"});
}
else{
$(".menu").css({"background-color":"white"});
}
})
})

window.addEventListener('scroll', function (e) {
var nav = document.getElementById('nav');
if (document.documentElement.scrollTop || document.body.scrollTop > window.innerHeight) {
nav.classList.add('nav-colored');
nav.classList.remove('nav-transparent');
} else {
nav.classList.add('nav-transparent');
nav.classList.remove('nav-colored');
}
});
best approach to use event listener. especially for Firefox browser, check this doc Scroll-linked effects and Firefox is no longer support document.body.scrollTop and alternative to use document.documentElement.scrollTop. This is completes the answer from Yahya Essam

How about the Intersection Observer API? This avoids the potential sluggishness from using the scroll event.
HTML
<nav class="navbar-fixed-top">Navbar</nav>
<main>
<div class="content">Some content</div>
</main>
CSS
.navbar-fixed-top--scrolled changes the nav bar background color. It's added to the nav bar when the content div is no longer 100% visible as we scroll down.
.navbar-fixed-top {
position: sticky;
top: 0;
height: 60px;
}
.navbar-fixed-top--scrolled {
/* change background-color to whatever you want */
background-color: grey;
}
JS
Create the observer to determine when the content div fully intersects with the browser viewport.
The callback function is called:
the first time the observer is initially asked to watch the target element
when content div is no longer fully visible (due to threshold: 1)
when content div becomes fully visible (due to threshold: 1)
isIntersecting indicates whether the content div (the target element) is fully intersecting with the observer's root (the browser viewport by default).
// callback function to be run whenever threshold is crossed in one direction or the other
const callback = (entries, observer) => {
const entry = entries[0];
// toggle class depending on if content div intersects with viewport
const navBar = document.querySelector('.navbar-fixed-top');
navBar.classList.toggle('navbar-fixed-top--scrolled', !entry.isIntersecting);
}
// options controls circumstances under which the observer's callback is invoked
const options = {
// no root provided - by default browser viewport used to check target visibility
// only detect if target element is fully visible or not
threshold: [1]
};
const io = new IntersectionObserver(callback, options);
// observe content div
const target = document.querySelector('.content');
io.observe(target);
IntersectionObserver options
The nav bar currently changes background color when the content div starts moving off the screen.
If we want the background to change as soon as the user scrolls, we can use the rootMargin property (top, right, bottom, left) and set the top margin to negative the height of the nav bar (60px in our case).
const options = {
rootMargin: "-60px 0px 0px 0px",
threshold: [1]
};
You can see all the above in action on CodePen. Kevin Powell also has a good explanation on this (Github & YouTube).

Slight variation to the above answers, but with Vanilla JS:
var nav = document.querySelector('nav'); // Identify target
window.addEventListener('scroll', function(event) { // To listen for event
event.preventDefault();
if (window.scrollY <= 150) { // Just an example
nav.style.backgroundColor = '#000'; // or default color
} else {
nav.style.backgroundColor = 'transparent';
}
});

So I'm using querySelector to get the navbar
I added a scroll event to the window to track the scrollY property
I check if it's higher than 50 then I add the active class to the navbar, else if it contains it already, I simply remove it and I'm pretty sure the conditions can be more currated and simplified.
I made this codepen to help you out!
const navbar = document.querySelector('#nav')
window.addEventListener('scroll', function(e) {
const lastPosition = window.scrollY
if (lastPosition > 50 ) {
navbar.classList.add('active')
} else if (navbar.classList.contains('active')) {
navbar.classList.remove('active')
} else {
navbar.classList.remove('active')
}
})

I use WordPress which comes with Underscore. So when you register your theme scripts, you would use 'jquery' and 'underscore' as the handle for the array of the dependancies. If you are not using WordPress, then make sure that you load both the jQuery framework and Underscore before your scripts.
CodePen: https://codepen.io/carasmo/pen/ZmQQYy
To make this demo (remember it requires both jQuery and Underscore).
HTML:
<header class="site-header">
<div class="logo">
</div>
<nav>navigation</nav>
</header>
<article>
Content with a forced height for scrolling. Content with a forced height for scrolling. Content with a forced height for scrolling. Content with a forced height for scrolling. Content with a forced height for scrolling. Content with a forced height for scrolling. Content with a forced height for scrolling
</article>
CSS:
body,
html {
margin: 0;
padding: 0;
font: 100%/180% sans-serif;
background: #eee;
}
html {
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
box-sizing: border-box;
}
*,
*::before,
*::after {
box-sizing: inherit;
}
article {
height: 2000px;
padding: 5%;
background: #fff;
margin: 2% auto;
max-width: 900px;
box-shadow: 0px 0px 30px 0px rgba(0, 0, 0, 0.10);
}
.site-header {
background: #fff;
padding: 20px 5%;
box-shadow: 0px 0px 12px 0px rgba(0, 0, 0, 0.23);
transition: all .5s ease-in-out;
-web-kit-position: sticky;
position: sticky;
top: 0;
display: -webkit-box;
display: -ms-flexbox;
display: flex;
-webkit-box-orient: horizontal;
-webkit-box-direction: normal;
-ms-flex-direction: row;
flex-direction: row;
-webkit-box-align: center;
-ms-flex-align: center;
align-items: center;
-webkit-box-pack: center;
-ms-flex-pack: center;
justify-content: center;
}
.logo {
background-image: url('the-path-to-the-logo.svg');
background-repeat: no-repeat;
background-position: center center;
width: 200px;
height: 60px;
background-size: contain;
transition: width .5s ease-in-out, height .5s ease-in-out;
}
.site-header nav {
text-align: right;
-webkit-box-flex: 1;
-ms-flex-positive: 1;
flex-grow: 1;
-ms-flex-preferred-size: 0;
flex-basis: 0;
}
.site-header.is-scrolling {
opacity: .8;
background: tomato;
padding: 10px 5%;
}
.site-header.is-scrolling .logo {
height: 40px;
width: 100px;
}
jQuery:
( function( window, $, undefined ) {
'use strict';
////////////// Begin jQuery and grab the $ ////////////////////////////////////////
$(document).ready(function() {
function is_scrolling() {
var $element = $('.site-header'),
$nav_height = $element.outerHeight( true );
if ($(this).scrollTop() >= $nav_height ) { //if scrolling is equal to or greater than the nav height add a class
$element.addClass( 'is-scrolling');
} else { //is back at the top again, remove the class
$element.removeClass( 'is-scrolling');
}
}//end is_scrolling();
$(window).scroll(_.throttle(is_scrolling, 200));
}); //* end ready
})(this, jQuery);

I've recently done it slightly different to some of the examples above so thought I'd share, albeit very late!
Firstly the HTML, note there is only one class within the header:
<body>
<header class="GreyHeader">
</header>
</body>
And the CSS:
body {
height: 3000px;
}
.GreyHeader{
height: 200px;
background-color: rgba(107,107,107,0.66);
position: fixed;
top:200;
width: 100%;
}
.FireBrickRed {
height: 100px;
background-color: #b22222;
position: fixed;
top:200;
width: 100%;
}
.transition {
-webkit-transition: height 2s; /* For Safari 3.1 to 6.0 */
transition: height 2s;
}
The html uses only the class .greyHeader but within the CSS I have created another class to call once the scroll has reached a certain point from the top:
$(function() {
var header = $(".GreyHeader");
$(window).scroll(function() {
var scroll = $(window).scrollTop();
if (scroll >= 500) {
header.removeClass('GreyHeader').addClass("FireBrickRed ");
header.addClass("transition");
} else {
header.removeClass("FireBrickRed ").addClass('GreyHeader');
header.addClass("transition");
}
});
});
check this fiddle: https://jsfiddle.net/29y64L7d/1/

First things first, you have to include Jquery into your HTML file or whatever file you are using.
create a script code space in the head part of your file and include the code below.
$(document).ready(function(){
$(window).scroll(function(){
if($(window).scrollTop() > 100){
$(".navbar").css({"background-color":"black"});
}
else{
$(".navbar").css({"background-color":""});
}
})
})
With this where the code says ($(window).scrollTop() > 100) 100 is in "px" so you can specify the height at which the function is called.
This line of code $(".navbar").css({"background-color":"black"}); is where you replace your class name of the Nav element. This is just directly accessing the CSS and then editing the CSS.
HTML Code Below
<header class="hero">
<nav class="navbar ">
<div class="container">
<a class="navbar-brand" href="#">
<img src="" alt=""> </a>
<button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarSupportedContent">
<ul class="navbar-nav me-auto mb-2 mb-lg-0">
<li class="nav-item">
<a class="nav-link active" aria-current="page" href="#">Home</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">TV shows</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">Movies</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">News and Popular</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">My List</a>
</li>
</ul>
</div>
</div>
</nav>
</header>

$(document).ready(function(){
$(window).scroll(function() {
if ($(document).scrollTop() >1290 ) {
$(".navbar-fixed-top").css("background-color", "rgb(255, 160, 160)");
}else if ($(document).scrollTop() >850) {
$(".navbar-fixed-top").css("background-color", "black");
}else if ($(document).scrollTop() >350) {
$(".navbar-fixed-top").css("background-color", "rgba(47, 73, 158, 0.514)");
}
else {
$(".navbar-fixed-top").css("background-color", "red");
}
});
});
#import url(https://fonts.googleapis.com/css?family=Roboto+Slab:400,700|Open+Sans);
body {
font-family: "Roboto Slab", sans-serif;
position: relative;
}
h1,
h2,
h3,
h4 {
font-family: "Open Sans", sans-serif;
}
.main {
padding-top: 50px;
}
#home {
padding-top: 20%;
background-image: linear-gradient( rgba(0, 0, 0, 0.5), rgba(0, 0, 0, 0.5)), url('https://s31.postimg.org/l5q32ptln/coffee_cup_mug_apple.jpg');
background-attachment: fixed;
background-repeat: no-repeat;
background-position: center center;
position: relative;
height: 100vh;
}
#home h2 {
color: white;
font-size: 4em;
}
#home h4 {
color: white;
font-size: 2em;
}
#home ul {
list-style-type: none;
text-align: center;
}
#home li {
padding-bottom: 12px;
padding-right: 12px;
display: inline;
}
#home li:last-child {
padding: 0;
}
#media (max-width: 710px) {
#home li {
display: block;
}
}
.img-style {
height: 200px;
width: 200px;
margin-top: 50px;
}
#about {
height: 100vh;
padding-top: 10%;
background: linear-gradient( rgba(0, 0, 0, 0.5), rgba(0, 0, 0, 0.5)), url('https://s32.postimg.org/sm6o6617p/photo_1432821596592_e2c18b78144f.jpg');
background-attachment: fixed;
background-repeat: no-repeat;
background-position: center center;
position: relative;
color: white;
}
#about p,
li {
font-size: 17px;
}
.navbar.color-yellow {
background-color: yellow;
height: 50px;
color: yellow;
}
.navbar.color-change {
background-color: #f45b69;
height: 50px;
color: rgba(255, 254, 255, 0.8);
}
#portfolio {
padding-top: 30px;
rgba(226,
226,
226,
1);
background: linear-gradient(to bottom, rgba(226, 226, 226, 1) 0%, rgba(209, 209, 209, 1) 25%, rgba(219, 219, 219, 1) 57%, rgba(254, 254, 254, 1) 100%);
height: 100vh;
}
#portfolio .block .portfolio-contant ul li {
float: left;
width: 32.22%;
overflow: hidden;
margin: 6px;
position: relative;
}
#portfolio .block .portfolio-contant ul li:hover .overly {
opacity: 1;
}
#portfolio .block .portfolio-contant ul li:hover .position-center {
position: absolute;
top: 50%;
-webkit-transform: translate(0%, -50%);
-moz-transform: translate(0%, -50%);
-ms-transform: translate(0%, -50%);
transform: translate(0%, -50%);
}
#portfolio .block .portfolio-contant ul li a {
display: block;
color: #fff;
}
#portfolio .block .portfolio-contant ul li a h2 {
font-size: 22px;
text-transform: uppercase;
letter-spacing: 1px;
}
#portfolio .block .portfolio-contant ul li a p {
font-size: 15px;
}
#portfolio .block .portfolio-contant ul li a span {
font-style: italic;
font-size: 13px;
color: #655E7A;
}
#portfolio .block .portfolio-contant ul img {
width: 100%;
height: auto;
}
#portfolio .block .portfolio-contant .overly {
position: absolute;
top: 0;
bottom: 0;
right: 0;
left: 0;
background: rgba(0, 0, 0, 0.9);
opacity: 0;
-webkit-transition: .3s all;
-o-transition: .3s all;
transition: .3s all;
text-align: center;
}
#portfolio .block .portfolio-contant .position-center {
position: absolute;
top: 50%;
left: 10%;
-webkit-transform: translate(0%, 50%);
-moz-transform: translate(0%, 50%);
-ms-transform: translate(0%, 50%);
transform: translate(0%, 50%);
-webkit-transition: .5s all;
-o-transition: .5s all;
transition: .5s all;
}
#contact {
height: 100vh;
padding-top: 10%;
background: linear-gradient( rgba(0, 0, 0, 0.5), rgba(0, 0, 0, 0.5)), url("https://s32.postimg.org/ex6q1qxkl/pexels_photo.jpg");
background-attachment: fixed;
background-size: cover;
background-repeat: no-repeat;
background-position: center center;
position: relative;
}
#contact h3 {
color: white;
}
footer ul {
list-style-type: none;
text-align: center;
}
footer li {
display: inline;
padding-right: 10px;
}
footer li:last-child {
padding: 0;
}
footer p {
color: grey;
font-size: 11px;
}
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.4.0/css/font-awesome.min.css" rel="stylesheet" />
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<header>
<nav class="navbar navbar-default navbar-fixed-top" role="navigation">
<div class="container">
<div class="navbar-header">
<button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#collapse" aria-expanded="false">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="#featured">Portfolio</a>
</div>
<!-- navbar-header -->
<div class="collapse navbar-collapse" id="collapse">
<ul class="nav navbar-nav navbar-right">
<li class="active">Home</li>
<li>About</li>
<li>Portfolio</li>
<li>Contact</li>
</ul>
</div>
<!-- collapse navbar-collapse -->
</div>
<!-- container -->
</nav>
</header>
<div class="main">
<div class="row " id="home" data-speed="2" data-type="background">
<div class="container">
<h2 class="text-center">Welcome to my portfolio</h2>
<h4 class="text-center">Where awesomeness is crafted</h4>
<hr>
<ul>
<li><i class="fa fa-github"></i> GitHub</li>
<li><i class="fa fa-linkedin"></i> LinkedIn</li>
<li><i class="fa fa-fire"></i> FreeCodeCamp</li>
</ul>
</div>
<!--container-->
</div>
<!--home-->
<div class="row" id="about" data-speed="2" data-type="background">
<div class="container">
<div class="row">
<div class="col-md-5 col-md-offset-1">
<h2>About me</h2>
<p>Courteous and Enthusiastic,I'm interested in IT and around in its globe. I began to be fascinated by web programming i.e, building websites and developing cross-platform apps.I'm always looking for new ventures where i can learn evolve and
expertise.
</marquee>
</div>
</p>
<p>My skills are:
<ul>
<li> Front-end : HTML5, CSS3 , jQuery, Bootstrap, AngularJS</li>
<li>Back-end: Ruby on Rails</li>
<li>Methodology: Agile, TDD</li>
</ul>
</p>
</div>
<!--col-md-5-->
<div class="col-md-4 col-md-offset-1">
<img class="img-circle img-style hidden-xs" src="https://www.triketech.site/images/log.png" />
</div>
</div>
<!--row-->
</div>
<!--container-->
</div>
<!--about-->
<div class="row" id="portfolio" data-speed="2" data-type="background">
<div class="container">
<h2 class="text-center">Portfolio projects</h2>
<div class="row">
<div class="col-md-12">
<div class="block">
<div class="portfolio-contant">
<ul id="portfolio-contant-active">
<li class="mix Branding">
<a href="#">
<img src="#" alt="">
<div class="overly">
<div class="position-center">
<h2>Local Support</h2>
</div>
</div>
<!--overly-->
</a>
</li>
</ul>
</div>
<!--portfolio-contant-->
</div>
<!--block-->
</div>
<!--col-->
</div>
<!--row-->
</div>
<!--container-->
</div>
<!--portfolio-->
<div class="row" id="contact" data-speed="2" data-type="background">
<div class="container">
<div class="col-md-4 col-md-offset-1">
<h3>Contact me at:</h3>
<h3>thegreatvamshi#triketech.com</h3>
</div>
<!--col-md-4-->
</div>
<!--container-->
</div>
<!--contact-->
</div>
<!--main-->
<footer>
<ul>
<li>Home </li>
<li>About </li>
<li>Portfolio </li>
<li>Contact </li>
</ul>
<p class="text-center">Copyright © - All Rights Reserved. </p>
</footer>
</body>
</html>
<script>
$(document).ready(function(){
$(window).scroll(function() {
if ($(document).scrollTop() >1920 ) {
$(".navbar-fixed-top").css("background-color", "rgb(255, 160, 160)");
} else if ($(document).scrollTop() >1580) {
$(".navbar-fixed-top").css("background-color", "black");
} else if ($(document).scrollTop() >620) {
$(".navbar-fixed-top").css("background-color", "rgba(47, 73, 158, 0.514)");
} else {
$(".navbar-fixed-top").css("background-color", "transparent");
}
});
});
</script>

First you make an id named nav (can change whatever you want) inside the nav div (exp: id="nav")
Then at the bottom where body tag had been finished. You add this code
<script>
$(document).ready(function()
$(window).scroll(function(){
var scroll = $(window).scrollTop();
if(scroll>50){
$("#nav").css("background", "#555");
}
else {
$("#nav").css("background", "transparent");
}
})
})
</script>

$(window).on('activate.bs.scrollspy', function (e,obj) {
if ((window.innerHeight + window.pageYOffset) >= document.body.offsetHeight) {
return;
}
var isBGLight = $(obj.relatedTarget).hasClass('nav_white');
var isBGDark = $(obj.relatedTarget).hasClass('nav_blue');
$('.menu').removeClass('nav_white');
$('.menu').removeClass('nav_blue');
if(isBGDark)
{
$('.menu').addClass('nav_white');
}else if(isBGLight)
{
$('.menu').addClass('nav_blue');
}
/*var isScrolled = $(document).scrollTop() > 1;
$('.menu').toggleClass('scrolled', isScrolled);
$(".demos").toggleClass("demo");
$(".demos").toggleClass("demo1");
var posicionActual = $(document).scrollTop();
$.each($('.nav_transparent'),function(){
if ($(this).position().top < posicionActual){
$("nav.menu").removeClass("nav_white");
$("nav.menu").removeClass("nav_blue");
$("nav.menu").addClass("nav_transparent");
$(".demos").removeClass("demo");
$(".demos").addClass("demo1");
$(".cls").removeClass("cls2");
$(".cls").addClass("cls1");
$(".cl").removeClass("cl2");
$(".cl").addClass("cl1");
$(".hamb-bottom").css({"background-color": "#fff"});
$(".hamb-middle").css({"background-color": "#fff"});
$(".hamb-top").css({"background-color": "#fff"});
}
});
$.each($('.nav_blue'),function(){
if ($(this).position().top <= posicionActual){
$("nav.menu").removeClass("nav_transparent");
$("nav.menu").removeClass("nav_white");
$("nav.menu").addClass("nav_blue");
$(".demos").removeClass("demo1");
$(".demos").addClass("demo");
$(".cls").removeClass("cls2");
$(".cls").addClass("cls1");
$(".cl").removeClass("cl2");
$(".cl").addClass("cl1");
$(".hamb-bottom").css({"background-color": "#fff"});
$(".hamb-middle").css({"background-color": "#fff"});
$(".hamb-top").css({"background-color": "#fff"});
}
});
$.each($('.nav_white'),function(){
if ($(this).position().top <= posicionActual){
$("nav.menu").removeClass("nav_blue");
$("nav.menu").removeClass("nav_transparent");
$("nav.menu").addClass("nav_white");
$(".demos").removeClass("demo");
$(".demos").addClass("demo1");
$(".cls").removeClass("cls1");
$(".cls").addClass("cls2");
$(".cl").removeClass("cl1");
$(".cl").addClass("cl2");
$(".hamb-bottom").css({"background-color": "#4285f4"});
$(".hamb-middle").css({"background-color": "#4285f4"});
$(".hamb-top").css({"background-color": "#4285f4"});
}
});*/
});
$(window).on("scroll", function(){
if($(document).scrollTop() < 10)
{
$('.nav').removeClass('nav_white');
$('.nav').removeClass('nav_blue');
$('.nav').removeClass('nav_transparent');
$('.nav').addClass('nav_transparent');
}
});
the solutions, maybe

Related

Horizontal scroll areas with buttons and gradients

This is my code so far:
// Show and hide gradients
$(document).ready(function() {
$(".scroll-area").each(function(index) {
if ($(this)[0].scrollWidth <= $(this)[0].clientWidth) {
$(this).closest(".container").find(".left").css("display", "none");
$(this).closest(".container").find(".right").css("display", "none");
} else {
$(this).scroll(function() {
if ($(this)[0].scrollWidth > $(this)[0].clientWidth) {
if ($(this).scrollLeft() > 0) {
$(this).closest(".container").find(".left").css("display", "block");
}
if ($(this).scrollLeft() == 0) {
$(this).closest(".container").find(".left").css("display", "none");
}
var fullWidth = $(this)[0].scrollWidth - $(this)[0].offsetWidth - 1;
if ($(this).scrollLeft() >= fullWidth) {
$(this).closest(".container").find(".right").css("display", "none");
}
if ($(this).scrollLeft() < fullWidth) {
$(this).closest(".container").find(".right").css("display", "block");
}
}
});
}
});
});
// Scroll buttons
let interval;
$('.scroll-btn').on('mousedown', ({
target
}) => {
const type = $(target).attr('id');
interval = setInterval(() => {
var x = $('#a').scrollLeft();
$('#a').scrollLeft(type === 'left-arrow' ? x - 10 : x + 10);
}, 50);
});
$('.scroll-btn').on('mouseup', () => clearInterval(interval));
* {
margin: 0;
padding: 0;
font-family: sans-serif;
font-size: 16px;
}
.container {
width: 550px;
height: 80px;
background-color: grey;
position: relative;
margin-bottom: 20px;
}
.scroll-area {
white-space: nowrap;
overflow-x: auto;
height: 100%;
}
.left,
.right {
width: 50px;
height: 100%;
position: absolute;
pointer-events: none;
top: 0;
}
.left {
background: linear-gradient(90deg, orange 0%, rgba(0, 0, 0, 0) 100%);
left: 0;
display: none;
}
.right {
background: linear-gradient(-90deg, orange 0%, rgba(0, 0, 0, 0) 100%);
right: 0;
}
.arrow {
display: block;
position: absolute;
display: flex;
align-items: center;
justify-content: center;
height: 100%;
width: 15px;
cursor: pointer;
}
.left-arrow {
left: 0;
}
.right-arrow {
right: 0;
}
.left-arrow div,
.right-arrow div {
font-size: 40px;
}
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<div class="container">
<div id="x" class="left"></div>
<div class="right"></div>
<div class="arrow left-arrow">
<div class="scroll-btn" id="left-arrow">
<</div>
</div>
<div class="arrow right-arrow">
<div class="scroll-btn" id="right-arrow">></div>
</div>
<div id="a" class="scroll-area">
<div class="text">Scroll to right. The gradients and arrows should appear and disappear based on the scroll position. It should work with more than one container. Lorem ipsum.</div>
</div>
</div>
The needs are:
The arrows should appear and disappear in the same way like the gradients.
If there is not enough text to cause a scrollable area, there should be no gradient and now arrow.
There should be more than one container in the end.
Can somebody help me to do that? I would be super thankful!
You can put your arrows inside the left/right gradient divs. That way they will show/hide same way as the gradients.
EDIT
I cleaned up the code a bit since the original answer was kinda messy. (or 'weird' as mstephen19 put it :)).
// Show gradient and left/right arrows only if scrollable
$(".scroll-area").each((i, el) => {
$(el).parent().find(".right")[el.scrollWidth > el.clientWidth ? "show" : "hide"]();
});
// Show/hide gradient and arrows on scroll
$('.scroll-area').scroll((e) => {
const fullWidth = $(e.target)[0].scrollWidth - $(e.target)[0].offsetWidth - 1;
const left = $(e.target).scrollLeft()
$(e.target).parent().find(".left, .left-arrow")[left > 0 ? "show" : "hide"]();
$(e.target).parent().find(".right, .right-arrow")[left < fullWidth ? "show" : "hide"]();
});
// Scroll on left/right arrow mouse down
let intervalId;
$(".left-arrow, .right-arrow").on("mousedown", (e) => {
const scroll = $(e.target).closest(".container").find(".scroll-area");
intervalId = setInterval(() => {
const left = scroll.scrollLeft();
scroll.scrollLeft(e.target.classList.contains("left-arrow") ? left - 10 : left + 10);
}, 50);
}).on("mouseup mouseleave", () => {
clearInterval(intervalId);
});
* {
margin: 0;
padding: 0;
font-family: sans-serif;
font-size: 16px;
}
.container {
width: 550px;
height: 80px;
background-color: grey;
position: relative;
margin-bottom: 20px;
margin-left: 20px;
}
.scroll-area {
white-space: nowrap;
overflow-x: auto;
height: 100%;
}
.left,
.right {
width: 50px;
height: 100%;
position: absolute;
top: 0;
}
.left {
background: linear-gradient(90deg, orange 0%, rgba(0, 0, 0, 0) 100%);
left: 0;
display: none;
}
.right {
background: linear-gradient(-90deg, orange 0%, rgba(0, 0, 0, 0) 100%);
right: 0;
text-align: right;
}
.left-arrow,
.right-arrow {
margin: 0 10px;
position: absolute;
top: 50%;
-ms-transform: translateY(-50%);
transform: translateY(-50%);
cursor: pointer;
user-select: none;
font-size: 40px
}
.left-arrow {
display: none;
left: -25px;
}
.right-arrow {
right: -25px;
}
<html>
<head>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body>
<div class="container">
<div class="left"></div>
<div class="right"></div>
<div class="left-arrow"><</div>
<div class="right-arrow">></div>
<div class="scroll-area">
<div class="text">Scroll to right. The gradients and arrows should appear and disappear based on the scroll position. It should work with more than one container. Lorem ipsum.</div>
</div>
</div>
<div class="container">
<div class="left"><span class="left-arrow"><</span></div>
<div class="right"><span class="right-arrow">></span></div>
<div class="scroll-area">
<div class="text">No scroll.</div>
</div>
</div>
</body>
</html>
Some things about your code:
Your original code would not work with multiple containers, because you had a hardcoded #a ID in the interval code. You should really only have IDs on one element ideally, anyways (they're unique identifiers, while classes can be placed on multiple elements). The .scroll-area element should be found based on the target clicked.
You should combine your gradient and arrow elements into one element. By that, I mean making the div in which the arrow lives should be a child of the gradient div. Why manage them both separately?
Use class adding/removing/toggling instead of directly setting the CSS. Remember - when you find yourself writing the same code multiple times, it usually means there is a way to condense it down and make your code more dry and easier to understand + read.
Don't use the literal < and > symbols, as it can confuse some browsers. Use < and > instead.
Rather than toggling display to none and block, it's better to use visibility in this specific case. In my example, we use opacity for a fun fading effect.
Don't forget to listen for both mouseup mouseout events :)
Here is the working solution. I've refactored the code a bit:
let interval;
$('.arrow').on('mousedown', ({ target }) => {
const type = target.classList[1];
const scrollArea = $(target).parent().find('.scroll-area');
interval = setInterval(() => {
const prev = scrollArea.scrollLeft();
scrollArea.scrollLeft(type === 'left-arrow' ? prev - 10 : prev + 10);
}, 50);
});
$('.arrow').on('mouseup mouseout', () => clearInterval(interval));
$('.scroll-area').on('scroll', ({ target }) => {
const left = $(target).parent().find('.left-arrow');
const right = $(target).parent().find('.right-arrow');
const scroll = $(target).scrollLeft();
const fullWidth = $(target)[0].scrollWidth - $(target)[0].offsetWidth;
if (scroll === 0) left.addClass('hide');
else left.removeClass('hide');
if (scroll > fullWidth) right.addClass('hide');
else right.removeClass('hide');
});
.container {
width: 550px;
height: 80px;
background: grey;
position: relative;
}
.right-arrow,
.left-arrow {
height: 100%;
width: 50px;
position: absolute;
display: flex;
justify-content: center;
align-items: center;
font-size: 2rem;
cursor: pointer;
transition: all 0.2s linear;
}
.scroll-area {
white-space: nowrap;
overflow-x: scroll;
height: 100%;
}
.right-arrow {
background: linear-gradient(-90deg, orange 0%, rgba(0, 0, 0, 0) 100%);
left: 500px;
}
.left-arrow {
background: linear-gradient(90deg, orange 0%, rgba(0, 0, 0, 0) 100%);
left: 0px;
}
.scroll-btn {
pointer-events: none;
}
.hide {
opacity: 0;
}
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<div class="container">
<div class="arrow left-arrow">
<div class="scroll-btn" id="left-arrow"><</div>
</div>
<div class="arrow right-arrow">
<div class="scroll-btn" id="right-arrow">></div>
</div>
<div class="scroll-area">
<div class="text">
Scroll to right. The gradients and arrows should appear and disappear based on the scroll position. It should work with more than one
container. Lorem ipsum.
</div>
</div>
</div>
PS: If you don't like the fade effect, remove the transition: all 0.2s linear; part of the CSS, and switch .hide's opacity: 0 to visibility: hidden.

Change CSS of one element when another element is in view

I am creating a web page with an Index along one side, with anchor links to each relevant section on the page.
Upon loading the page, the first point on the index list is highlighted (different colour), when the user scrolls down manually to another section, I want the corresponding point on the index list to then become highlighted.
So I have a CSS property, to highlight the index point, and this is initially set to the first point on the list.
How can I take this CSS property from one element, and give it to another?
.current {
opacity: 1;
-webkit-transition: opacity 200ms ease;
transition: opacity 200ms ease;
}
This is the CSS applied to the element that should be highlighted. Currently, the first element in the index is always highlighted, but of course, I need it to change as the user scrolls down the page.
Let me know if you need more info.
It is possible with Intersection Observer API .
Example Code using jQuery:
$(window).scroll(function() {
var scrollDistance = $(window).scrollTop();
var threshold=250; //in px
$('section').each(function(i) //list of sections tag to loop
{
if ($(this).position().top-threshold <= scrollDistance && i<4) {
$('.nav-menu li.menu-active').removeClass('menu-active');
$('.nav-menu li').eq(i).addClass('menu-active');
}
});
}).scroll();
Please see this fiddle. https://jsfiddle.net/cse_tushar/Dxtyu/141/
HTML :-
<div class="m1 menu">
<div id="menu-center">
<ul>
<li><a class="active" href="#home">Home</a>
</li>
<li>Portfolio
</li>
<li>About
</li>
<li>Contact
</li>
</ul>
</div>
</div>
<div id="home"></div>
<div id="portfolio"></div>
<div id="about"></div>
<div id="contact"></div>
CSS:-
body, html {
margin: 0;
padding: 0;
height: 100%;
width: 100%;
}
.menu {
width: 100%;
height: 75px;
background-color: rgba(0, 0, 0, 1);
position: fixed;
background-color:rgba(4, 180, 49, 0.6);
-webkit-transition: all 0.3s ease;
-moz-transition: all 0.3s ease;
-o-transition: all 0.3s ease;
transition: all 0.3s ease;
}
.light-menu {
width: 100%;
height: 75px;
background-color: rgba(255, 255, 255, 1);
position: fixed;
background-color:rgba(4, 180, 49, 0.6);
-webkit-transition: all 0.3s ease;
-moz-transition: all 0.3s ease;
-o-transition: all 0.3s ease;
transition: all 0.3s ease;
}
#menu-center {
width: 980px;
height: 75px;
margin: 0 auto;
}
#menu-center ul {
margin: 15px 0 0 0;
}
#menu-center ul li {
list-style: none;
margin: 0 30px 0 0;
display: inline;
}
.active {
font-family:'Droid Sans', serif;
font-size: 14px;
color: #fff;
text-decoration: none;
line-height: 50px;
}
a {
font-family:'Droid Sans', serif;
font-size: 14px;
color: black;
text-decoration: none;
line-height: 50px;
}
#home {
background-color: grey;
height: 100%;
width: 100%;
overflow: hidden;
background-image: url(images/home-bg2.png);
}
#portfolio {
background-image: url(images/portfolio-bg.png);
height: 100%;
width: 100%;
}
#about {
background-color: blue;
height: 100%;
width: 100%;
}
#contact {
background-color: red;
height: 100%;
width: 100%;
}
Jquery:-
$(document).ready(function () {
$(document).on("scroll", onScroll);
//smoothscroll
$('a[href^="#"]').on('click', function (e) {
e.preventDefault();
$(document).off("scroll");
$('a').each(function () {
$(this).removeClass('active');
})
$(this).addClass('active');
var target = this.hash,
menu = target;
$target = $(target);
$('html, body').stop().animate({
'scrollTop': $target.offset().top+2
}, 500, 'swing', function () {
window.location.hash = target;
$(document).on("scroll", onScroll);
});
});
});
function onScroll(event){
var scrollPos = $(document).scrollTop();
$('#menu-center a').each(function () {
var currLink = $(this);
var refElement = $(currLink.attr("href"));
if (refElement.position().top <= scrollPos && refElement.position().top + refElement.height() > scrollPos) {
$('#menu-center ul li a').removeClass("active");
currLink.addClass("active");
}
else{
currLink.removeClass("active");
}
});
}
Please add just active class to the current button (highlight it)
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
/* Style the buttons */
.btn {
border: none;
outline: none;
padding: 10px 16px;
background-color: #f1f1f1;
cursor: pointer;
font-size: 18px;
}
/* Style the active class, and buttons on mouse-over */
.active, .btn:hover {
background-color: #666;
color: white;
}
</style>
</head>
<body>
<h1>Active Button</h1>
<p>Highlight the active/current (pressed) button.</p>
<div id="myDIV">
<button class="btn">1</button>
<button class="btn active">2</button>
<button class="btn">3</button>
<button class="btn">4</button>
<button class="btn">5</button>
</div>
<script>
// Add active class to the current button (highlight it)
var header = document.getElementById("myDIV");
var btns = header.getElementsByClassName("btn");
for (var i = 0; i < btns.length; i++) {
btns[i].addEventListener("click", function() {
var current = document.getElementsByClassName("active");
current[0].className = current[0].className.replace(" active", "");
this.className += " active";
});
}
</script>
</body>
</html>
You can use the onScroll event to so that a function is triggered when a user scrolls. This can then use scrollTop to get the position.
document.getElementById("idOfScrollingSection").onscroll(() => {
let scrollValue = document.getElementById("elementId").scrollTop;
//Remove class from highlighted item
let oldElement = document.getElementsByClassName("current");
oldElement.classList.remove("current");
//Add highlight class, change values depending on page position
if (scrollValue < 200) {
let elementToBeHighlighted = document.getElementById("idOfElementToBeHighlighted");
elementToBeHighlighted.classList.add("current");
} else if ....
} else {
let elementToBeHighlighted = document.getElementById("idOfElementToBeHighlighted");
elementToBeHighlighted.classList.add("current");
}
})
This is done is pure JS and would be a lot better using jQuery

Why is my responsive navigation bar, made with Javascript, working only after refresh in iPhone browsers?

If a user, using iPhone (actual devices), lands on my website for the first time the "hamburger menu" will not open the menu at all, and navbar will not appear on scrolldown. It seems to be working just fine on Android devices (except maybe Nexus 4 in portrait mode if we were to believe responsinator ), and Win desktops.
The actual website's backend is made with Razor/ASP.NET but obviously I believe this is a pure frontend issue.
After a refresh it starts to work on Apple devices (well, iPhone) as well. And then sometimes stops working (once or twice it stopped working again, I believe).
Head (tried removing async and defer, did not work):
<script type="text/javascript" src="script.js" async defer></script>
Here is HTML (with bad usage of h2 tag with logo image in it):
<div id="navigation-main">
<h2 class="logo">
<a href="#">
<img src="images/white-logo.png" alt="">
</a>
</h2>
<div id="menu-icon">
<span class="icon-menu-hamburguer"></span>
</div>
<nav id="menu-main">
<ul>
<li><a class="scroll" href="#about-anchor">About us</a></li>
<li><a class="scroll" href="#agenda-anchor">Agenda</a></li>
<li><a class="scroll" href="#gallery-anchor">Gallery</a></li>
<li><a class="scroll" href="#sponsors-anchor">Sponsors</a></li>
<li><a class="scroll" href="#contact-anchor">Contact</a></li>
<li>Log in <img src="images/login_icon.png" alt=""></li>
</ul>
</nav>
CSS:
#navigation-main {
min-height: 60px;
z-index: 9;
overflow: hidden;
-webkit-transition: all 0.5s linear;
-moz-transition: all 0.5s linear;
-ms-transition: all 0.5s linear;
-o-transition: all 0.5s linear;
transition: all 0.5s linear;
}
#navigation-main:active {
background-color: #000000;
}
#navigation-main .logo {
float: left;
}
#navigation-main .logo img {
display: none;
}
#navigation-main nav {
position: relative;
top: 20px;
}
#navigation-main nav ul {
margin: 0;
padding-left: 0;
}
#navigation-main nav ul li {
list-style: none
}
#navigation-main nav ul li a {
color: #FFFFFF;
text-decoration: none
}
#navigation-main #menu-icon {
display: none;
}
#navigation-main.active {
background-color: rgb(0, 0, 0);
position: fixed;
top: 0;
height: 60px;
width: 100%;
margin-bottom: 0;
-webkit-transition: all 0.5s linear;
-moz-transition: all 0.5s linear;
-ms-transition: all 0.5s linear;
-o-transition: all 0.5s linear;
transition: all 0.5s linear;
}
#navigation-main.active img {
display: inline-block;
}
#navigation-main.active #menu-icon {
top: 10px;
}
#navigation-main.active .logo img {
max-width: 50%;
}
#navigation-main.active nav li a {
color: #FFFFFF
}
#navigation-main nav ul li img {
vertical-align: middle;
}
#media (max-width: 768px) {
#navigation-main .logo img {
max-width: 80%
}
#navigation-main #menu-icon {
padding: 18px 12px;
margin: 2px 0;
position: relative;
top: 20px;
display: block;
float: right;
z-index: 10;
cursor: pointer;
}
#navigation-main #menu-icon .icon-menu-hamburguer {
background: #ff0000;
width: 30px;
height: 4px;
margin: 2px 0;
display: block;
}
#navigation-main #menu-icon .icon-menu-hamburguer:after,
#navigation-main #menu-icon .icon-menu-hamburguer:before {
content: '';
background: #ff0000;
width: 30px;
height: 4px;
display: block;
margin: 2px 0;
position: relative;
}
#navigation-main #menu-icon .icon-menu-hamburguer:before {
bottom: 8px;
}
#navigation-main #menu-icon .icon-menu-hamburguer:after {
top: 2px;
}
#navigation-main nav {
display: none;
width: 100%;
}
#navigation-main nav.menu-active {
display: block;
clear: both;
height: 100%;
position: fixed;
z-index: 1;
left: 0;
top: 0;
background-color: rgb(0, 0, 0);
background-color: rgba(0, 0, 0, 0.80);
overflow-x: hidden;
}
#navigation-main nav.menu-active ul {
position: relative;
top: 15%;
width: 100%;
text-align: center;
margin-top: 30px;
}
#navigation-main nav.menu-active a {
padding: 8px;
text-decoration: none;
font-size: 1.75rem;
display: block;
}
}
#media (min-width: 768px) {
#navigation-main nav {
float: right;
padding-right: 20px;
}
#navigation-main nav ul li,
#navigation-main nav ul li img {
display: inline-block;
}
#navigation-main nav ul li a {
padding: 0 5px;
font-size: 0.9rem;
}
}
Javascript:
(function() {
////////// Sticky navbar and hamburger icon
var headerScroll = getId('navigation-main'),
scrollHeight = 250,
menuIcon = getId('menu-icon'),
menuMain = getId('menu-main'),
classMenu = 'menu-active',
classHeader = 'active';
// Scroll
window.addEventListener("scroll", scrollOn);
function scrollOn() {
animatedScroll(headerScroll, classHeader, scrollHeight);
}
// Responsive menu
menuIcon.onclick = function() {
toggle(menuMain, classMenu);
}
menuMain.onclick = function() {
toggle(menuMain, classMenu);
}
// Moving the element after scrolling
function animatedScroll(element, classN, height) {
y = pageYOffset;
if (y > height) {
element.className = classN;
} else {
element.className = '';
}
}
// Change the element's class
function toggle(element, classe) {
element.className = element.className ? '' : classe;
}
// Return the element
function getId(id) {
return document.getElementById(id);
}
////////// Sticky navbar and hamburger icon
// Feature Test
if ('querySelector' in document && 'addEventListener' in window && Array.prototype.forEach) {
// Function to animate the scroll
var smoothScroll = function(anchor, duration) {
// Calculate how far and how fast to scroll
var startLocation = window.pageYOffset;
var endLocation = anchor.offsetTop;
var distance = endLocation - startLocation;
var increments = distance / (duration / 16);
var stopAnimation;
// Scroll the page by an increment, and check if it's time to stop
var animateScroll = function() {
window.scrollBy(0, increments);
stopAnimation();
};
// If scrolling down
if (increments >= 0) {
// Stop animation when you reach the anchor OR the bottom of the page
stopAnimation = function() {
var travelled = window.pageYOffset;
if ((travelled >= (endLocation - increments)) || ((window.innerHeight + travelled) >= document.body.offsetHeight)) {
clearInterval(runAnimation);
}
};
}
// If scrolling up
else {
// Stop animation when you reach the anchor OR the top of the page
stopAnimation = function() {
var travelled = window.pageYOffset;
if (travelled <= (endLocation || 0)) {
clearInterval(runAnimation);
}
};
}
// Loop the animation function
var runAnimation = setInterval(animateScroll, 16);
};
// Define smooth scroll links
var scrollToggle = document.querySelectorAll('.scroll');
// For each smooth scroll link
[].forEach.call(scrollToggle, function(toggle) {
// When the smooth scroll link is clicked
toggle.addEventListener('click', function(e) {
// Prevent the default link behavior
e.preventDefault();
// Get anchor link and calculate distance from the top
var dataID = toggle.getAttribute('href');
var dataTarget = document.querySelector(dataID);
var dataSpeed = toggle.getAttribute('data-speed');
// If the anchor exists
if (dataTarget) {
// Scroll to the anchor
smoothScroll(dataTarget, dataSpeed || 500);
}
}, false);
});
}
})();
And here is JSFiddle.
If it's touchstart/onclick issue why does it work after the refresh? Should I remove IFFE? Should I put script tag at the end of the page?
What seems to be the issue here?
Apparently the line in the header was an issue.I have removed "async" and the navigation menu started working.
<script type="text/javascript" src="script.js" async defer></script>
changed to:
<script type="text/javascript" src="script.js" defer></script>

fullpage.js - expanding circles background cover up the text

I have a website with expanding circles and text on top of that. The website was working fine, till I added the jquery fullpage.js plugin. Now, the expanding circles come on top of the text and covers it up entirely. I have tried giving the text a higher z-index and tried it both with absolute and relative positioning, but nothing seems to work. Can anyone help me out with this?
link to website: https://rimildeyjsr.github.io/spotify-circle-animation/
HTML:
<div id="fullpage">
<div class="section active" id="section1">
<div class="button_container" id="toggle">
<span class="top"></span>
<span class="middle"></span>
<span class="bottom"></span>
</div>
<div class="overlay" id="overlay">
<nav class="overlay-menu">
<ul>
<li >Home</li>
<li>About</li>
<li>Projects</li>
<li>Blog</li>
<li>Contact</li>
</ul>
</nav>
</div>
<div class="main-heading">
<span id="main-heading"></span>
</div>
<span id="welcome-msg">Welcome to my website</span>
</div>
<div class="section">
</div>
</div>
CSS:
.initial-div {
width: 1000px;
height: 1000px;
transform: scale(0);
}
.position-div{
position: absolute;
border-radius: 50%;
display: none;
}
.animate {
-webkit-animation: expand 2500s;
}
#-webkit-keyframes expand {
0%{
-webkit-transform: scale(0,0);
}
100%{
-webkit-transform: scale(100.0,100.0);
display: none;
}
}
.main-heading{
text-align:left;
z-index: 20;
position: relative;
display: block;
height:228px;
width:644px;
font-family: Graphik, Roboto;
font-size: 10em;
font-weight: 600;
letter-spacing: 0.2px;
color: #ffffff;
top: 23%;
left: 8%;
}
#welcome-msg {
display: block;
z-index: 20;
position: relative;
text-align: left;
font-size: 4em;
font-family: Graphik,Roboto;
color: #ffffff;
height: 198px;
width: 1138px;
font-weight: 600;
top: 24%;
left: 8%;
}
Jquery:
var animationEnd = 'webkitAnimationEnd mozAnimationEnd MSAnimationEnd oanimationend animationend';
function makeDiv(color){
var divsize = 1000;
//$('body').css({'background-color':bgColor});
console.log(1);
$newdiv = $('<div/>').addClass('initial-div').css({
'background-color': color
});
var posx = (Math.random() * ($(document).width()) - (divsize / 2)).toFixed();
var posy = (Math.random() * ($(document).height()) - (divsize / 2)).toFixed();
$newdiv.addClass('position-div').css({
'left':posx+'px',
'top':posy+'px'
}).appendTo( 'body' ).addClass('animate').css({'display':'block'}).one(animationEnd,function(){
$(this).remove();
});
}
$(document).ready(function(){
$('#fullpage').fullpage({
anchors: ['home'],
fixedElements: '#toggle,#overlay'
});
$("#main-heading").delay(2000).css("visibility","visible").typed({
strings:["^1000Hello,","Bonjour,","Hola,","nuqneH,","Ola,","Hallo,","سلام"
,"Ciao,"],
typeSpeed: 300,
loop: true,
showCursor: true,
cursorChar: "|",
preStringTyped: function(){
$(".main-heading").css("visibility","visible");
},
onStringTyped: function(){
$('.button-launch').addClass("animated slideInDown").css("visibility","visible")
;
}
});
$('#toggle').click(function() {
$('#toggle').toggleClass('active');
$('#overlay').toggleClass('open');
});
$('#overlay ul li a').click(function() {
$('#toggle').toggleClass('active');
$('#overlay').toggleClass('open');
});
//var arrayLength = colorArray.length;
var colorArray = ['#11256c','#24ccdf'];
var i= 0,flag=0;
var color = colorArray[i];
setInterval(function(){
flag++;
makeDiv(color);
if (flag == 15){
color = colorArray[i];
i++;
if (i == 2) {
i = 0;
}
flag=0;
}
},2000);
});
Link to github repository: https://github.com/rimildeyjsr/spotify-circle-animation
hello add this css in your file for remove applied CSS transformation and its work
#fullpage {
-webkit-transform: none !important;
transform: none !important;
}
In your case try this
#fullpage {
z-index: 2;
}

scroll to section by section

I have HTML markup:
HTML:
<body>
<header></header>
<nav>
<ul>
<li>one</li>
<li>two</li>
</ul>
</nav>
<section id="one"></section>
<section id="two"></section>
<footer></footer>
</body>
where section is fullscreen (width: 100%; height:100%;) and menu have absolute position.
Question:
How can I use mouse scroll (or keys ) to scroll and snap to each section?
When scroll to last section then scroll-down to #one again and repeat it.
When I click on link, it scroll to section.
Thank you for your suggestions, ideas, code.
Interesting
I stole this code, changed the layout and tried to add the functions you mentioned (1. scroll-snap + 2. scroll when link is clicked).
Unfortunately, I can't have this second function to work.
Adding scroll-snap is not a problem
You need scroll-snap-type: y mandatory; on the container and scroll-snap-align: start; on the sections.
var doc = window.document,
context = doc.querySelector('.js-loop'),
clones = context.querySelectorAll('.is-clone'),
disableScroll = false,
scrollHeight = 0,
scrollPos = 0,
clonesHeight = 0,
i = 0;
function getScrollPos () {
return (context.pageYOffset || context.scrollTop) - (context.clientTop || 0);
}
function setScrollPos (pos) {
context.scrollTop = pos;
}
function getClonesHeight () {
clonesHeight = 0;
for (i = 0; i < clones.length; i += 1) {
clonesHeight = clonesHeight + clones[i].offsetHeight;
}
return clonesHeight;
}
function reCalc () {
scrollPos = getScrollPos();
scrollHeight = context.scrollHeight;
clonesHeight = getClonesHeight();
if (scrollPos <= 0) {
setScrollPos(1); // Scroll 1 pixel to allow upwards scrolling
}
}
function scrollUpdate () {
if (!disableScroll) {
scrollPos = getScrollPos();
if (clonesHeight + scrollPos >= scrollHeight) {
// Scroll to the top when you’ve reached the bottom
setScrollPos(1); // Scroll down 1 pixel to allow upwards scrolling
disableScroll = true;
} else if (scrollPos <= 0) {
// Scroll to the bottom when you reach the top
setScrollPos(scrollHeight - clonesHeight);
disableScroll = true;
}
}
if (disableScroll) {
// Disable scroll-jumping for a short time to avoid flickering
window.setTimeout(function () {
disableScroll = false;
}, 40);
}
}
function init () {
reCalc();
context.addEventListener('scroll', function () {
window.requestAnimationFrame(scrollUpdate);
}, false);
window.addEventListener('resize', function () {
window.requestAnimationFrame(reCalc);
}, false);
}
if (document.readyState !== 'loading') {
init()
} else {
doc.addEventListener('DOMContentLoaded', init, false)
}
html,
body {
height: 100%;
overflow: hidden;
}
.Loop {
position: relative;
height: 100%;
overflow: scroll;
-webkit-overflow-scrolling: touch;
scroll-snap-type: y mandatory;
}
section {
position: relative;
text-align: center;
height: 100%;
scroll-snap-align: start;
}
::scrollbar {
display: none;
}
body {
font-family: "Avenir Next", Helvetica, sans-serif;
font-weight: normal;
font-size: 100%;
position: relative;
}
nav {
position: absolute;
top: 0;
left: 0;
width: 100%;
z-index: 10;
}
nav ul {
display: flex;
justify-content: space-around;
margin: 0;
padding: 1rem 0;
}
nav ul li{
display: flex;
justify-content: space-around;
}
.nav-link{
text-decoration: none;
color: grey
}
.one {
background: black;
}
.two {
background: darkblue;
}
.three {
background: lightgreen;
}
.four {
background: lightcoral;
}
.five {
background: lightskyblue;
}
.six {
background: orange;
}
h1 {
margin: 0;
position: absolute;
top: 50%;
transform: translateY(-50%);
width: 100%;
font-size: 80px;
letter-spacing: 5px;
color: #fff;
text-transform: uppercase;
}
<nav>
<ul>
<li><a class="nav-link" href="#one">one</a></li>
<li><a class="nav-link" href="#two">two</a></li>
<li><a class="nav-link" href="#three">three</a></li>
<li><a class="nav-link" href="#four">four</a></li>
<li><a class="nav-link" href="#five">five</a></li>
<li><a class="nav-link" href="#six">six</a></li>
</ul>
</nav>
<main class="Loop js-loop">
<section class="one" id="one">
<h1>One</h1>
</section>
<section class="two" id="two">
<h1>Two</h1>
</section>
<section class="three" id="three">
<h1>Three</h1>
</section>
<section class="four" id="four">
<h1>Four</h1>
</section>
<section class="five" id="five">
<h1>Five</h1>
</section>
<section class="six" id="six">
<h1>Six</h1>
</section>
<!--
These blocks are the same as the first blocks to get that looping illusion going.
You need to add clones to fill out a full viewport height.
-->
<section class="one is-clone">
<h1>One</h1>
</section>
<section class="two is-clone">
<h1>Two</h1>
</section>
</main>
Adding the scrolling when you click on the link is a problem
With a normal container you only need to add the scroll-behaviour: smooth; to it. But here if you do that, you will lose the loop illusion because you will see it scroll back to the first instead of seemingly continue. (and it will also start an infinite back and forth scrolling that I couldn't fix yet)
var doc = window.document,
context = doc.querySelector('.js-loop'),
clones = context.querySelectorAll('.is-clone'),
disableScroll = false,
scrollHeight = 0,
scrollPos = 0,
clonesHeight = 0,
i = 0;
function getScrollPos () {
return (context.pageYOffset || context.scrollTop) - (context.clientTop || 0);
}
function setScrollPos (pos) {
context.scrollTop = pos;
}
function getClonesHeight () {
clonesHeight = 0;
for (i = 0; i < clones.length; i += 1) {
clonesHeight = clonesHeight + clones[i].offsetHeight;
}
return clonesHeight;
}
function reCalc () {
scrollPos = getScrollPos();
scrollHeight = context.scrollHeight;
clonesHeight = getClonesHeight();
if (scrollPos <= 0) {
setScrollPos(1); // Scroll 1 pixel to allow upwards scrolling
}
}
function scrollUpdate () {
if (!disableScroll) {
scrollPos = getScrollPos();
if (clonesHeight + scrollPos >= scrollHeight) {
// Scroll to the top when you’ve reached the bottom
setScrollPos(1); // Scroll down 1 pixel to allow upwards scrolling
disableScroll = true;
} else if (scrollPos <= 0) {
// Scroll to the bottom when you reach the top
setScrollPos(scrollHeight - clonesHeight);
disableScroll = true;
}
}
if (disableScroll) {
// Disable scroll-jumping for a short time to avoid flickering
window.setTimeout(function () {
disableScroll = false;
}, 40);
}
}
function init () {
reCalc();
context.addEventListener('scroll', function () {
window.requestAnimationFrame(scrollUpdate);
}, false);
window.addEventListener('resize', function () {
window.requestAnimationFrame(reCalc);
}, false);
}
if (document.readyState !== 'loading') {
init()
} else {
doc.addEventListener('DOMContentLoaded', init, false)
}
html,
body {
height: 100%;
overflow: hidden;
}
.Loop {
position: relative;
height: 100%;
overflow: scroll;
-webkit-overflow-scrolling: touch;
scroll-snap-type: y mandatory;
scroll-behavior: smooth;
}
section {
position: relative;
text-align: center;
height: 100%;
scroll-snap-align: start;
}
::scrollbar {
display: none;
}
body {
font-family: "Avenir Next", Helvetica, sans-serif;
font-weight: normal;
font-size: 100%;
position: relative;
}
nav {
position: absolute;
top: 0;
left: 0;
width: 100%;
z-index: 10;
}
nav ul {
display: flex;
justify-content: space-around;
margin: 0;
padding: 1rem 0;
}
nav ul li{
display: flex;
justify-content: space-around;
}
.nav-link{
text-decoration: none;
color: grey
}
.one {
background: black;
}
.two {
background: darkblue;
}
.three {
background: lightgreen;
}
.four {
background: lightcoral;
}
.five {
background: lightskyblue;
}
.six {
background: orange;
}
h1 {
margin: 0;
position: absolute;
top: 50%;
transform: translateY(-50%);
width: 100%;
font-size: 80px;
letter-spacing: 5px;
color: #fff;
text-transform: uppercase;
}
<nav>
<ul>
<li><a class="nav-link" href="#one">one</a></li>
<li><a class="nav-link" href="#two">two</a></li>
<li><a class="nav-link" href="#three">three</a></li>
<li><a class="nav-link" href="#four">four</a></li>
<li><a class="nav-link" href="#five">five</a></li>
<li><a class="nav-link" href="#six">six</a></li>
</ul>
</nav>
<main class="Loop js-loop">
<section class="one" id="one">
<h1>One</h1>
</section>
<section class="two" id="two">
<h1>Two</h1>
</section>
<section class="three" id="three">
<h1>Three</h1>
</section>
<section class="four" id="four">
<h1>Four</h1>
</section>
<section class="five" id="five">
<h1>Five</h1>
</section>
<section class="six" id="six">
<h1>Six</h1>
</section>
<!--
This block is the same as the first block to get that looping illusion going.
You need to add clones to fill out a full viewport height.
-->
<section class="one is-clone">
<h1>One</h1>
</section>
<section class="two is-clone">
<h1>Two</h1>
</section>
</main>
I know this code is not 100% functional yet, but I think it can lead us to a better answer.
You can use ID in this case.
Set the ID for your section and add anchor tag and set href attribute to your section id.
Go Up <!-- don't forget # before write your ID. -->
Don't forget set scroll-behavior to smooth for smooth scrolling.

Categories

Resources