Add class to <li> when clicking on a link - javascript

That's the html of my menu:
<ul class="nav">
<li>A</li>
<li><a href="#b" >B</a></li>
<li><a href="#c" >C</a></li>
<li><a href="#d" >D</a></li>
</ul>
I want that, after I clicked on a link in the menu, the active class will be added to the clicked <li>.
Thanks in advance

Use jquery
$("li a").click(function() {
$('li a').not(this).removeClass('active');
$(this).toggleClass('active');
});
DEMO Updated

He is not asking for a jQuery solution. But that jQuery would be the ideal choice, here is how to do it with javascript, best practices, event delegation and modern. Perhaps someone learns something new from it as well.
http://jsfiddle.net/N9Hem/
window.onload = function(){
(function(){
var els = [];
var doc = document;
var get = function(id){return doc.getElementById(id);};
get('clickable').onclick = function(evt){
evt = evt || window.event;
var el = evt.target || evt.srcElement;
els = doc.querySelectorAll('#clickable a');
if(el.nodeName == "A"){
for(var i = els.length - 1; i >= 0; i -= 1){
els[i].className = '';
};
el.className = 'active';
};
};
})();
};

If you use jQuery then you could use code like this:
$(function () {
$(".nav a").click(function () {
$(".nav a").removeClass("active");
$(this).addClass("active");
});
});

Try this with jQuery
$('#nav li a').click(function(){
$('#nav li a').removeClass('active');
$(this).addClass('active');
});

Here is a prototype that doesn't use jquery as you didn't request it on your question.
It searches for the current element with the active class, remove it and add the class to the clicked one.
Javasript Function
function activeThis(element){
var current = document.getElementsByClassName("active")[0];
current.className = null;
element.className="active";
}
HTML code
<a href="#b" onclick="activeThis(this)">

I hope I got what you want... I add eventHandlers to <ul>. On click remove clicked from previous elem and set clicked-class (if current class is active??)
<ul class="nav">
<li>A</li>
<li>B</li>
<li>C</li>
<li>D</li>
</ul>
<script>
var clickedElem = null;
document.getElementsByClassName("nav")[0].addEventListener("click", function (e) {
if (clickedElem)
clickedElem.removeAttribute("class");
// check if e.srcElement.className is active?? that's what you want?
e.srcElement.className = "clicked";
clickedElem = e.srcElement;
});
</script>

This one should works for you
elems =document.getElementsByClassName("nav")[0].getElementsByTagName("a");
for (var i = 0; i < elems.length; i++) {
elems[i].addEventListener("click", function (e) {
for (var i = 0; i < elems.length; i++) {
elems[i].className="";
};
this.className = "active";
});
}

I guess this will work
var navlinks = document.getElementByClass('nav').getElementsByTagName('a');
for (var i = 0; i < navlinks.length; i++) {
if(navlinks[i].className == 'active'){
navlinks[i].parentNode.parentNode.parentNode.className = 'YOUR CLASS';
}
}

Check my fiddle
I hope this is what you want
http://jsfiddle.net/arunberti/ftZzs/
a:visited
{
color:green;
}
a:active {color:yellow;}
a:link {color:red;}

Try this:
$('.nav li').click(function(e) {
$(this).addClass('selected').siblings().removeClass('selected');
});
Alternatively, if you want to attach the click event to the a:
$('.nav a').click(function(e) {
e.preventDefault();
$('.nav a').removeClass('selected');
$(this).addClass('selected');
});
Example fiddle

thats quite easy
jQuery CODE:
$('.nav li a').on('click',function(){
$('.nav li').each(function() {
var anc=$(this).find('a');
if(anc.hasClass('active'))
{
$(anc).removeClass('active');
}
})
$(this).addClass('active');
})
Edited:
Code is refined
Happy Coding :)

Related

Active navigation class based on current URL problem

