Change active link color - javascript

Problem
I have an issue with my website, I want to change the color of the selected link to blue, and if other is selected put it back to gray, but don`t know how to target the clicked link in javascript. Here is my code.
var center = document.getElementsByClassName("center");
for (let i = 0; i < center.length; i++) {
center[i].addEventListener("click", DivSelector());
}
function DivSelector() {
for (let i = 0; i < center.length; i++) {
center[i].classList.Remove('active');
};
}
.nav-item {
text-decoration: none;
color: #505b67;
margin-left: 10px;
}
.active {
color: #4460f1;
}
<ul class="nav-tab-ul">
<li id="Profile">
<a class="center nav-item" href="">Profile</a>
</li>
<li id="Change-Password">
<a class="center nav-item" href="">Change password</a>
</li>
<li id="Notifications">
<a class="center nav-item" href="">Notifications</a>
</li>
<li id="My-Cards">
<a class="center nav-item" href="">My Cards</a>
</li>
</ul>
Don`t know how to select the clicked link here for adding the 'active' class.

Try this. its working
var center = document.getElementsByClassName("center");
for (let i = 0; i < center.length; i++) {
center[i].addEventListener("click", function(e){
for (let i = 0; i < center.length; i++) {
center[i].classList.remove('active');
e.target.classList.add('active');
}
})
}

All you need to do is add the class active to the actual link of the page you are on. So when you on the profile page you add active to profile link and none of the others
PROFILE PAGE
<ul class="nav-tab-ul">
<li id="Profile">
<a class="center nav-item active" href="">Profile</a>
</li>
<li id="Change-Password">
<a class="center nav-item" href="">Change password</a>
</li>
<li id="Notifications">
<a class="center nav-item" href="">Notifications</a>
</li>
<li id="My-Cards">
<a class="center nav-item" href="">My Cards</a>
</li>
</ul>
CHANGE PASSWORD PAGE
When you on the change password page you add the active class to that link and none of the others.
<ul class="nav-tab-ul">
<li id="Profile">
<a class="center nav-item" href="">Profile</a>
</li>
<li id="Change-Password">
<a class="center nav-item active" href="">Change password</a>
</li>
<li id="Notifications">
<a class="center nav-item" href="">Notifications</a>
</li>
<li id="My-Cards">
<a class="center nav-item" href="">My Cards</a>
</li>
</ul>
If these are separate pages there is no need for JS?
If you are using one header file and including the file into all your pages then it will be a different solution. Let us know why you want to use JS

You can get the element clicked in event.currentTarget.
const nodes = document.getElementsByClassName("center");
for (let i = 0; i < nodes.length; i++) {
nodes[i].addEventListener("click", divSelector);
}
function divSelector(event) {
removeAllActives();
event.currentTarget.className += ' active';
}
function removeAllActives() {
const actives = document.getElementsByClassName("active");
for (let i = 0; i < actives.length; i++) {
actives[i].classList.remove('active');
}
}
.active {
color: blue;
}
<a class="center"> Link 1 </a> <br/>
<a class="center"> Link 2 </a>

A few things:
When adding your event listener, you called DivSelector, meaning you added the return value of DivSelector() as a listener, which is void. Instead just pass the name of the function you want to add as a listener.
You need to add the 'active' class to the clicked element after removing it from all the others. You can get the clicked element by using the event argument passed to your event listener. The element will be event.target.
DivSelector should be defined before it's used, so it should be moved above the rest of the code.
Here's an example:
function DivSelector(event) {
for (let i = 0; i < center.length; i++) {
center[i].classList.remove('active');
}
event.target.classList.add('active');
}
let center = document.querySelectorAll("center");
for (let i = 0; i < center.length; i++) {
center[i].addEventListener("click", DivSelector);
}
.nav-item {
text-decoration: none;
color: #505b67;
margin-left: 10px;
}
.active {
color: #4460f1;
}
<ul class="nav-tab-ul">
<li id="Profile">
<a class="center nav-item" href="#">Profile</a>
</li>
<li id="Change-Password">
<a class="center nav-item" href="#">Change password</a>
</li>
<li id="Notifications">
<a class="center nav-item" href="#">Notifications</a>
</li>
<li id="My-Cards">
<a class="center nav-item" href="#">My Cards</a>
</li>
</ul>

Related

active anchor link not being highlighted

