change class name with js - javascript

I have menu list that contains:
<ul class="content_menu tabs">
<li class="pager_link_0_active"></li>
<li class="pager_link_1"></li>
<li class="pager_link_2"></li>
<li class="pager_link_3"></li>
<li class="pager_link_4"></li>
<li class="pager_link_5"></li>
<li class="pager_link_6"></li>
<li class="pager_link_7"></li>
<li class="pager_link_8"></li>
</ul>
What I want to do is when particular link is clicked I need to remove active from li class name that contains active (e.g pager_link_0_active) and add active to the li that is clicked (e.g pager_link_2_active)
I know there is one way to make it:
$(".active").removeClass("active");
$(this).addClass("active");
but in my situation, active is not seperated, it is part of class name.

According to standards ul can contain only element but what you want can be achived these way:
$(function () {
$('ul.content_menu.tabs a.tab').click(function () {
var newActive = $(this);
if (newActive.hasClass('active')) {
return;
}
var oldActive = $('ul.content_menu.tabs a.tab.active');
oldActive.removeClass('active');
var oldIndex = $('ul.content_menu.tabs a.tab').index(oldActive);
oldActive.children().attr('class', 'pager_link_' + oldIndex);
var newIndex = $('ul.content_menu.tabs a.tab').index(newActive);
newActive.addClass('active');
newActive.children().attr('class', 'pager_link_' + newIndex + '_active');
});
});
Here is fiddle