I have the following HTML menu:
<div class="nav">
<ul>
<li class="first">Home</li>
<li>Something</li>
<li>Else</li>
<li class="last">Random</li>
</ul>
<ul style="float:right;">
<li class="first last">News</li>
</ul>
</div>
</div>
And then I have this code:
jQuery(function($){
var current = location.pathname;
$('.nav ul li a').each(function(){
var $this = $(this);
// if the current path is like this link, make it active
if($this.attr('href').indexOf(current) !== -1){
$this.addClass('active');
}
})
})
The code is working great, but it has a problem. For example, if I see the Home page (www.example.com) then all of the menu links receives the active class. Another problem would be that it works great for www.example.com/something but it doesn't keep it active if I go to www.example.com/something/1 etc. Any idea how to fix this? Thanks in advance!
For home page add extra class 'default' in list like.
<li class="first default">Home</li>
jquery code.
jQuery(function($){
var current = location.pathname;
console.log(current);
//remove the active class from list item.
$('.nav ul li a').removeClass('active');
if(current != '/'){
$('.nav ul li a').each(function(){
var $this = $(this);
// if the current path is like this link, make it active
if(current.indexOf($this.attr('href')) !== -1 && $this.attr('href') != '/'){
$this.addClass('active');
}
})
}else{
console.log('home');
$('.default a').addClass('active');
}
})
Use the below jQuery code to add active class:
$(function() {
var pgurl = window.location.href.substr(window.location.href
.lastIndexOf("/") + 1);
$(".nav ul li a").each(function() {
if ($(this).attr("href") == pgurl || $(this).attr("href") == '')
$(this).addClass("active");
})
});
By using indexOf(), you are checking if the link's target is the same the current location.
What you want is not "the same URL" but "the same pattern", so I would tend to use a regular expression :
let re = new RegExp("^" + $(this).attr("href") + ".*");
if (re.test($current)) {
$(this).addClass("active");
}
Note that this would force you to create a separate solution for your link to the main page, else it would always be active.

toggleClass on hyperlink not working

I'm working with the following code:
http://jsfiddle.net/k5pnj4a4/8/ however my 'toggleClass' isn't working. Try the example in jsFiddle. Basically if I click the link, it goes red as expected but click again & it doesn't return to the original state :-(
Javascript:
$(document).ready(function(){
$('.filters a').on('click', function() {
var data_filter = $(this).closest("a").data('filter');
$(this).addClass('active');
if($(this).hasClass('active')) {
localStorage.setItem(data_filter,true);
} else {
localStorage.setItem(data_filter,false);
}
});
$('.filters a').each(function(){
var data_filter = $(this).closest("a").data('filter');
var checked = localStorage.getItem(data_filter);
if(checked){
$(this).addClass('active');
} else {
$(this).removeClass('active');
}
});
});
HTML
<div class="filters">
<h3 data-target="#colours_filters">Colour</h3>
<ul id="colours_filters">
<li class="filter-option">Black</li>
<li class="filter-option">Blue</li>
</ul>
</div>
Can someone provide assistance with this?
Thank you
Try this:
$(document).ready(function(){
$('.filters a').on('click', function() {
if($(this).hasClass("active")) {
$(this).removeClass("active");
}
else {
$(this).addClass("active");
}
});
});

JQuery adding a class

