Add active Menu or Navigation class based on URL - javascript

I've added an active class to my menu items. However my current implementation is adding the class to all list menu items as opposed to whatever the current page is.
Please let me know if there is an issue with my current code, and what I can do to achieve the desired outcome.
<ul id="menu_items">
<li class="has-sub">STORE</li>
<li>RESEARCH</li>
<li>INFO</li>
</ul>
$(function(){
var current = location.pathname;
$('#menu_items 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');
}
})
})
.active {text-decoration:underline;}

Okay, Try this way, hope it will work
<ul id="menu_items">
<li>Index</li>
<li class="has-sub">STORE</li>
<li>RESEARCH</li>
<li>INFO</li>
</ul>
</html>
<Script>
$("#menu_items li").bind("click", function(e){
$("li").click(function() {
$(this).siblings().find("a").removeClass("active");
$(this).find("a").addClass("active")
})
})
</Script>

Please Check the URLs , All the Links are "/collections"

Related

Keep active class on gallery navigation when using pagination

I have the following navigation on the gallery page of my website that allows users to filter the images by category.
<ul>
<li>All</li>
<li>Our Gym</li>
<li>Our Classes</li>
<li>Our Coaches</li>
</ul>
I've added the following snippet to add the class 'active' the category that is currently being viewed by the user.
<script>
jQuery(function($) {
var path = window.location.href;
$('.gallery_listing_wrapper li a').each(function() {
if (this.href === path) {
$(this).addClass('active');
}
});
});
</script>
This works for the above gallery navigation however once I navigate using the pagination it doesn't work.
The URL for the pagination is slightly different to the gallery and its categories.
For example - instead of /gallery/our-gym/ - page/ and the page number is added to the URL i.e. /gallery/page/2/
Is it possible to adjust the above snippet to keep the active class on All when the pagination is being used?
You could always just add the class to the "All" button if none of the other buttons match the current URL.
<script>
jQuery(function($) {
var path = window.location.href;
let match = $(`.gallery_listing_wrapper li a[href="${path}"]`);
if(match.length >= 1)
match.addClass("active");
else
$(".gallery_listing_wrapper li a[href='/gallery/']").addClass("active");
});
</script>

How to find the class of element in a each loop

I am trying to create a menu system where I can change the style of the active page item in the menu. I am using a separate body class on each page, then I want to cycle through the li in the menu and find a match to the body class. At that match I will add the new styling to that menu item.
Here is my code so far.
HTML
<body class="home-state">
...
<div class="menu-left">
<ul>
<li class="home-state">
Home
</li>
<li class="work-state">
Work
</li>
<li class="services-state">
Services
</li>
<li class="about-state">
About
</li>
<li class="blog-state">
Blog
</li>
<li class="shop-state">
Shop
</li>
<li class="contact-state">
<a data-toggle="modal" href="#modal-coworking">Contact</a>
</li>
<li class="project-state">
Project brief
</li>
</ul>
</div>
...
</body>
JS
var bodyClass = $("body").attr('class');
$('.menu-left ul li').each(function(){
First: I want to find the element's class here I have used $(this).attr("class"); which didn't work
var element = $(this);
Second: I want to use a if statement to check to see if the class matches the bodyClass
console.log(element);
Last: If there is a match I want to add the class .active to the element li.
});
Given that elements can have multiple classes, I'd suggesting changing your body element to use a data- attribute rather than a class to specify what the current page is:
<body data-current="home-state">
Then the JS needed to add the active class to the relevant menu item is simple:
$("li." + $("body").attr("data-current")).addClass("active")
You don't need to loop over the menu items comparing classes as mentioned in the question, because you can just directly select the required li element based on its class.
In the event that the body element doesn't have a data-current attribute then $("body").attr("data-current") would return undefined, which would mean the code above tries to select an element with $("li.undefined") and add a class to it. Probably you have no elements with such a class so that would be harmless, but if you wanted to explicitly test that the data-current attribute exists:
var current = $("body").attr("data-current")
if (current) {
$("li." + current).addClass("active")
}
You can do this in couple ways, here is the simple way to do this;
var bodyClass = $("body").attr('class');
$("li." + bodyClass).addClass("active")
You can also use a loop for this one;
var bodyClass = $("body").attr('class');
$(".menu-left li").each(function(i, classes) {
if (bodyClass === $(this).attr("class")) {
$(this).addClass("active")
}
})
both will do the job.
enter image description here
enter image description here
as the comment said,the element can have more than one class ,so you should check it one by one
You missed to bind the click event for the menu item. Follow like below
var bodyClass = $("body").attr('class');
$('.menu-left ul li').on( "click", function() {
var myClass = $(this).attr("class");
alert(myClass);
});
Tested: https://codepen.io/anon/pen/XzYjGY

Cant get the value of <li data-*> element. Tried Javascript as well as Jquery

