jQuery add active class to parent on page load - javascript

(All child is active as shown in the picture)
I want to add class="active" to parent when its child is clicked. I manage to add class "active" to parent but all the child is added class= "active" too. What i want is only the chosen child and its parent is "active".
Jquery:
$(document).ready(function(){
var pathname = window.location.pathname;
var filename=pathname.replace(/^.*[\\\/]/, '');
var currentLink=$('a[href="' + filename + '"]'); //Selects the proper a tag
currentLink.parents('.doctormenu').find('li a').removeClass('active');
currentLink.parentsUntil('.doctormenu', 'li').addClass('active');
//currentLink.parent().addClass("active");
//alert(filename);
})
Html:
<ul class="doctormenu">
<li>home</li>
<li>about</li>
<li>Disease</li>
<li>Search</li>
<li><a href="#" >
Services</a>
<ul>
<li>Self Diagnosis</li>
<li>Online Consultation</li>
<li>Clinic Appointment</li>
</ul>
</li>
</ul>

Here's a fiddle with a proper demo
The important code would be this:
// you can change this on.hashchange for the on.documentready
$(window).on('hashchange', function () {
// select a reference, in your case can be the pathname or whatever
var ref = location.hash
// find the matching element
var $el = $('a[href="' + ref + '"]')
// and it's closest parent (avoid select other
// parents and it's less risky than .parent)
var $menu = $el.closest('.doctormenu')
// remove previous active, if there's any
// (may you don't need this if the page is reloading)
$('.doctormenu')
.removeClass('active')
.find('a')
.removeClass('active')
// execute the needed operations, adding class in this example
$el.addClass('active')
$menu.addClass('active')
});

$('.doctormenu li a').each(function(){
// and test its normalized href against the url pathname regexp
if(urlRegExp.test(this.href.replace(/\/$/,''))){
$(this).parent().addClass('active');
}
});

Related

Add active Menu or Navigation class based on URL

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"

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

Jquery programatically adding li, getting id returns all li elements