I want add a class when a <li> element clicked. but it didn't work. Here's JQuery snippet
$(".mama").click(function(){
var arr = ["cat","dog", "mice", "bird"];
alink = $(this).text();
$.each(arr, function(index, value) {
if(alink == value){
$(this).addClass('hi');
}
});
});
And HTML
<ul id="animal">
<li class="mama">cat</li>
<li class="mama">dog</li>
<li class="mama">Mice</li>
</ul>
i also have tried to do it by .map but nothing happen. please give solution and some explain. Thanks
This should work:
$(".mama").click(function(){
var $this = $(this);
var arr = ["cat","dog", "mice", "bird"];
alink = $(this).text();
$.each(arr, function(index, value) {
if(alink == value){
$this.addClass('hi');
}
});
});
because this inside the each is not the DOM element <li>.
You probably just need to do this:
http://jsfiddle.net/reugB/1/
$('.mama').on('click', function(evt) {
evt.preventDefault();
$(this).addClass('hi');
});
Use this to refer to current element which was clicked.
$(".mama").click(function (e) {
e.preventDefault();
$(this).addClass('hi');
});
If you mean add the class hi to the clicked li, just do like below:
$(".mama").click(function(e){
e.preventDefault();
$(".mama").removeClass('hi');
$(this).addClass('hi')
});
.hi { background-color: #f00 !important;}
$('.mama').on('click', function(evt) {
evt.preventDefault();
$(this).addClass('hi');
});
$(".mama").click(function(e){
e.preventDefault();
var arr = ["cat","dog", "mice", "bird"];
var alink = $(this).find("a").text();
$.each(arr, function(index, value) {
if(alink == value){
$(this).addClass('hi');
}
});
});
see reference text and find

.addClass to element adds a styling then removes, how do I fix

I have a code
var prev;
function addClass( classname, element ) {
prev = cn;
var cn = document.getElementById(element);
$(cn).addClass("selected");
}
The element in the dom look like this:
<div class="arrowgreen">
<ul>
<li>Manager</li>
<li>Planner</li>
<li>Administrator</li>
</ul>
</div>
For 'arrowgreen' I have a styling which changes the li styling on rollover and click.
When an element is clicked on, I want to apply the 'selected' classname to the element.
It does this for a split second and then reverts back.
The css looks like
.arrowgreen li a.selected{
color: #26370A;
background-position: 100% -64px;
}
Working jsFiddle Demo
In usage of $ in your code, I see that you are using jQuery.
There is no need to set onclick internally.
Let's jQuery handle it for you:
// wait for dom ready
$(function () {
// when user clicks on elements
$('.arrowgreen li a').on('click', function (e) {
// prevent default the behaviour of link
e.preventDefault();
// remove old `selected` classes from elements
$('.arrowgreen li a').removeClass('selected');
// add class `selected` to current element
$(this).addClass('selected');
});
});
Working JSFiddle
There was an error in your HTML, a " that opened a new string after onclick.
var prev;
function addClass(classname, element) {
var cn = document.getElementById(element);
prev = cn; //does nothing useful really
$(cn).addClass("selected");
}
<div class="arrowgreen">
<ul>
<li>Manager
</li>
<li>Planner
</li>
<li>Administrator
</li>
</ul>
</div>
Remember to include jQuery in your page!
There is a way to do this without jQuery anyway:
function addClass(classname, element) {
var cn = document.getElementById(element);
prev = cn; //does nothing useful really
cn.className += " " + classname;
}
Similar way to do it:
(function ($) {
$('.arrowgreen > ul > li > a').on('click', function (e) {
e.preventDefault();
$(this).addClass('selected').siblings().removeClass('selected');
});
}(jQuery));

How to get the prev/next element in class

I want to to fadeOut the previous and the next class of a specific one, why my code isnt working? You know the solution?
Note: How to specify that the previous of #homebut is #aboutus, and that the next of#aboutus is #homebut?
Thanks a lot for any help!
This is my html-code:
<body>
<div class="menuEintraege" id="2">
<li class="current">home</li>
<li>apps</li>
<li>hedone</li>
<li>contact</li>
<li>about us</li>
</div>
</body>
and this my javascript till now:
$("a").click(function() {
$(this).prev("li").fadeOut("fast");
$(this).next("li").fadeOut("fast");
}
My first thoughts, would be:
$('li a:first').addClass('active');
$('button').click(function(e) {
e.preventDefault();
var that = this,
$that = $(that),
aEls = $('.menuEintraege a'),
aActive = $('.menuEintraege a.active')
.closest('li')
.index();
if (that.id == 'pre') {
$('.active').removeClass('active');
var pre = aEls.eq(aActive - 1);
var prev = pre.length ? pre : aEls.last();
prev.addClass('active');
}
else if (that.id == 'nxt') {
$('.active').removeClass('active');
var pre = aEls.eq(aActive + 1);
var prev = pre.length ? pre : aEls.first();
prev.addClass('active');
}
});​
JS Fiddle demo.
$("a").click(function() {
$(this).parent().prev("li").fadeOut("fast");
$(this).parent().next("li").fadeOut("fast");
}

Categories