Change CSS of one element when another element is in view - javascript

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

Related

Using jquery and css how do I create a delayed background color change animation?

I have a javascript-powered searchable html list. When the user types in some text that hones the list down to one result, I want the ".opaqueblock" div background to turn into a brighter color and then turn back to the original color after a quick delay. At the moment the color changes smoothly to a brighter when the user types in "Text 53" in the search box, but I can't figure out how to change the color back to the original darker color. I want a bright flash effect. Also, the each() function that I try to use to only change the background color of the isolated item "Text 53" is changing the background color of all the items. I do not want the color to change for list items that are hidden. Does anyone know a solution?
<script type="text/javascript" src="https://code.jquery.com/jquery-1.9.0.min.js""></script>
<script type="text/javascript" src="https://code.jquery.com/color/jquery.color-2.1.2.min.js"></script>
<link href='https://fonts.googleapis.com/css?family=Comfortaa' rel='stylesheet'> <!--for search text-->
<link href='https://fonts.googleapis.com/css?family=Nunito' rel='stylesheet'> <!--for search text-->
<script>
function ListSearch() {
var input, filter, ul, li, a, i, txtValue, resultsCount = 0, resultText = " results"; // Declare variables
input = document.getElementById('myInput');
filter = input.value.toUpperCase();
ul = document.getElementById("DocumentList");
li = ul.getElementsByTagName('li');
$('.opaqueBlock').css('border-color','transparent') //remove all borders in case a border was added when the results were honed down to 1
for (i = 0; i < li.length; i++) { // Loop through all list items, hide those that don't match query
a = li[i].getElementsByTagName("div")[0];
txtValue = a.textContent || a.innerText;
if (txtValue.toUpperCase().indexOf(filter) > -1) {
li[i].style.display = "";
resultsCount++;
} else {
li[i].style.display = "none";
}
}
if (resultsCount == 1) {
$('.opaqueBlock').css('border-color','#68e8d5');
$('.PreviewArrow').css("opacity", "1"); document.getElementById("results_span").style.color = "#b6fbd2";
resultText = " result";
$(".opaqueBlock:visible").each(
$('.opaqueBlock').delay(300).css("background-color", "rgba(147,185,212,0.6)")
/* $('.opaqueBlock').delay(300).css("background-color", "rgba(72,97,115,0.6)"); */
);
}
else if(resultsCount < 1){document.getElementById("results_span").style.color = "#fbb6bc";}
else if(resultsCount < 3){document.getElementById("results_span").style.color = "#b6fbd2";}
else if(resultsCount < 4){document.getElementById("results_span").style.color = "#b6d7fb";}
else if(resultsCount < 5){document.getElementById("results_span").style.color = "#eeb8ff";}
else {document.getElementById("results_span").style.color = "#fbb6bc";}
document.getElementById("results_span").innerHTML = resultsCount + resultText;
}
$(document).ready(function(){
function HoverOverItem(thisParticularItem, DocImageLink){
if (!thisParticularItem.hasClass("active_form_item") ) {
$(".PreviewContainer").css("opacity", "0.3");
$(".PreviewContainer").css("background-image", DocImageLink);
$(".PreviewContainer").animate({'opacity': '1'},500);
$("#ContentContainer").find('.active_form_item').removeClass('active_form_item');
thisParticularItem.addClass("active_form_item");
}
}
});
$(window).load(function(){
$("#myInput").focus();
var ul, li, resultsCount = 0, resultText = " searchable documents"; // Declare variables
ul = document.getElementById("DocumentList");
li = ul.getElementsByTagName('li');
for (i = 0; i < li.length; i++) {resultsCount++;} // Loop through all list items to get a count
document.getElementById("results_span").innerHTML = resultsCount + resultText;
});
</script>
<style>
#ContentContainer{
height: 700px;
background-color: #132e54;
}
#ContentContainer a{text-decoration: none;}
#ContentContainer img{border: none;}
#search_prompt_div{margin-left: 16px;}
#search_prompt_div p{color: white; font-size: 14px; margin-bottom: 12px; font-family: comfortaa;}
#search_prompt_div input{height: 25px;font-size: 16px; width: 300px; font-family: comfortaa;}
#search_prompt_div #results_span{display: inline-block;margin-left: 6px; color: #fbb6bc; font-size: 12px;}
#DocumentListContainer{
height: 600px;
width: 660px;
overflow: hidden;
}
#DocumentList{
list-style-type: none;
margin: 0;
padding: 6px 0 0 0;
width: 105%;
overflow: auto;
height: 893px;
}
.opaqueBlock{
opacity: 1; /*can set this to 0 if you want to animate it*/
margin-left: 56px; /*can set this to 0 if you want to animate it*/
display: inline-block;
width: 490px;
height: 35px;
border: 2px solid transparent;
background-color: rgba(72,97,115,0.6);
border-radius: 10px;
-webkit-transition: all .6s ease;
-moz-transition: all .6s ease;
-ms-transition: all .6s ease;
-o-transition: all .6s ease;
}
.opaqueBlock:hover{
border: 2px solid #5cb1d8;
-ms-filter: "progid:DXImageTransform.Microsoft.Alpha(Opacity=70)";
opacity:0.7 !important;
}
.fileLinkContainer{
width: 630px;
height: 37px;
margin-bottom: 10px;
position: relative;
}
.fileTextSpan{
margin-left: 10px;
color: white;
margin-top: 5px;
font-family: 'Nunito' !important;
font-size: 19px !important;
display: inline-block;
}
</style>
<div id="ContentContainer">
<br><br><br>
<div id="search_prompt_div">
<p>Type something in the search box to find what you are looking for:</p>
<input id="myInput" type="text" placeholder="Search..." onkeyup="ListSearch()">
<span id="results_span"></span>
</div>
<br/><br/><br/>
<div class="PreviewContainer"></div>
<div id="DocumentListContainer">
<ul id="DocumentList">
<li><div class="fileLinkContainer"><div class="opaqueBlock"><span class="fileTextSpan">Text 1</span></div></div></li>
<li><div class="fileLinkContainer"><div class="opaqueBlock"><span class="fileTextSpan">Text 11</span></div></div></li>
<li><div class="fileLinkContainer"><div class="opaqueBlock"><span class="fileTextSpan">Text 21</span></div></div></li>
<li><div class="fileLinkContainer"><div class="opaqueBlock"><span class="fileTextSpan">Text 33</span></div></div></li>
<li><div class="fileLinkContainer"><div class="opaqueBlock"><span class="fileTextSpan">Text 53</span></div></div></li>
</ul>
</div>
</div>
What about to use CSS keyframes somehow like this?
#keyframes anim {
0% { background-color: #fff; }
50%, 70% { background-color: #333; }
100% { background-color: #fff; }
}
Then just toggle class on the element by JS

Menu want get fixed to the top on scroll

I'm trying to accomplish a simple effect of sticking the menu to top of the browser window when scrolling passes a certain point, but something went wrong and the menu wont get fixed to the top. From the libraries I'm using jQuery and animate it.
My code is as follows:
HTML:
<nav class="animatedParent">
<ul class="animated bounceInUp delay-750">
<li class="animated">O meni</li>
<li class="animated">Katalog</li>
<li class="animated">Razno</li>
</ul>
</nav>
CSS:
.fixedNav {
display: block;
position: fixed;
top: 0;
width: 100%;
background: rgba( 0, 0, 0, .8);
height: 100px;
}
nav {
width: 400px;
margin: 20px auto;
}
nav ul {
list-style: none;
}
nav ul li {
float: left;
overflow: auto;
width: 130px;
}
nav ul li a {
font-size: 35px;
font-family: 'Indie Flower', cursive;
color: #fff;
cursor: pointer;
transition: 500ms linear all;
}
nav ul li a:hover {
color: #123456;
transition: 500ms linear all;
}
JS (jQuery):
$(document).ready(function(){
$("nav ul li").mouseenter(function() {
$(this).addClass("wiggle");
});
$("nav ul li").mouseleave(function() {
$(this).removeClass("wiggle");
});
var nav = $("nav").offsetTop();
if($(window).scrollTop() > nav) {
$("nav").addClass("fixedNav");
console.log('Hello!');
} else {
$("nav").removeClass("fixedNav");
}
});
So first off, you only use the code once, which is when the document is loaded. You're going to want to check everytime you scroll the document as the code should obivously be triggered once you scroll a certain amount.
$(document).scroll(function(){
var nav = $("nav").height();
if($(window).scrollTop() > nav) {
$("nav").addClass("fixedNav");
} else {
$("nav").removeClass("fixedNav");
}
});
body {
background: black;
height:700px;
}
.fixedNav {
display: block;
position: fixed;
top: 0;
width: 100%;
background: rgba( 0, 0, 0, .8);
height: 100px;
}
nav {
display: block;
height: 100px;
width: 100%;
margin: 20px auto;
}
nav ul {
list-style: none;
}
nav ul li {
float: left;
overflow: auto;
width: 130px;
}
nav ul li a {
font-size: 35px;
font-family: 'Indie Flower', cursive;
color: #fff;
cursor: pointer;
transition: 500ms linear all;
}
nav ul li a:hover {
color: #123456;
transition: 500ms linear all;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<nav class="animatedParent nav">
<ul class="animated bounceInUp delay-750">
<li class="animated">O meni</li>
<li class="animated">Katalog</li>
<li class="animated">Razno</li>
</ul>
</nav>
You need to use the event scroll and check the offset there.
When the user is scrolling, toggleClass will add/remove the class based on the condition $window.scrollTop() > navOffset which will return true or false
var $window = $(window);
var $nav = $('nav');
var navOffset = $nav.offsetTop();
$window.on('scroll', function() {
$nav.toggleClass('fixedNav', $window.scrollTop() > navOffset);
});
add an scroll event to check your scroll position
for example:
$(document).scroll(()=>{...});
like here
This is a very plain demo, it only demonstrate wha i meant
You can use a library like scrollMonitor to accomplish your task as scroll monitoring have its own caveats.
You can let scrollMonitor to lock position of your menu when it leaves viewport, something like this:
var $menu = document.querySelector('nav'); // It is better to use CSS class name instead
var watcher = scrollMonitor.create($menu);
watcher.lock();
watcher.exitViewport(function() {
$menu.classList.add('fixedNav');
});
watcher.enterViewport(function() {
$menu.classList.remove('fixedNav');
});
Please refer this example as it closely matches your task.
You don't fire the check for the current scroll on scroll event. That's an event you're looking for.
Also you could check the scrollTop on the document (it's more error proof in jQuery), not on the window as it doesn't always work.
$(document).ready(function(){
$("nav ul li").mouseenter(function() {
$(this).addClass("wiggle");
});
$("nav ul li").mouseleave(function() {
$(this).removeClass("wiggle");
});
$(document).on('scroll', function() {
var nav = $("nav").offsetTop();
if($(document).scrollTop() > nav) {
$("nav").addClass("fixedNav");
console.log('Hello!');
} else {
$("nav").removeClass("fixedNav");
}
})
});
That is what you are looking for:
$(document).ready(function(){
$("nav ul li").mouseenter(function() {
$(this).addClass("wiggle");
}) ;
$("nav ul li").mouseleave(function() {
$(this).removeClass("wiggle");
}) ;
});
$(document).ready(fixedHeader) ;
$(window).scroll(fixedHeader) ;
function fixedHeader() {
var nav = parseInt($("nav").css("margin-top")) ;
if($(window).scrollTop() > nav) {
$("nav").addClass("fixedNav");
}
else {
$("nav").removeClass("fixedNav");
}
}
body{
height: 1000px;
}
.fixedNav {
display: block;
position: fixed;
top: 0;
width: 100%;
background: rgba( 0, 0, 0, .8);
height: 100px;
}
nav {
width: 400px;
margin: 20px auto;
}
nav ul {
list-style: none;
}
nav ul li {
float: left;
overflow: auto;
width: 130px;
}
nav ul li a {
font-size: 20px;
font-family: 'Indie Flower', cursive;
color: #fff;
cursor: pointer;
transition: 500ms linear all;
}
nav ul li a:hover {
color: #123456;
transition: 500ms linear all;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<nav class="animatedParent">
<ul class="animated bounceInUp delay-750">
<li class="animated">O meni</li>
<li class="animated">Katalog</li>
<li class="animated">Razno</li>
</ul>
</nav>

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>

Nav buttons that change color when scrolling

I need help. I have a nav bar with buttons. I want them to change color when clicked on and when the scroll bar hits the right anchor (it is a one page website). But the script is not working, only the first button gets white at the beginning but when scrolling....nothing happen. Please Help, I m a dumb truck :-)
// Cache selectors
var lastId,
topMenu = $("#nav"),
topMenuHeight = topMenu.outerHeight() + 15,
// All list items
menuItems = topMenu.find("a"),
// Anchors corresponding to menu items
scrollItems = menuItems.map(function() {
var item = $($(this).attr("href"));
if (item.length) {
return item;
}
});
// Bind click handler to menu items
// so we can get a fancy scroll animation
menuItems.click(function(e) {
var href = $(this).attr("href"),
offsetTop = href === "#" ? 0 : $(href).offset().top - topMenuHeight + 1;
$('html, body').stop().animate({
scrollTop: offsetTop
}, 300);
e.preventDefault();
});
// Bind to scroll
$(window).scroll(function() {
// Get container scroll position
var fromTop = $(this).scrollTop() + topMenuHeight;
// Get id of current scroll item
var cur = scrollItems.map(function() {
if ($(this).offset().top < fromTop)
return this;
});
// Get the id of the current element
cur = cur[cur.length - 1];
var id = cur && cur.length ? cur[0].id : "";
if (lastId !== id) {
lastId = id;
// Set/remove active class
menuItems
.parent().removeClass("active")
.end().filter("[href=#" + id + "]").parent().addClass("active");
}
});
#nav {
width: 100%;
height: 20px;
background-image: url(photos/BG_header2.png);
background-repeat: repeat-x;
display: block;
margin-top: 25px;
margin-left: 390px;
line-height: 17px;
white-space: nowrap;
z-index: 1;
}
#nav2 {
padding-left: 20px;
}
#nav li {
display: inline-block;
margin-top: 0px;
margin-right: 4px;
margin-left: 4px;
margin-bottom: 0px;
text-indent: 3px;
}
#nav a {
color: #006EBE;
width: auto;
text-decoration: none;
font-weight: bold;
font-size: 13px;
font-family: Arial, Helvetica, sans-serif;
text-transform: uppercase;
letter-spacing: 1px;
vertical-align: middle;
-webkit-transition: .5s all ease-out;
-moz-transition: .5s all ease-out;
transition: .5s all ease-out;
}
#nav a:hover {
color: #fff;
}
#nav li.active a {
color: #fff;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<ul id="nav">
<ul id="nav2">
<li class="active">Accueil
</li>
<li class="trait"></li>
<li>L'entreprise
</li>
<li class="trait"></li>
<li>Services
</li>
<li class="trait"></li>
<li>Jobs
</li>
<li class="trait"></li>
<li>Contact
</li>
</ul>
</ul>
</header>
<a id="anchor1"></a>
<a id="anchor2"></a>
<a id="anchor3"></a>
<a id="anchor4"></a>

