How to add active class to selected list item - javascript

Hi I'm trying to add class to the selectedlList item & also add class if I scroll to the specific div. for example of scroll on div#six number six(6) in the menu should also have class active.
[see my code and demo here][1]
[1]: https://codepen.io/GoPerov/pen/aZmVgE

Try this code, Here's your updated pen
$(document).ready(function(){
$(".page-scroll").click(function(){
$(".page-scroll").removeClass("active"); //removes current active class
$(this).addClass("active"); // adds active class to specific click
})
});

Update your code as below.
You need to manually check for which div is currently active with scroll position.
Updated codepen demo
$(document).ready(function() {
$(".page-scroll").click(function() {
$(".page-scroll").removeClass("active"); //removes current active class
$(this).addClass("active"); // adds active class to specific click
});
});
$(window).scroll(function() {
var selectedDiv = $(".page-scroll:first");
var topOffset = 1;
var windowTop = $(window).scrollTop();
$(".page-scroll").each(function() {
var id = $(this).attr("href");
var offset = ($(id).offset() || {
top: 0
}).top - windowTop;
if (offset < 1 && (topOffset == 1 || offset > topOffset)) {
topOffset = offset;
selectedDiv = $(this);
}
});
if (!selectedDiv.hasClass("active")) {
$(".page-scroll").removeClass("active");
selectedDiv.addClass("active");
}
});

Related

Toggle style same as class in pure javascript

I've got some code where when a button is clicked it toggles an active class. At the same time I need to set a top-margin on the toggled element, which also needs to be removed once the button is clicked again and the toggled class is removed. I can't set the top-margin as part of the active class as I need to get the value of the margin dynamically by checking the height of another element.
This is the code I've got to toggle the class and add the margin
var sizeBtn = document.querySelector(".size-toggle-btn");
var sizeItems = document.querySelector(".select-items");
var elementHeight = document.querySelector(".Detail-Container__inline").offsetHeight ;
sizeBtn.addEventListener("click", function(e) {
sizeItems.classList.toggle('size-toggle--active')
sizeItems.style.marginTop = "-" + elementHeight + "px";
});
However, obviously this doesn't remove the style when the button is clicked again so basically I need to toggle the style just like the active class. Is there anyway to do this?
You need to check if className is there or not so the code could be:
var sizeBtn = document.querySelector(".size-toggle-btn");
var sizeItems = document.querySelector(".select-items");
var elementHeight = document.querySelector(".Detail-Container__inline").offsetHeight ;
sizeBtn.addEventListener("click", function(e) {
if(sizeItems.classList.contains('size-toggle--active')) {
sizeItems.classList.remove('size-toggle--active')
sizeItems.style.marginTop = null;
}
else{
sizeItems.classList.add('size-toggle--active')
sizeItems.style.marginTop = "-" + elementHeight + "px";
}
});

JavaScript Jquery function that is triggered on event executes all at once instead of right time

I made a function that Is made to be trigered when user scrolls on a element on the page. In this case when user scrolls to an id then it fades in. The problem is that they fade in all at the same time with the first scroll instead of when they reaching the element That is supposed to allow it to fade in! Please help me make my function work.
Thanks a lot
var selected={
//// Storing selectors
items:[],
/// Function that stores items and hides them from the page
selectFunc: function(select) {
//// Store selected element
selected.items.push(select);
/// hide selector from the page
$(select).hide();
}
};
//// Function triggeres on scroll
$(window).scroll(function() {
/// loops trough the selected elements
for(i=0; i<selected.items.length; i++){
var currentItem = selected.items[i];
///// calculates your position and item position
var hT = $(currentItem).offset().top,
hH = $(currentItem).outerHeight(),
wH = $(window).height(),
wS = $(this).scrollTop();
////// check if you are in the position
if (wS > (hT+hH-wH)){
$( currentItem ).fadeIn( 2500 );
}
}
});
//// Using my function to select id about and p element in it.
selected.selectFunc("#about p");
selected.selectFunc("#about input");
In your for loop, you are doing an iteration for each element in selected.items. What's in there? Two strings: "#about p", and "#about input".
So for each of these selectors, you show them all. You need to get every element separately.
Another problem is that hiding these elements means they are not taking up the space they should on the page, so you might not be able to scroll down. You can solve that by changing their opacity instead of making them display:none (what .hide() is doing).
Here is your code with some modifications:
var selected = {
//// Storing selectors
items: [],
/// Function that stores items and hides them from the page
selectFunc: function(select) {
//// Store selected element
var items = $(select);
for (var i = 0, l = items.length; i < l; i++) selected.items.push(items[i]);
/// hide selector from the page
items.css('opacity', 0);
}
};
//// Function triggeres on scroll
$(window).scroll(function() {
/// loops trough the selected elements
for (i = 0; i < selected.items.length; i++) {
var currentItem = selected.items[i];
///// calculates your position and item position
var hT = $(currentItem).offset().top,
hH = $(currentItem).outerHeight(),
wH = $(window).height(),
wS = $(this).scrollTop();
////// check if you are in the position
if (wS > (hT + hH - wH)) {
$(currentItem).animate({
'opacity': 1
}, 2500);
}
}
});
//// Using my function to select id about and p element in it.
selected.selectFunc("#about p");
selected.selectFunc("#about input");
// Simulating a scroll to show the first elements
$(window).scroll();
JS Fiddle Demo

How to highlighting active menu item on scroll and click?

