Li parent elemnt is not selected on child li selection in jquery - javascript

I have write code to make the li active on url basis .It works fine but it fails on child li.It make child li active while i want that top li should be active not child.My code is below:
<script type="text/javascript">
jQuery(function () {
setNavigation();
});
function setNavigation() {
// this portion code make li active on url basis
var pathname = window.location.pathname;
path = pathname.replace(/\/$/, "");
path = decodeURIComponent(path);
var value = jQuery(location).attr('href');
// value = value.replace('.html', ''); alert(value);
jQuery(".flexy-menu a").each(function () {
var href = jQuery(this).attr('href');
if (value === href) {
jQuery(this).closest('li').addClass('active');
}
});
// this is code for child li but only first code works
jQuery('.flexy-menu').children('li').click(function(){
jQuery(this).parent('li').addClass('active');
});
}</script>
My HTML is like this :
<ul class="flexy-menu orange">
<li style="">Home</li>
<li style="">Collection
<ul style=""> <li>My Secret Garden </li>
<li>Legend</li></ul>
</li>
<li class="active" style="">Artisans</li>
<li style="">Contact </li>
</ul>

Instead of parent use .closest():
jQuery(this).closest('li').addClass('active');
and put this in doc ready:
jQuery(function () {
setNavigation();
jQuery('.flexy-menu').find('li').click(function(){
jQuery(this).closest('li').addClass('active');
});
});
Here i changed your selector little bit with .find() instead of .children(), because .find() looks for grand child also and if you want to traverse up to the parent then use .closest() method.
I have write code to make the li active on url basis
Okay! then you can choose to do this:
$('a[href*="'+ path +'"]').parents('li').addClass('active');
This should work:
All to all you just need to do this only, no extra function required:
jQuery(function () {
var path = window.location.pathname;
$('a[href*="'+ path +'"]').parents('li').addClass('active');
jQuery('.flexy-menu').find('li').click(function(){
jQuery(this).closest('li').addClass('active');
});
});

jQuery('.flexy-menu > li').click(function(e){
jQuery(this).closest('li').addClass('active').siblings().removeClass('active');
e.preventDefault();
});
Demo:
http://jsfiddle.net/hqPQu/

Related

add class on li remove after page load

I am using jquery to add the class to active css on "li" and also navigate to an html page.but after page navigates the class disappers on "li". I have tried different ways to resolve this but couldn't get the point.
$(document).ready(function(){
$( '#topList ul li' ).click(function() {
alert($(this).attr('id'));
if($(this).attr('id') == "add") {
document.location.href = 'localhost:8080/add';
$(this).attr('id').addClass("active");
}
});
});
here is the menu list, what I want is when I click on li it should call a page add and also add a class on that li.
html code
<ul class="nav">
<li class="" id="add"></i> Add </li>
<ul>
You need to add class for the li in the page you are calling ie, the page will be rendered when you call localhost:8080/add.
Because in your code setting up of active class wont be called since the localhost:8080/add will start loading in the previous line of code (document.location.href = 'localhost:8080/add';)
If the page to be rendered is static page then, add this code in that page.
$(document).ready(function(){
$('#add').addClass("active");
});
Use the following script on the page where you have menu or the links.
<div id="cssmenu">
<a href="blah blah" > Test page</a>
<a href="blah blah" > Test page</a>
</div>
$(document).ready(function () {
var pageTitle = window.location.pathname.replace(/^.*\/([^/]*)/, "$1");
$('#cssmenu a').each(function () {
if ($(this).attr('href').toLowerCase() == pageTitle.toLocaleLowerCase())
$(this).addClass('active');
});
});
I solved this problem on my website by looking at the URL and deciding which of the navigation elements was best to add.
function showContent(target) {
var e = $('#'+target);
$(".content").hide();
$("#nav li.active").removeClass("active");
$("#nav li[target='"+target+"']").addClass("active");
e.toggle();
ga('send','pageview',window.location.pathname+"#"+target);
}
// this looks at the URL (by the #...) and decides which view is active
// this gets called on ready and if the client hits the link
// (which dynamically loads instead of making a trip for a new page to the server)
$(window).hashchange(function() {
var which=window.location.hash.substring(1);
switch( which) {
default:
which="profile";
case "profile":
case "resume":
case "projects":
case "contact":
showContent( which);
}
});

Add class for parent of parent