News/Image Slider for PHP Loop, (JS) Reset Interval on Click & Better Format for Unique ID's

I'm currently setting up a news/image slider on my site via JS. I have the slide data rolling in through a PHP loop with unique ID's. Everything is working smoothly, I just can't figure out how to reset the timer/interval when you manually switch slides.
Also, there has to be a better/easier way to write the manual click navigation I currently have setup with all the unique ID's. I have the loop sliced at 5.
(my code is a mess)
$(document).ready(function(){
$("#newsFeatured article:first").addClass("active");
$("#newsFeatured li:first").addClass("active");
});
var toggleSlide = function(){
$("#newsFeatured article.active").removeClass("active")
.next().add("#newsFeatured article:first").last().addClass("active");
$("#newsFeatured li.active").removeClass("active")
.next().add("#newsFeatured li:first").last().addClass("active");
}
setInterval(toggleSlide, 8000);
$(document).ready(function(){
$("#control1").on('click', function() {
$("#slide1").addClass("active");
$("#slide2, #slide3, #slide4, #slide5").removeClass("active");
$("#control1").addClass("active");
$("#control2, #control3, #control4, #control5").removeClass("active");
clearInterval(toggleSlide);
});
$("#control2").on('click', function() {
$("#slide2").addClass("active");
$("#slide1, #slide3, #slide4, #slide5").removeClass("active");
$("#control2").addClass("active");
$("#control1, #control3, #control4, #control5").removeClass("active");
});
$("#control3").on('click', function() {
$("#slide3").addClass("active");
$("#slide1, #slide2, #slide4, #slide5").removeClass("active");
$("#control3").addClass("active");
$("#control1, #control2, #control4, #control5").removeClass("active");
});
$("#control4").on('click', function() {
$("#slide4").addClass("active");
$("#slide1, #slide2, #slide3, #slide5").removeClass("active");
$("#control4").addClass("active");
$("#control1, #control2, #control3, #control5").removeClass("active");
});
$("#control5").on('click', function() {
$("#slide5").addClass("active");
$("#slide1, #slide2, #slide3, #slide4").removeClass("active");
$("#control5").addClass("active");
$("#control1, #control2, #control3, #control4").removeClass("active");
});
});
https://jsfiddle.net/aor1xmb5/
Lastly, i'm interested in getting my slide to interact with touch for mobile devices, if anyone can point me in the direction of a good tutorial on getting that started.
Thanks!
Clearing intervals is fairly simple:
function myFn() {console.log('idle');}
var myTimer = setInterval(myFn, 4000);
// Then, later at some future time,
// to restart a new 4 second interval starting at this exact moment in time
clearInterval(myTimer);
myTimer = setInterval(myFn, 4000);
Please check the snippet:
$(function() {
$("#newsFeatured article:first").addClass("active");
$("#newsFeatured li:first").addClass("active");
var sliderInterval = setInterval(toggleSlide, 8000);
$('.featuredControls').on('click', 'li', function() {
var $this = $(this),
id = $this.attr('id'),
index = id.replace('control', '');
slideTo(index);
// Clear interval.
clearInterval(sliderInterval);
sliderInterval = setInterval(toggleSlide, 8000);
});
function slideTo(index) {
var id = '#control' + index,
$this = $(id);
// Highlight active slide.
$(".featuredSlide").removeClass("active");
$("#slide" + index).addClass("active");
// Highlight active control.
$this.parent().find('li').removeClass("active");
$this.addClass("active");
}
function toggleSlide() {
// Get current slide.
var id,
index,
$next = $(".featuredControls .active").next();
// If last item, start over.
if ($next.length === 0) {
$next = $(".featuredControls li").first();
}
id = $next.attr('id'),
index = id.replace('control', '');
slideTo(index);
};
});
/* NEWS FEATURED SLIDER */
#newsFeatured {
position: relative;
height: 300px;
transition: 0.1s all linear;
}
#newsFeatured:hover {
box-shadow: -6px 0px 0px 0px #ffc60d;
}
.featuredControls {
opacity: 0;
position: absolute;
list-style-type: none;
right: 30px;
margin: 0;
padding: 20px;
z-index: 1;
transition: 0.2s all linear;
}
#newsFeatured:hover .featuredControls {
opacity: 1;
right: 0;
}
.featuredControls li {
background: rgba(0, 0, 0, 0.7);
display: inline-block;
height: 20px;
width: 15px;
border: 0;
border-radius: 3px;
cursor: pointer;
}
.featuredControls li.active {
background: #ffc60d;
}
.featuredSlide {
display: none;
background: rgba(0, 0, 0, 0.3);
position: absolute;
left: 0;
width: 100%;
height: 300px;
overflow: hidden;
}
#newsFeatured:hover .featuredSlide {
box-shadow: -1px 0px 0px 0px #101415;
}
#newsFeatured article.active {
display: block;
}
.featuredImage {
width: 100%;
height: 100%;
background-size: cover;
background-position: 50% 50%;
background-repeat: no-repeat;
transition: 0.3s all ease;
animation: featuredImage ease 1;
animation-duration: 1s;
}
#keyframes featuredImage {
from {
opacity: 0;
background-position: 30% 50%;
}
to {
opacity: 1;
background-position: 50% 50%;
}
}
.featuredContent {
width: 100%;
padding: 20px;
background: rgba(0, 0, 0, 0.65);
position: absolute;
bottom: 0;
transition: 0.5s all ease;
}
.featuredContent h2 {
font-size: 16px;
font-weight: normal;
text-transform: uppercase;
margin: 0;
animation: featuredTitle ease 1;
animation-duration: 1s;
}
#keyframes featuredTitle {
from {
padding-left: 75px;
opacity: 0;
}
to {
padding-left: 0;
opacity: 1;
}
}
.featuredContent h2 a {
color: #ffc60d;
margin: 0 0 5px 0;
transition: 0.1s all linear;
}
#newsFeatured:hover .featuredContent h2 a {
color: #eee;
}
.featuredContent section {
color: #a7a397;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id='newsFeatured' class='ipsClearfix'>
<ul class='featuredControls'>
<li id='control1'></li>
<li id='control2'></li>
</ul>
<article id='slide1' class='featuredSlide'>
<a href=''>
<div class='featuredImage' style='background-image: url(http://i.imgur.com/udTA5il.jpg);'></div>
</a>
<div class='featuredContent'>
<h2>
First Slide Title
</h2>
<section class='ipsType_normal ipsType_richText ipsType_break'>First slide description.</section>
</div>
</article>
<article id='slide2' class='featuredSlide'>
<a href=''>
<div class='featuredImage' style='background-image: url(http://i.imgur.com/SWy0AHZ.jpg);'></div>
</a>
<div class='featuredContent'>
<h2>
Second Slide Title
</h2>
<section class='ipsType_normal ipsType_richText ipsType_break'>Second slide description.</section>
</div>
</article>
</div>

Categories

Resources