Apply the class "active" to nav links when clicked? - javascript

My website is a parallax one page scrolling website, so all my nav links are directed to ids nested within that page...
For example:
<ul class="clearfix">
<li>Home</li>
<li>Work</li>
<li>About</li>
<li>Contact</li>
</ul>
So How would I tell my html that when someone clicks on one of these links and directs them to the corresponding ID on the page, to take on the class active? And the link that was active to turn back to the regular styling?

Assuming your link elements are contained in an element with class nav, and you're using jQuery, you could do the following:
$('.nav a').on('click', function(event) {
$('.nav a.active').removeClass('active');
$(this).addClass('active');
});
fiddle

You will have to use JavaScript to add that functionality into your application. Everytime a link is clicked, add the 'active' class to the triggering element, and remove it from all others. This is straightforward if you can use jQuery (jsFiddle with jQuery), and only a little more tedious otherwise.
$(function() {
$("ul.clearfix > li > a").click(function() {
$("a.active").removeClass("active");
$(this).addClass("active");
});
});
If you're only using native JS, you can try something along the lines of the below (jsFiddle using vanilla JS):
var links = document.getElementsByTagName("a"); // more specific selector if other links
for (var i = 0; i < links.length; i++) {
var link = links[i];
link.onclick = function () {
var prev = document.getElementsByClassName("active");
if (prev && prev[0]) {
prev[0].className = ""; // if using other classes, filter better
}
this.className += " active";
};
}
This second solution needs to be adapted to fit your particular application/DOM structure, since it's not quite as flexible as the first.

jQuery
$('ul a').on('click', function(event) {
$('a').removeClass("active");
$(this).addClass("active");
});
Replace ul a with something more specific like .nav a

Related

Add active class to parent nav when on child pages

I need to highlight the parent nav item when a user is within a child page based on the URL.
User is currently on the page foo1-child and the parent is foo1 so I need to add the active class to Foo 1: http://foo.com/foo1/foo1-child.html
NAV:
<ul class="main-nav">
<li>Foo 1</li>
<li>Foo 5</li>
</ul>
I have no issue adding an active class to links within the nav as I just compare every the href in the .nav li a vs the URL but how can I check the URL for a matching anchor link name in the URL or something similar?
Current JS
$('.main-nav li > a').each(function () {
var $this = $(this);
if ($this.attr('href').indexOf(location.pathname) !== -1) {
$this.addClass('active');
}
});
If you cut off the ".html" from the end of both of them and you search for the a's href (which should be shorter) in the location, it should work.
$('.main-nav li > a').each(function () {
var $this = $(this);
var loc = location.
if (location.pathname.replace(/\/[^\/]*\.html$/, '').startsWith($this.attr('href').replace(/\.html$/, ''))) {
$this.parent().addClass('active');
}
});
You can see it in "action" here: https://jsfiddle.net/c8u2f91v/ Note it uses a fake location_pathname instead of location.pathname, because jsfiddle doesn't have the necessary prefixes in the path, but it shows that it should work.

Create elements with jQuery each not working

I have a dynamic rotator that I am trying to create a nav button for each image. I dont have access to the back end so I have to do this with jQuery on load.
My thinking is that I find each LI item and create a new and append it in the nav but I cant seem to get it working
http://jsfiddle.net/bc0yu7pg/2/
jQuery
navItem = 0;
$( "li" ).each(function() {
navLink = '';
$('section').append(navLink);
navItem++;
});
HTML
<section>
<ul>
<li>Slide</li>
<li>Slide</li>
<li>Slide</li>
</ul>
<nav></nav>
</section>
Use $('section nav') instead of $('section'). Try this:
navItem = 0;
$( "li" ).each(function() {
navLink = '';
$('section nav').append(navLink);
navItem++;
});
DEMO
Hope this helps you :)
You have a missing quote mark. You never close the href quote. Also you should assign to the nav as #Unknown said.
navItem = 0;
$( "li" ).each(function() {
navLink = '';
$('section nav').append(navLink);
navItem++;
});
Working fiddle
You're adding your link to the <section> element rather than to the <nav> element.
$( "li" ).each(function() {
navLink = '';
$('nav').append(navLink);
navItem++;
});
See this updated jsfiddle jsfiddle.net/bc0yu7pg/5/
However I think your CSS may need some extra work.
You can not use section as a normal container in DOM for this kind of manipulation.
https://stackoverflow.com/a/7183188/1027550

Change link style and properties using jquery