I want to add a class active to the current menu item on scroll and click. It’s a single (long) page with different sections. When click on an item, the active state should switch to the current one.
I came up with the following code, but doesn’t now how I can integrate the above:
// Click event
$('#primary-navwrapper li a[href^="#"]').click(function(event) {
// Prevent from default action to intitiate
event.preventDefault();
// The id of the section we want to go to
var anchorId = $(this).attr('href');
// Our scroll target : the top position of the section that has the id referenced by our href
var target = $(anchorId).offset().top - offset;
console.log(target);
$('html, body').stop().animate({ scrollTop: target }, 500, function () {
window.location.hash = anchorId;
});
return false;
});
To add active class on click is simple using jQuery. You just need this code in the click handler
//remove active from all anchor and add it to the clicked anchor
$('#primary-navwrapper li a[href^="#"]').removeClass("active")
$(this).addClass('active');
And for the scroll part you need to monitor the position of the scroll bar and compare it with every page offset like so
//check the pages when scroll event occurs
$(window).scroll(function(){
// Get the current vertical position of the scroll bar
position = $(this).scrollTop();
$('#primary-navwrapper li a[href^="#"]').each(function(){
var anchorId = $(this).attr('href');
var target = $(anchorId).offset().top - offset;
// check if the document has crossed the page
console.log(position,target);
if(position>=target){
//remove active from all anchor and add it to the clicked anchor
$('#primary-navwrapper li a[href^="#"]').removeClass("active")
$(this).addClass('active');
}
})
Here is a demo http://jsfiddle.net/k5afwfva/
<nav>
item
item
item
item
</nav>
var el = $(".item"),
yPos = 0;
el.click(function(event){
event.preventDefault();
$(this).addClass("active").siblings().removeClass("active");
});
$(window).scroll(function(){
yPos = $(this).scrollTop();
//i'm almost sure that you will need to calculate offset of your section to know when to switch classes
if(yPos > 100){
el.removeClass("active").eq(1).addClass("active");
}
if(yPos > 200){
el.removeClass("active").eq(2).addClass("active");
}
//etc....
});

on click addClass selected overrule addClass on scroll

I'm finding myself in a problem which I think has a easy solution but I cannot see... I have two functions to add a class called selected which highlights the buttons.
One function removes the class selected if present and adds the class to the button clicked:
var sidebarLinks = $('.js-sidebar a');
// About section: Remove and add class on click
sidebarLinks.on('click', function() {
sidebarLinks.removeClass('selected');
$(this).addClass('selected');
});
The other function adds the class selected if the user decides to scroll instead of clicking on the buttons. These buttons would highlight in a determined offset of the page:
var buttonOne = $('.buttonOne');
var buttonTwo = $('.buttonTwo');
var buttonThree = $('.buttonThree');
// Select nav buttons if scrolling and not clicking the button
$(window).scroll(function () {
// About nav sidebar links
var buttonOne = $('.js-polspotten-sidebar');
var buttonTwo = $('.js-product-sidebar');
var buttonThree = $('.js-designers-sidebar');
// About sections top scroll position
var currentTopPosition = $(this).scrollTop();
var productsTopPosition = $('#products').offset().top;
var designersTopPosition = $('#designers').offset().top;
// polspotten selected depending on scroll position
if (currentTopPosition >= currentTopPosition && currentTopPosition < productsTopPosition) {
buttonOne.addClass('selected');
}
else{
buttonOne.removeClass('selected');
}
// products selected depending on scroll position
if (currentTopPosition >= productsTopPosition &&
currentTopPosition < designersTopPosition) {
buttonTwo.addClass('selected');
}
else{
buttonTwo.removeClass('selected');
}
// designers selected depending on scroll position
if (currentTopPosition >= designersTopPosition) {
buttonThree.addClass('selected');
}
else{
buttonThree.removeClass('selected');
}
});
The problem is that both interact at the same time as the click event creates scroll.
What I want is that if somebody clicks on the button the scroll function will not work. It will only work if the user scrolls himself.
Is this possible?

find anchor and set active with jquery

i have 3 content boxes and all have a menu with anchor-links to the content-boxes below!
(the links are included and dynamic)
yesterday i received help with the script.. and its working very good when i have a large content-box.
see here: http://jsfiddle.net/wv9EQ/7/
now i got an problem when i have an small content-box
see here: http://jsfiddle.net/wv9EQ/8/
when i am for example between box 2 and 3 both anchors getting active.
any ideas to fix that? i just want an active anchor only for the box i am currently inside
i use this script:
$(function(){
var sections = {},
_height = $(window).height(),
i = 0;
//// Grab positions of our sections
$('.section').each(function(){
sections[this.name] = $(this).offset().top;
});
$(document).scroll(function(){
var $this = $(this),
pos = $this.scrollTop();
for(i in sections){
if(sections[i] > pos && sections[i] < pos + _height){
$('a').removeClass('active');
$('.nav_' + i).addClass('active');
}
}
});
$('.head-nav-button').click(function()
{
$('a').removeClass('active');
$('.nav_' + $(this).attr('href').replace('#', '')).addClass('active');
});
});
Leave the function after setting a section to active: http://fiddle.jshell.net/doktormolle/nCasy/
Using a offset and break after the first activated menu seems to work:
Trivial parts:
offset = 50; // Should be at least the height of your nav bar
if(sections[i] - pos + offset > 0){
$('a').removeClass('active');
$('.nav_' + i).addClass('active');
break;
}
Full code in fiddle here: http://jsfiddle.net/wv9EQ/10/

Categories