The following is my dropdown list.
<ul id="navBar" data-value="">
<li data-city-value="blore">Bangalore
<ul>
<li data-city-value="delhi">Delhi</li>
<li data-city-value="che">Chennai</li>
<li data-city-value="jaipur">Jaipur</li>
<li data-city-value="hyd">Hyderabad</li>
<li data-city-value="mum">Mumbai</li>
<li data-city-value="pune">Pune</li>
</ul>
</li>
</ul>
And the following are my methods I tried to access the data-city-value attribute.
Method 1)
var cityName = document.getElementById('navBar');
var city = cityName.getAttribute('data-city-value');
alert(city);
It alerts "null"
Method 2)
var cityName = document.getElementById('navBar');
var city = cityName.dataset.cityValue;
alert(city);
It alerts "undefined".
Method 3)
$('#navBar li').click(function() {
$(this).parent().data('value', $(this).data('cityValue'));
});
alert($('#city').data('value'));
It alerts "undefined".
I checked the syntax to get data value here
It would be of great help if you can help me find where I am doing mistake.
Thanks. :)
IN your first two methods you target the top ul with id navBar. In the third method you do $(this).parent() which again takes you to the ul element.
That element does not have the data-city-value attribute.
The jquery method should be
$('#navBar').on('click','li', function(e) {
var city = $(this).data('city-value');
alert(city);
return false;
});
Demo at http://jsfiddle.net/gaby/Mb7KS/
As pointed out by Gaby, you need to reach the element firts. Try this:
$('#navBar:first-child')
This is how you can iterate through your data-city-value attributes:
$('li[data-city-value]').each(function(index,element){
alert($(element).data('city-value'));
});
You can also check my jsFiddle example.
For click events:
$(document).ready(function()
{
$('li').click(function() {
alert($(this).data('city-value'));
return false;
});
});
You should return false because the top li element has inner elements and it was triggering inner li element click event.
My second jsFiddle demo.

nth-child increase decrease with click

I have a set of li elements forming a menu. When the user clicks a particular li element I want to change the source of an iframe element to the URL that corresponds to the clicked item.
I've tried the function below but it didn't work. Can somebody please advise how to do this?
http://jsfiddle.net/ZnMTK/8/
$(document).ready(function(){
var source1="http://www.hurriyet.com.tr";
var source2="http://www.milliyet.com.tr";
var source3="http://www.vatan.com.tr";
var source4="http://www.ensonhaber.com";
$("#menubar ul li:nth-child(i)").click(function(){
$(this).attr('src', source(i) );
});
});
You can use an array and then use the clicked li elements index to fetch the target source from array.
$(document).ready(function(){
var sources =["http://www.hurriyet.com.tr","http://www.milliyet.com.tr","http://www.vatan.com.tr","http://www.ensonhaber.com"],
$("#menubar li").click(function(){
$('#iframe1').attr('src', sources[$(this).index()])
});
});
Demo: Fiddle
This type of functionality is what arrays are for:
$(document).ready(function(){
var sources =["http://www.hurriyet.com.tr","http://www.milliyet.com.tr","http://www.vatan.com.tr","http://www.ensonhaber.com"],
i = 0;
$("#menubar li").click(function(){
$("#iframe1").attr('src', sources[$(this).index()] );
});
});
However, specifying all of your URLs in your JavaScript and relying on the indices matching up with the order of the menu li elements is kind of fragile. I would recommend linking the values more closely, perhaps something like this:
<ul id="menubar">
<li data-src="http://www.hurriyet.com.tr">Hurriyet</li>
<li data-src="http://www.milliyet.com.tr">Milliyet</li>
<li data-src="http://www.vatan.com.tr">Vatan</li>
<li data-src="http://www.ensonhaber.com">Ensonhaber</li>
</ul>
And then with JS:
$(document).ready(function () {
$("#menubar li").click(function () {
$("#iframe1").attr('src', $(this).attr("data-src"));
});
});

Sort <li> with jQuery

Currently I have a language select which is a simple <ul> with <li>s and <a>s inside.
Every <li> has a class - lang-inactive or lang-active. It depends on what language the user is using right now.
The <li>s with .lang-inactive are hidden by default. When you .hover() the ul the other options are showed.
Here is a simple example.
But as you can see the first <li> is French, and when I'm using English and I hover the language bar the French appears over the english.
Is there a way I can sort the <li> depending on whether they are lang-active or lang-inactive. The inactive ones should appear below the active one.
My current code is:
var ul = $('#languages-iv');
ul.css('position', 'absolute');
ul.css('top', 5);
li = ul.children('li');
li.detach().sort(function(a,b) {
//how do I sort
});
ul.append(li);
$("#languages-iv").hover(function(){
$('.lang-inactive').slideToggle();
}, function() {
$('.lang-inactive').stop().slideToggle();
});
This executed on page-load (or whenever your language selector gets created) should push the active language up to first child.
$('.lang-active').prependTo('#languages-iv');
Demo:
http://jsfiddle.net/gqfPV/
<ul>
<li>English</li>
<li>French</li>
<li>German</li>
</ul>
<script>
$(document).ready(function(){
$('ul li').live('click',function(){
$('li a').removeClass('lang-active');
var elem = $(this);
$(this).remove();
$('ul').prepend(elem);
$(this).children('a').addClass('lang-active');
});
});
<script>
Here's your sort:
var listItems = myList.children('li').get();
listItems.sort(function(a,b){
return $(a).hasClass('lang-inactive') ? -1 : $(b).hasClass('lang-inactive') ? 1 : 0;
});

Categories

Resources