I am adding li elements to a menu programatically every time the user clicks a button. Here is the starting menu:
<ul id="menu">
<li><a href='#'>Add to this menu</a>
<ul class = 'addition'>
</ul>
</li>
</ul>
I then add to it using this:
$("#menu ul.addition").append('<li><a href="#" id=addition' + userText + '>addition' + userText + '</a></li>');
Where user text is some unique String added by the user. The problem is that when I try to get a specific li from the menu after it is populated, it only returns the first li.
$("#menu ul.addition").click(function() {
var selected = $('#menu ul.addition a').attr('id');
console.log(selected);
});
always logs the first menu item even though there are many being populated. when I change the selection to to select the html like so:
var selected = $(this).html();
console.log(selected);
It just logs every li element added to the menu.
What am I doing wrong here? I need to select the correct menu option that the user clicks on.
When you access an attribute for a set of multiple elements, you'll get the attribute of the first element in the set. In your code, you're selecting the id of the first <a> element in your <ul> upon any click on the <ul>.
In order to identify which <a> was clicked, its easiest to listen for a click on the <a> elements rather than on the <ul> container.
Since the <li> and <a> elements are added after the DOM loads, you'll need to delegate your click handler. I suggest binding the listener to your existing <ul>, but listening for a click on any programmatically-added child li > a element.
Then, you can use JavaScript's this keyword to refer to the clicked element and collect its "id".
var userText="SampleText";
$("#menu ul.addition").append('<li>addition' + userText + '</li>');
userText="AnotherSample";
$("#menu ul.addition").append('<li>addition' + userText + '</li>');
$("#menu ul.addition").on('click','li a',function() {
var selected = this.id;
$('div#output').html(selected);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<ul id="menu">
<li><a href='#'>Add to this menu</a>
<ul class = 'addition'>
</ul>
</li>
</ul>
<div id="output"></div>
I think you are more or less on the the right track. If you slightly changed your click function, you can get the ID of the menu option, clicked by the user. Here is a fiddle for it.
$("#menu ul.addition").click(function(e) {
alert(e.target.id);
for (var prop in e) {
console.log(prop + " : " + e[prop]);
}
$('#menu ul.addition a').attr('id');
// console.log(selected);
});
var $li = $('<li><a href="#" id=addition' + userText + '>addition' + userText + '</a></li>');
$li.click(function(){
var selected = $(this).html();
console.log(selected);
});
$("#menu ul.addition").append($li);
It seems this is what you want
First of all, you have change <a href="#" id=addition' + userText + '> to <a href="#" id="addition' + userText + '">
When you run $('#menu ul.addition a') jquery returns all the <a> nodes, but when you try to get the ID of a set, Jquery selects the first node in the set.
If you want to select a specific item on the list, use the unique ID.
$('#menu ul.addition #your-unique-id).click(doSomething)
if you want to create a generic function for clicking any of the added items:
$("#menu ul.addition").on('click', 'a', function(ev){
console.log(this);
})
If you want to get the specific li you need to use this example:
$("#add").click(function() {
$(".addition").append('<li>Item 1</li>');
$(".addition").append('<li>Item 2</li>');
$(".addition li a").click(function() {
var item = $(this).text();
alert(item);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<ul id="menu">
<li>Add to this menu
<ul class="addition">
</ul>
</li>
</ul>
$("#menu ul.addition").on('click', 'li', function() {
console.log($(this).attr('id'));
});

How to add class based on location and corresponding href?

I have a menu with a simple markup , and my aim is to add a class to the menu <li> item automatically by the name of the current page ....
The relevant Markup is :
<ul class="sub-menu">
<li >
<a href="page_example_one.html">
<i class="icon-time"></i>
Timeline</a>
</li>
<li >
<a href="page_example_two.html">
<i class="icon-cogs"></i>
Page Two</a>
</li>
.... Many other elements
</ul>
What I need to get is very simple , when I am on a certain page ( assume page_example_one.html
) I would need the corresponding <li> element to have an additional class like so
<li class="active">
<a href="page_example_one.html">
<i class="icon-time"></i>
Timeline</a>
</li>
I tried to do that with jQuerylike so :
jQuery(document).ready(function() {
// Get the current page name ( pathname)
var currentUrl = jQuery(location).attr('pathname');
// Get the element ( try at least )
var currentMenuItem = jQuery("sub-menu li a[href='" + currentUrl + "']");
// Add the class
currentMenuItem.addClass("active");
//Tried also something like this :
// jQuery("sub-menu li a[href='" + currentUrl + "']").find('a').addClass("active");
});
both the methods above failed for me - ( the commented one with VAR , and the concatenated )
But because my JS skills are very low, I can not really see what I am doing wrong ( probably somehting really obvious to someone who knows JS )
After resolving this issue, I would also like to know how to add spans or classes also to a parent menu item ( in case of sub menu ) based on the current page link ...
var currentMenuItem = jQuery("a[href='" + currentUrl + "']").parent()
Add a demo here
target the submenu by its class ul.sub-menu. alternativley you can also target more generally all items with the class by .sub-menu. sub-menu alone would target a theoretical <sub-menu> element.
than get the parent (the <li>) of the link:
var currentMenuItem = jQuery(".submenu li a[href='" + currentUrl + "']").parent();
also check if the currentUrl is equal to the href. you can output currentUrl to console for debugging like this:
console.log(currentUrl);

how do I activate my jquery tabber based on the link URL

I'm pretty new to jquery and I decided to build a jquery tabber. So far so good but I have a little problem!!! I cant see how I can activate the tabber based on the URL. For instance when the link is www.myweb.com#tab2, the second tabber becomes activated. My jquery is as follows. Now I know jquery has it's own tabber script but I don't want to use it. So anybody else help me accomplish this please
Javascript
$(document).ready(function() {
var hash = location.hash;
var link1 = ("ul#tabs li a[href='" + hash + "']")
var link2 = ("ul.tabs li a[href='" + hash + "']")
var link3 = ("ul#tabs li[href='" + hash + "']")
$(".tab_content").hide(); //Hide all content
if ((link3.length)(link2.length)(link1.length))
{ //check if such link exists
$(link3, link2, link1).parent().addClass("active"); //Activate tab
$(hash).show();
}
else {
$("ul.tabs li a:first, ul#tabs li:first, ul#tabs li a:first").addClass('active');
$(".tab_content:first").show()
// On Click Event
$("ul.tabs li").click(function() {
$("ul.tabs li").removeClass("active"); //Remove any "active" class
$(this).addClass("active"); //Add "active" class to selected tab
$(".tab_content").hide(); //Hide all tab content
var activeTab = $(this).find("a").attr("href"); //Find the href attribute value to identify the active tab + content
$(activeTab).fadeIn(); //Fade in the active ID content
return false;
});
});
HTML
<ul class="tabs">
<li>Design Team</li>
<li>Publications</li>
<li>Awards & Recognitions</li>
<li>Our Mission</li>
<li class="last-item">Company Profile</li>
</ul>
this is how far I have come. Since I have 3 selectors the jquery code is weirdly not working how do I achieve this so tabber is activated based on URL? Thanks
Look at JQueryUI, they have pre-built components like this.
Specifically: http://jqueryui.com/tabs/
Edit:
Or is their a specific reason why you are building your own?
You can set the selected tab using the following :
$(document).ready(function() {
$('#tabs').tabs(); // make jquery tabs
$("#tabs").tabs("select", window.location.hash);
});
Second parameter of $.tabs function accept either index or a selector.

Categories

Resources