I'm trying to change the colour of an child (In a menu) after been clicked by the user, and I'm having trouble to execute that.
I'm using class .active
to change the menu style while scrolling down.
I was thinking about adding .active::after
so each child of <li>
tag that has been clicked will be changing his font color.
.active
works fine, though .active::after
doesn't work at all. Also the code includes scrolling slowly on click of child.
jQuery:
/**
* This part handles the highlighting functionality.
* We use the scroll functionality again, some array creation and
* manipulation, class adding and class removing, and conditional testing
*/
var aChildren = $("nav ul li").children(); // find the a children of the list items
var aArray = []; // create the empty aArray
for (var i=0; i < aChildren.length; i++) {
var aChild = aChildren[i];
var ahref = $(aChild).attr('href');
aArray.push(ahref);
} // this for loop fills the aArray with attribute href values
$(window).scroll(function(event){
var windowPos = $(window).scrollTop(); // get the offset of the window from the top of page
var windowHeight = $(window).height(); // get the height of the window
var docHeight = $(document).height();
var yOffset = window.pageYOffset;
var breakpoint = 50;
for (var i=0; i < aArray.length; i++) {
var theID = aArray[i];
var divPos = $(theID).offset().top; // get the offset of the div from the top of page
var divHeight = $(theID).height(); // get the height of the div in question
if (windowPos >= divPos && windowPos < (divPos + divHeight)) {
if (yOffset > breakpoint){
$("nav ul").addClass('active');
$("nav ul li a").addClass('active');
}else{
$("nav ul").removeClass('active');
$("nav ul li a").removeClass('active');
}
$("a[href='" + theID + "']").addClass("active::after");
} else {
if (yOffset > breakpoint){
$("nav ul").addClass('active');
$("nav ul li a").addClass('active');
}else{
$("nav ul").removeClass('active');
$("nav ul li a").removeClass('active');
}
$("a[href='" + theID + "']").removeClass("active::after");
}
}
if(windowPos + windowHeight == docHeight) {
if (!$("nav li:last-child a").hasClass("nav-active")) {
var navActiveCurrent = $(".nav-active").attr("href");
$("a[href='" + navActiveCurrent + "']").removeClass("active::after");
$("nav li:last-child a").addClass("active::after");
}
}
});
});
CSS:
nav ul.active{
margin: -7px 0 0;
background:rgba(0, 0, 0, 0.7);
}
nav ul li a.active{
color: white;
}
nav ul li a.active::after{
color: #ccc;
}
How can I change specific menu child color on click properly?