I have been staring at this code for far too long, unfortunately I do not see the problem.
I am trying to get the active menu entry highlighted when the relevant div gets scrolled into view. But nothing is happening and no errors are being thrown in the console.
My menu html:
<section class="LeftAnchorNav" style="display: block;">
<nav id="LeftAnchorNav">
<div class="container" style="padding-left: 50px;">
<div class="col-md-4 LeftAnchorNavWrapper">
<ul class="LeftAnchorNavMenu">
<li class="leftanchorlink">
<a class="leftlink" href="#20a51af3-f8b0-4ef9-ba73-cf3cd0a321b9">About us</a>
</li>
<li class="leftanchorlink">
<a class="leftlink" href="#d736bc13-a2a7-48d4-8ecc-75b9a17f801b">Demo Center</a>
</li>
<li class="leftanchorlink">
<a class="leftlink" href="#545a6339-87e4-41ed-ad51-70c3788cedee">Testimonial</a>
</li>
<li class="leftanchorlink">
<a class="leftlink" href="#9355324a-6219-4300-ae97-aa77bf67dab4">Newsletter</a>
</li>
<li class="leftanchorlink">
<a class="leftlink" href="#0c70b0db-3e70-4faa-ab98-154b4eae498e">Blog</a>
</li>
<li class="leftanchorlink">
<a class="leftlink" href="#4903bc53-b862-42f0-a600-e21061204e42">Contact</a>
</li>
<li class="leftanchorlink">
<a class="leftlink" href="#002f6fd7-758b-4b27-8c75-0ce087ee826a">Solution Finder</a>
</li>
</ul>
</div>
</div>
</nav>
</section>
An example div:
<div class="block anchorblock col-lg-12 col-md-12 col-sm-12 col-xs-12 span12 "><div id="20a51af3-f8b0-4ef9-ba73-cf3cd0a321b9"></div>
</div>
My jquery/js:
if ($('.LeftAnchorNav').length > 0) {
// prepare the variables
var lastID;
var anchorMenu = $(".LeftAnchorNavMenu");
var anchorMenuHeight = anchorMenu.outerHeight() + 100;
var anchorMenuItems = anchorMenu.find(".leftlink");
var anchorMenuItemsTarget = anchorMenuItems.map(function () {
var item = $($(this).attr("href"));
if (item.length) { return item; }
});
// bind everything to the scrolling
$(window).scroll(function () {
// get anchornav container scroll position and add buffer
var fromTop = $(this).scrollTop() + anchorMenuHeight + 300;
// get ID of the current scroll item
var currentItem = anchorMenuItemsTarget.map(function () {
if ($(this).offset().top < fromTop)
return this;
});
// get the ID of the current element
currentItem = currentItem[currentItem.length - 1];
var id = currentItem && currentItem.length ? currentItem[0].id : "";
if (lastID !== id) {
lastID = id;
// Set/remove active class
anchorMenuItems.removeClass("highlightleftnavactive")
anchorMenuItems.filter("[href='#" + id + "']").addClass("highlightleftnavactive");
}
});
}
It's quite fiddly to do the arithmetic for scrolling so this snippet uses IntersectionObserver instead. This has the added benefit of less processing overhead as it just gets informed when the elements come in or go out of view, not every time the user scrolls a bit.
It sets up the observer to observe when any of the relevant elements come into or go out of the viewport. When alerted to that it adds or removes the highlighting class to the related navbar link.
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap#4.5.3/dist/css/bootstrap.min.css" integrity="sha384-TX8t27EcRE3e/ihU7zmQxVncDAy5uIKz4rEkgIXeMed4M0jlfIDPvg6uqKI2xXr2" crossorigin="anonymous">
<script src="https://cdn.jsdelivr.net/npm/bootstrap#4.5.3/dist/js/bootstrap.bundle.min.js" integrity="sha384-ho+j7jyWK8fNQe+A12Hb8AhRq26LrZ/JpcUGGOn+Y7RsweNrtN/tE3MoK7ZeZDyx" crossorigin="anonymous"></script>
<style>
.LeftAnchorNav {
position: fixed;
z-index:1;
}
.tall {
width: 100vw;
height: 100vh;
background-image: linear-gradient(cyan, magenta, yellow, black);
}
.highlightleftnavactive {
background-color: yellow;
}
</style>
</head>
<section class="LeftAnchorNav" style="display: block;">
<nav id="LeftAnchorNav">
<div class="container" style="padding-left: 50px;">
<div class="col-md-4 LeftAnchorNavWrapper">
<ul class="LeftAnchorNavMenu">
<li class="leftanchorlink">
<a class="leftlink" href="#20a51af3-f8b0-4ef9-ba73-cf3cd0a321b9">About us</a>
</li>
<li class="leftanchorlink">
<a class="leftlink" href="#d736bc13-a2a7-48d4-8ecc-75b9a17f801b">Demo Center</a>
</li>
<li class="leftanchorlink">
<a class="leftlink" href="#545a6339-87e4-41ed-ad51-70c3788cedee">Testimonial</a>
</li>
<li class="leftanchorlink">
<a class="leftlink" href="#9355324a-6219-4300-ae97-aa77bf67dab4">Newsletter</a>
</li>
<li class="leftanchorlink">
<a class="leftlink" href="#0c70b0db-3e70-4faa-ab98-154b4eae498e">Blog</a>
</li>
<li class="leftanchorlink">
<a class="leftlink" href="#4903bc53-b862-42f0-a600-e21061204e42">Contact</a>
</li>
<li class="leftanchorlink">
<a class="leftlink" href="#002f6fd7-758b-4b27-8c75-0ce087ee826a">Solution Finder</a>
</li>
</ul>
</div>
</div>
</nav>
</section>
<div class="tall"></div>
<div class="block anchorblock col-lg-12 col-md-12 col-sm-12 col-xs-12 span12 "><div id="20a51af3-f8b0-4ef9-ba73-cf3cd0a321b9">
An example block coming into and going out of view it belongs to the About us link in the navbar</div>
</div>
<div class="tall"></div>
<script>
let callback = (entries) => {
entries.forEach(entry => {
let id = entry.target.firstChild.id;
let leftLink = document.querySelector("a.leftlink[href='#"+ id + "']");
if (entry.isIntersecting) { leftLink.classList.add('highlightleftnavactive');}
else { leftLink.classList.remove('highlightleftnavactive');}
});
};
const observer = new IntersectionObserver(callback);
const anchorBlocks = document.querySelectorAll('.anchorblock');
anchorBlocks.forEach( (anchorBlock) => {
observer.observe(anchorBlock);
});
</script>