It would be better to make it a separate class <li class="pager_link_1 pager_active">, then you can remove and add pager_active easily.
If the LI will always have just one class, try this:
var active_li = $(".active li");
var active_class = active_li.attr("class");
active_li.attr("class", active_attr.replace("_active", "");
var this_li = $(this).children("li");
var this_class = this_li.attr("class");
this_li.attr("class", this_class+"_active");

Related

Search and returned li element in JQuery

I have a ul of class items . The ul has li each of class item and different id example id1 id2 id3. We have a jquery code that select each item like below and perform action based on the selected or clicked linked.
$("#main-menu .items a").each(function () {
var url = new URL($(this).attr('href'));
if(url.is_in(that.page_url)) {
item = $(this).closest('.item');
}
});
Example like
<ul class="items">
<li id="id1" class="item"></li>
<li id="id2" class="item"></li>
<li>....</li>
My question is what would the item from the jquery code above return? My pages are separated by language, let say i want to set a value for item in the jquery code based on my language, how would i do that and what should my item look like? I tried below.
$("#main-menu .items a").each(function () {
var url = new URL($(this).attr('href'));
if(url.is_in(that.page_url) && page.language() === 'EN' && /\/text/.test(page.url)) {
item = "http://example.com/id2";
}
else{
if(url.is_in(that.page_url)) {
item = $(this).closest('.item');
}
}
});
Please where do i go wrong ? Any help would be appreciated.

Get Values of sub elements of clicked class using jquery

I have a class amt and when that class is clicked I want to get the values of the clicked <h6>, <span> and <label> tags.
How do I do this in jquery? I have already seen a question here Get value of List Item with jQuery but it uses same under tag but i have to get different elemet value under same tag
<li class="amt" id="diecut_am1">
<h6>50</h6>
<span>$59.00</span>
<label>$51.30</label>
</li>
<li class="amt" id="diecut_am2">
<h6>100</h6>
<span>$68.00</span>
<label>$61.20</label>
</li>
Try this
$(".amt").click(function() {
var elem1 = $(this).find("h6").html();
var elem2 = $(this).find("span").html();
var elem3 = $(this).find("label").html();
alert(elem1);
alert(elem2);
alert(elem3);
});
https://jsfiddle.net/kLe5kLc3/1/
You could do something like this:
$( document ).ready(function() {
$('.amt').on("click", function() {
var h6 = $(this).find('h6').text();
var span = $(this).find('span').text();
var label = $(this).find('label').text();
});
});
Demo: https://jsfiddle.net/12q12k52/
here's the JS way :
var amt = document.querySelectorAll('.amt')
//add event listener to all .amt elements
var amtArr = [].slice.call(amt)
amtArr.forEach(function (x) {
x.addEventListener('click', listChilds, true)
});
//we retrive the target properties
function listChilds(e) {
console.log(e.path[1]) //all the children
//if you want one in particular it would be
console.log(e.target.childNodes[0])
}
<li class="amt" id="diecut_am1">
<h6>50</h6>
<span>$59.00</span>
<label>$51.30</label>
</li>
<li class="amt" id="diecut_am2">
<h6>100</h6>
<span>$68.00</span>
<label>$61.20</label>
</li>
You can iterate over the children of the clicked elements
$(this).children()

Combine cloned UL menus

I am cloning UL's from one element to another like so.
$( "#mobMenu li a" ).each(function(index) {
var subID = $(this).attr('id')
if (typeof(subID) !== "undefined") {
subID = "#sub_" + subID + " .subnav-menu"
var subMenu = $(subID).clone();
$(this).parent().append(subMenu);
}
});
Menu I am cloning:
<div id="sub_cat3">
<ul id="sub_cat" class="subnav-menu">
<li>..</li>
</ul>
<ul class="subnav-menu">
<li>..</li>
</ul>
</div>
Into a new mobile menu that looks like this:
<ul id="mobMenu">
<li><a id="cat3"></a>
// cloned menu to go here
</li>
</ul>
So ho can I combine each cloned ul into one UL?
<ul class="subnav-menu">
<li>..</li>
<li>..</li>
</ul>
I think you want something like this (had to contrive the HTML as a suitable example was not provided):
JSFiddle: http://jsfiddle.net/TrueBlueAussie/b10n5mf0/1/
or with your new HTML: http://jsfiddle.net/TrueBlueAussie/b10n5mf0/4/
$("#mobMenu li a").each(function (index) {
var subID = $(this).attr('id')
console.log(subID);
if (subID) {
subID = "#sub_" + subID + " .subnav-menu li"
var $div = $('<ul>').append($(subID).clone());
$(this).closest('li').append($div);
}
});
Notes:
It creates a single UL for each matching set of lists' LIs.
Only the matching LIs are cloned, then inserted under the created UL with append.
if (typeof(subID) !== "undefined") can be replaced with if (subID) as attr returns a string or undefined (and empty strings are treated as undefined by your code).
You can do...
var $subs = $('.subnav-menu'),
$lis = $subs.find('> li').clone();
// Add all the $lis to the first subnav...
$subs.eq(0).append($lis);
// Remove the rest of the subs...
$subs.slice(1).remove();
Here is a small demo: http://jsbin.com/jerapo/2/edit?js,output

dynamically apply active class to nav li

I have included a header to my files as in include. In the header is the nav bar.
How do I, using jQuery, apply class="active" to the relevant li.
The only way I could think of doing it is to set a variable on the actual pages, apply an id that is equal to that variable of the relevant page and if function so if they match apply a class to the li.
However, I thought there must be a simpler way of achieving this.
<ul class="nav nav-pills right" id="div">
<li id="home" class="active">
Home
</li>
<li id="search">
Search
</li>
<li id="contact">
Contact
</li>
</ul>
An easy way to do this would be to have a script per page:
$('#home').addClass('active'); // for home page
You could try and match the href to the current url:
var path = window.location.pathname.substring(1);
$('.nav>li>a[href="' + path + '"]').parent().addClass('active');
More compact way:
$(function(){
var sPath = window.location.pathname;
var sPage = sPath.substring(sPath.lastIndexOf('/') + 1);
$('a[href="'+ sPage +'"]').parent().addClass('active');
});
As soon as the page loads it will run this code:
$(document).ready(function(){
$('li').removeClass('active');
$('li a').each(function() {
$found = $.contains($(this).prop("href"),location.pathname);
if ($found) {
$(this).closest('li').addClass('active');
break;
}
});
});
OR
You can also do this using regex :
$(document).ready(function(){
$('li').removeClass('active');
var regex = /[a-z]+.php/g;
var input = location.pathname;
if(regex.test(input)) {
var matches = input.match(regex);
$('a[href="'+matches[0]+'"]').closest('li').addClass('active');
}
});
You might need to have the similar id name to that of php file.
Check the demo here : Demo
You can do this:
//remove the active class from all items, if there is any
$('.nav>li').removeClass('active');
//finally, add the active class to the current item
$('a[href='+ location.pathname.substring(1) +']').parent().addClass('active');
You could use javascript to find the current list item based on the url, by adding the class to the right list item after the DOM has been loaded (e.g. string manipulation of window.location together with JQuery selectors and addClass())
I found a routine to set active (current) class on my shared menu, but I need to modify it to set the parent link only, and not the 'closest' link. It works great on menu items with no sub menus, but when a sub menu item is clicked, there is not indication on the main menu after page load. (the code I need to modify is below)
(function( $ ) {
$.fn.activeNavigation = function(selector) {
var pathname = window.location.pathname
var extension_position;
var href;
var hrefs = []
$(selector).find("a").each(function(){
// Remove href file extension
extension_position = $(this).attr("href").lastIndexOf('.');
href = (extension_position >= 0) ? $(this).attr("href").substr(0, extension_position) :
$(this).attr("href");
if (pathname.indexOf(href) > -1) {
hrefs.push($(this));
}
})
if (hrefs.length) {
hrefs.sort(function(a,b){
return b.attr("href").length - a.attr("href").length
})
hrefs[0].closest('li').addClass("current")
}
}; })(jQuery);
If someone still checks on google how to do it here is my solution
var path = window.location.href; // full url
$('a[href="'+ path +'"]').parent().addClass('active'); // find by selector url
HTML
<ul class="navbar-nav mr-auto">
<li class="nav-item">
<a class="nav-link" href="http://example.com/">Home</a>
</li>
<li class="nav-item">
<a class="nav-link" href="http://example.com/history"> History</a>
</li>
</ul>

add class to last 2 links from a generate ul list

I have a function that generates a unordered list of links and I want to use javascript to select the last 2 links so that I can align them to the right.
so in the following example I would need to select the li parent of link4 and link5, then add a class so i can style it
<ul>
<li>link1</li>
<li>link2</li>
<li>link3</li>
<li>link4</li>
<li>link5</li>
</ul>
In the end it should be something like this:
<ul>
<li>link1</li>
<li>link2</li>
<li>link3</li>
<li class="align_right">link4</li>
<li class="align_right">link5</li>
</ul>
Couldn't you generate class="align_right" for the last 2 links when you build the list?
By the way, if you want to do this by javascript, you could do:
//get the sidebarmenu element
var sidebar = document.getElementById('sidebarmenu');
//getting the ul inside the wrapper
var ul = sidebar.getElementsByTagName("ul")[0];
//getting al the li childs
var li = ul.getElementsByTagName("li");
var totLi = li.length;
if(totLi >= 2){ //setting class to last 2
li[totLi-1].className = "align_right";
li[totLi-2].className = "align_right";
}
Edit: updated for your particular needs
Running example:
http://www.jsfiddle.net/steweb/m4v2J/
In Jquery:
$('ul li:last-child').prev('li').andSelf().addClass("align_right");
This best be done in the function generating those items, if you insist on client side script afterwards, here it is:
var oList = document.getElementById("myList");
var arrItems = oList.getElementsByTagName("li");
if (arrItems.length >= 2) {
arrItems[arrItems.length - 2].className = "align_right";
arrItems[arrItems.length - 1].className = "align_right";
}
For this to work, add ID to the <ul> tag and use it,

Categories