how can I add a class in a drop dowwn menu on click when child of parent of parent is clicked.
This is my html:
<ul id="FirstLevel">
<li>FirstLevel</li>
<li>FirstLevel
<ul class="secondLevel">
<li>SecondLevel</li>
<ul class="LastLevel">
<li>LastLevel</li>
<li>LastLevel</li>
</ul>
<li>SecondLevel</li>
<li>SecondLevel</li>
</ul>
</li>
<li>FirstLevel</li>
<li>FirstLevel</li>
<li>FirstLevel</li>
</ul
So what I need is that; onclick on LastLevel or SecondLevel of my menu I want to add a class via jQuery on FirstLevel li and to remove that class when another sub menu is selected.
I've tried this but is not really working:
$('#firstUl').find('li').click(function(){ //removing the previous selected menu state $('#firstUl').find('li').removeClass('active'); //is this element from the second level menu? if($(this).closest('ul').hasClass('lastLevel')){ $(this).parents('li').parents('li').addClass('menuActive'); //this is a parent element }else{ $(this).addClass('menuActive'); } });
Thank you.
Give your FirstLevel <li>'s a class, it'd make it much easier to target the correct element:
<li class="first-level">FirstLevel</li>
Then attach a click handler to all child <li>'s:
$('li.first-level li').on('click', function(e) {
e.preventDefault(); // prevent the link from being followed
$(this).closest('li.first-level').toggleClass('yourClass') //
.siblings('li.first-level').removeClass('yourClass');
});
Here's a fiddle
This does all the things you want:
$("ul.secondLevel a").click(function () {
$("#FirstLevel>li").removeClass("blue");
$(this).parents("ul.secondLevel").parent().addClass("blue");
});
Check here: http://jsfiddle.net/c4dTK/
Here is the solution :
$('.secondLevel li a').click(function (e) {
$('#FirstLevel > li').removeClass('selected');
$(this).parents('.secondLevel').parent().addClass('selected');
})
As your first level list has been given an Id, you could just find the element using a selector as follows:
$(".secondLevel a").click(function () {
e.preventDefault();
$("#FirstLevel li").addClass("newClass");
});
try this
jQuery(this).parent('ul').addClass('yourClass');
Or:
jQuery(this).parents('ul').addClass('yourClass');
here goes another answer
var test= $('li li,li li li')
console.log(test)
test.click(function(){
$(this).parents('ul').closest('li').addClass('kaka');
});
jsfiddle

How do I use jquery to get the Next/Previous Page(s)

when click next button will redirect to next li
<div id="mainmenu">
<ul id="menu">
<li class="active">Home</li>
<li >News</li>
<li >Sports</li>
</ul>
next
prev
I assume you want to cycle through those <li>s based on where the active class currently is?
Well, to get the next, you could use the ... next method :)
$('.next').click(function(){
var $current = $('li.active');
var $next = $current.next();
if ($next.length){
window.location = $next.find('a').attr('href'); //I assume???
} else {
//let's wrap around to the first li in the list, per TJ's comment
var $wrapAroundTarget = $current.siblings().first();
window.location = $wrapAroundTarget.find('a').attr('href');
}
});
And of course previous would be the same thing, but with the prev method instead of next, and, per TJ again, to wrap around to the last <li>, simply use $current.siblings().last().
How about this?
$('a.next').click(function() {
$('#mainmenu li.active').next().each(function () {
window.location = $(this).find('a').attr('href');
});
});
$('a.prev').click(function() {
$('#mainmenu li.active').prev().each(function () {
window.location = $(this).find('a').attr('href');
});
});
If you can guarantee that the you don't try to go prev from the first link or next from the last one (by hiding the links, etc), the code could be simplified significantly:
$('a.next').click(function() {
window.location = $('#mainmenu li.active').next().find('a').attr('href');
});
$('a.prev').click(function() {
window.location = $('#mainmenu li.active').prev().find('a').attr('href');
});

compare url string and menu string then add class using jquery

I have a URL which looks like this:
http://www.website.co.uk/en-us/aboutus/thegroup/test.aspx
I have a UL LI menu on the page:
<ul>
<li>Test</li>
<li>Hello</li>
<li>Bye</li>
<li>Something</li>
<li>Cars</li>
</ul>
I am having the menu on every page and would like to use jquery to check that im on that page. If i am then make the A/li bold so the user knows they are on the page.
I have tried the following:
$(document).ready(function () {
if(window.location.href.indexOf("test")) //
{
alert("your url contains the name test");
}
});
But id like something that doesnt involve hard coding the values of the URL string. As if the user decides to add more links to the UL/LI the jquery needs to check the link and the url automatically and add a class to the LI (so that i can style it).
Hopefully thats enough infomation.
The issue is because the indexOf() method returns -1 when the value is not found. You need to check for that value, not coerce the result to a boolean as you currently are. Try this:
$(document).ready(function () {
var loc = window.location.href;
$("ul a").each(function() {
if (loc.indexOf($(this).attr("href")) != -1) {
$(this).addClass("current");
}
});
});
You would need to make the selector a bit more specific, something like #menu a
This?
$('ul#menu a').each(function() {
if(window.location.href.indexOf($(this).attr('href')) !== -1) {
$(this).closest('li').addClass('yourClass');
}
});
I added an id menu to your ul to basically differentiate your menubar with other uls that may be in the same page. also !== -1 as indexOf returns -1 if it can't find the string searched in the argument.
indexOf returns -1 if the string is not contained:
(document).ready(function () {
if(window.location.href.indexOf("test") != -1) //
{
alert("your url contains the name test");
}
});
$(document).ready(function () {
var liTest = $('ul > li'); // ' was missing
liTest.each(function() {
if(window.location.href == $('a', this).attr('href')) //
{
$(this).css('font-weight', 'bold');
return;
}
});
});

Get index of element as child relative to parent

Let's say I have this markup:
<ul id="wizard">
<li>Step 1</li>
<li>Step 2</li>
</ul>
And I have this jQuery:
$("#wizard li").click(function () {
// alert index of li relative to ul parent
});
How can I get the index of the child li relative to it's parent, when clicking that li?
For example, when you click "Step 1", an alert with "0" should pop up.
$("#wizard li").click(function () {
console.log( $(this).index() );
});
However rather than attaching one click handler for each list item it is better (performance wise) to use delegate which would look like this:
$("#wizard").delegate('li', 'click', function () {
console.log( $(this).index() );
});
In jQuery 1.7+, you should use on. The below example binds the event to the #wizard element, working like a delegate event:
$("#wizard").on("click", "li", function() {
console.log( $(this).index() );
});
something like:
$("ul#wizard li").click(function () {
var index = $("ul#wizard li").index(this);
alert("index is: " + index)
});
There's no need to require a big library like jQuery to accomplish this, if you don't want to. To achieve this with built-in DOM manipulation, get a collection of the li siblings in an array, and on click, check the indexOf the clicked element in that array.
const lis = [...document.querySelectorAll('#wizard > li')];
lis.forEach((li) => {
li.addEventListener('click', () => {
const index = lis.indexOf(li);
console.log(index);
});
});
<ul id="wizard">
<li>Step 1</li>
<li>Step 2</li>
</ul>
Or, with event delegation:
const lis = [...document.querySelectorAll('#wizard li')];
document.querySelector('#wizard').addEventListener('click', ({ target }) => {
// Make sure the clicked element is a <li> which is a child of wizard:
if (!target.matches('#wizard > li')) return;
const index = lis.indexOf(target);
console.log(index);
});
<ul id="wizard">
<li>Step 1</li>
<li>Step 2</li>
</ul>
Or, if the child elements may change dynamically (like with a todo list), then you'll have to construct the array of lis on every click, rather than beforehand:
const wizard = document.querySelector('#wizard');
wizard.addEventListener('click', ({ target }) => {
// Make sure the clicked element is a <li>
if (!target.matches('li')) return;
const lis = [...wizard.children];
const index = lis.indexOf(target);
console.log(index);
});
<ul id="wizard">
<li>Step 1</li>
<li>Step 2</li>
</ul>
Take a look at this example.
$("#wizard li").click(function () {
alert($(this).index()); // alert index of li relative to ul parent
});
Delegate and Live are easy to use but if you won't have any more li:s added dynamically you could use event delagation with normal bind/click as well. There should be some performance gain using this method since the DOM won't have to be monitored for new matching elements. Haven't got any actual numbers but it makes sense :)
$("#wizard").click(function (e) {
var source = $(e.target);
if(source.is("li")){
// alert index of li relative to ul parent
alert(source.index());
}
});
You could test it at jsFiddle: http://jsfiddle.net/jimmysv/4Sfdh/1/
Yet another way
$("#wizard li").click(function ()
{
$($(this),'#wizard"').index();
});
Demo
https://jsfiddle.net/m9xge3f5/

Categories

Resources