Change color of LI by its ID (materialize,Javascript)

I have many list-items(li's) and every single one has its own ID. Is there a way to change the color of a specific Li by its ID for example by a button or something(pls in Javascript). Thanks for any help!
const li = `
<li id= "${doc_id}">
<div class="collapsible-header grey lighten-4 right-align"> ${name} ${distance}km von dir entfernt (${Ort},${PLZ}) </div>
<div class="collapsible-body white"><span>lol${name} lat</span>
</li>
`;
You could do something like this where you loop over and use setAttribute to apply a class.
const ul = document.getElementById("list");
const items = ul.getElementsByTagName("li");
console.log("+++", items);
for(let i=0; i<items.length; i++) {
items[i].setAttribute("class", "test");
}
.test {
color: #f00;
}
<ul id="list">
<li>
Test
</li>
<li>
Test
</li>
<li>
Test
</li>
<li>
Test
</li>
<li>
Test
</li>
<li>
Test
</li>
<li>
Test
</li>
<li>
Test
</li>
</ul>

How to change colour of an element nested in other elements using javascript

I have a list structured as such:
<ul class="list">
<li class="list-element ">
<a href="#"><a>
</li>
</ul>
<button onclick="changeColour()"></button>
<script src="js/index.js"></script>
The css for my links are:
ul li a {
color: red
{
How do I change the colour of my links?? I know you can do this:
function changeColour() {
var div = document.getElementsByTagName("ul");
div.style.changeColour = "rgb(0, 212, 177)";
}
but I don't know how to the links within list item within the list.
Try document.querySelectorAll:
let links = document.querySelectorAll("ul.list li.list-element a");
for (let link of links) {
link.style.color = "rgb(0, 212, 177)";
}
ul li a {
color: red
{
<ul class="list">
<li class="list-element">
LINK 1
</li>
<li class="list-element">
LINK 2
</li>
</ul>
You can change it with css. Your css is correct but you missed ; after red. And you can do it with javascript too or you can use both if you want to give it a color then change it at run time. For your javascript code you forgot to add the collection's index...
document.getElementsByTagName('a')[0].style.color='orange';
NB: I'm targeting the first anchor with [0]. To target all anchors loop through the collection.
Like this
function changeColour() {
var div = document.getElementsByTagName("a");
for(var i = 0; i < div.length; i++){
div[i].style.color = "rgb(111, 112, 112)";
}
}
changeColour();
ul li a {
color: red;
{
<ul class="list">
<li class="list-element ">
<a href="#">link 1<a>
</li>
<li class="list-element ">
<a href="#">link 2<a>
</li>
</ul>
HTML
<ul class="list">
<li class="list-element ">
<a href="#">link 1<a>
</li>
<li class="list-element ">
<a href="#">link 2<a>
</li>
</ul>
Script
$('.list').each(function(){
$(this).find('li a').css('color','rgb(111, 112, 112)');
});
Below is Jquery model in case you are looking for it
// Jquery model if you want to use
$(document).ready(function(){
$('#change').click(function(){
var color=["blue","red","yellow","black","pink","green"];
var prompts = prompt("please type your valid color");
// checking if entered colored is registered
for(x in color){
if(color[x] ==prompts){
//registered then set its value as color
$("a").css({"color":prompts});
return ;
}
}
// deal with unregistered color
var conf = confirm('not registered color entered , do you want to set the default color?');
if(conf ==true ){
$("a").css({"color":"black"});
}
});
});
ul li a {
color: red;
{
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul class="list">
<li class="list-element ">
link 1
</li>
<li class="list-element ">
link 2
</li>
</ul>
<p id='change'> please click here to change link color </p>

Load JavaScript if Breadrumb exists

So i made a javascript and would like to make it load only if a certain breadcrumb exists in a page, lets say this breadcrumb is called "support" and my breadcrumb code is:
<ol class="breadcrumb top ipsList_inline left" id="breadcrumb">
<li itemscope="" itemtype="http://data-vocabulary.org/Breadcrumb" class="first">
<a href="https://www.website.com" itemprop="url">
<span itemprop="title">website</span>
</a>
</li>
<li itemscope="" itemtype="http://data-vocabulary.org/Breadcrumb">
<span itemprop="title">website</span>
</li>
<li itemscope="" itemtype="http://data-vocabulary.org/Breadcrumb">
<span itemprop="title">Section</span>
</li>
<li itemscope="" itemtype="http://data-vocabulary.org/Breadcrumb">
<span itemprop="title">Support</span>
</li>
</ol>
You can do something like this:
window.onload = function () {
var breadcrumb = document.getElementById("breadcrumb");
var titles = breadcrumb.getElementsByTagName("span");
var support = 0;
for(var i = 0; i < titles.length; ++i){
support += titles[i].innerHTML == "Support";
}
if(support) initialize();
}
function initialize() {
/* Do your stuff. */
}

jQuery set class active with anchor

I have a menu like :
<ul>
<li>
<a class="scroll-to" href="#one">one</a>
</li>
<li>
<a class="scroll-to" href="#two">two</a>
</li>
<li>
<a class="scroll-to" href="#three">three</a>
</li>
</ul>
And on my page, multiple anchor like :
<a id="two" target="_blank"></a>
or
<a id="one" target="_blank"></a>
I'm looking for a way to set an active class to my menu when i scroll to an anchor (with click or mouse scroll).
For example if i scroll to my anchor id="two" i need to set active my li #two.
Any ideas ?
If I understand your problem, add your anchors some class, for example section and try this:
$('.section').hover(function() {
var anchor = $(this).attr('id');
$('a[href="#'+anchor+'"]').addClass('active');
}, function() {
$('a').removeClass('active');
});
http://codepen.io/tomekbuszewski/pen/MwMWoK
var links = document.querySelectorAll("a.scroll-to");
console.log(links[1]);
for (var i = links.length -1; i>=0; i--)
{
//click event
links[i].onclick= someHandlerFunction;
//hover event
links[i].onmouseover= someHandlerFunction;
}
var liActive = undefined;
function someHandlerFunction(event) {
if (liActive != undefined) liActive.setAttribute("class", "");
liActive = event.target.parentNode;
liActive.setAttribute("class", "active");
return false;
}
.menu{
background-color: #00ff00;
}
.menu li.active{
background-color: blue;
}
<ul class="menu">
<li>
<a class="scroll-to" href="#one">one</a>
</li>
<li>
<a class="scroll-to" href="#two">two</a>
</li>
<li>
<a class="scroll-to" href="#three">three</a>
</li>
</ul>
Voila (add and remove class in the same time), it's a but it's a bit redundant to add active class at click and hover.

Categories