Currently looking to take an OOP style approach with javascript, as I am a beginner level programmer looking to take my javascript skills up a notch. The code I have seems not to be working at all, and I have tried differed solutions for a few hours now.
My Goal
I would like to accomplish the action of creating click functionality on a page. Where a user clicks on a link and it adds the CSS class .active to the link (and of course not adding the class to other links when clicked on).And finally would like when a suer clicks on the same link(active link with the class) again for the class to remove itself and return to its normal state.
Thank you for the help!
Javascript
var activeState = $(".category-tree-with-article .article-list > li > a, .content-left-bottom li a, .content-right-bottom li a");
function clickState () {
this.initEvent();
clickState.prototype = {
initEvent: function() {
activeState.on('click', function (event) {
event.preventDefault();
var el = $(this);
// For class changes
activeState.toggleClass('active');
el.addClass('active');
});
}
}//prototype inherit
} //end function
clickState();
CSS
a.active {
color:red;
font-family:"Prime";
}
I'd say you should probably stop using your "OOP" style coding
var activeState = $(".category-tree-with-article .article-list > li > a, .content-left-bottom li a, .content-right-bottom li a");
activeState.on('click', function (event) {
event.preventDefault();
activeState.not(this).removeClass('active');
$(this).toggleClass('active');
});

Using location.hash to activate jquery toggle/slideToggle

I have a list of a list that uses jquery toggle and slideToggle so that when items are clicked on, explanatory text slides out and the class changes on the h3. The html for the items looks like:
<li><h3>What do I know about javascript?</h3>
<div class="check_list_wrap feature1">Not a lot, apparently.</div>
</li>
I included the jquery files and then write this in the header:
<script type="text/javascript">
$(function() {
$("#listfeatures h3 a").toggle(function(){
$(this).addClass("check_list_selected");
}, function () {
$(this).removeClass("check_list_selected");
});
$("#listfeatures h3 a").click(function() {
$("."+this.id).slideToggle('fast');
return false;
});
});
</script>
This makes it so that if a link is clicked on, it will toggle the class change of the h3, the display:block/display:inline and the sliding out of the div. It works fine.
BUT, now I want it so that with a url like index.php#feature1, the toggling for that list item will be activated as if it'd been clicked on. I know I need to use location.hash but I'm not sure how to do that. Where should I start?
location.hash contains everything in the URL including and after the hash (#) mark. So, if went to index.php#feature1 and wanted the div with id "feature1" to show on load, you could do
$(document).ready(function() {
if(location.hash) {
var id = location.hash.slice(1); //Get rid of the # mark
var elementToShow = $("#" + id); //Save local reference
if(elementToShow.length) { //Check if the element exists
elementToShow.slideToggle('fast'); //Show the element
elementToShow.addClass("check_list_selected"); //Add class to element (the link)
}
}
});

How to find the 2nd closest ancestor in jQuery?

My DOM looks something like this:
<li>
<li><a class="editEntity>Edit</a></li>
<li><a class="deleteEntity>Delete</a></li>
</li>
When the used clicks on 'Edit', I want to change the outer <li> to <li class="selected>.
I tried something like this, but this is not working:
$('li a.editEntity').live('click', function() {
$(this).closest('li').closest('li').addClass('selected');
});
Any help is appreciated.
Go up a parent:
$(this).closest('li').parent().closest('li').addClass('selected');
It wasn't working because closest starts with the current element, and so if you call it on something that matches the selector, you get back the same thing you started with.
Live example
Or you can use parents with the :eq selector:
$(this).parents("li:eq(1)").toggleClass("selected");
Note that :eq uses 0-based indexes, so :eq(1) is the second parent li.
Live example
Your quoted HTML is invalid, though (an li can't directly contain an li); I assume you meant:
<li>
<ul>
<li><a class="editEntity>Edit</a></li>
<li><a class="deleteEntity>Delete</a></li>
</ul>
</li>
...or similar.
you can use
$('li a.editEntity').live('click', function() {
$(this).parents('li').addClass('selected');
});
following my previous comment.. here's the example promised... :)
$('li').each(function(index) {
alert(index + ': ' + $(this).text());
});
Stop at the second index
Further info can be found here
http://api.jquery.com/each/
I'm using this code to add active class depending on the page. This is working 100% for multi level sub-menus of AdminLTE 3, just put this code in the footer section of your page.
var url = window.location;
const allLinks = document.querySelectorAll('.nav-item a');
const currentLink = [...allLinks].filter(e => {
return e.href == url;
});
currentLink[0].classList.add("active");
currentLink[0].closest(".nav-treeview").style.display = "block ";
currentLink[0].closest("ul.nav-treeview").closest('li').classList.add('menu-open');
$('.menu-open').find('a').each(function() {
if (!$(this).parents().hasClass('active')) {
$(this).parents().addClass("active");
$(this).addClass("active");
}
});

Categories