How to trigger click on next tab in jQuery, I have tried below code but not working, TIA.
var c = $('ul#tabs li').length;
var selected = parseInt($('ul#tabs li.active').index())+1;
if (c != selected) {
$("ul#tabs li:nth-child(" + selected + ")").click();
return false;
}
<div id="mytabs">
<ul class="nav nav-tabs" id="tabs">
<li class="active"><a data-toggle="tab" href="#Personal" aria-expanded="false">Personal</a></li>
<li><a data-toggle="tab" href="#Business">Business</a></li>
<li><a data-toggle="tab" href="#Documents" aria-expanded="true">Documents</a></li>
<li><a data-toggle="tab" href="#References">References</a></li>
<li><a data-toggle="tab" href="#OrderDelivery">Order & Delivery</a></li>
</ul>
</div>
I'm a bit unclear as to what's not working, but the simplified code below is all that's required to get current tab and next tab:
$(document).ready(function() {
let currentTab = $('ul#tabs li.active');
let nextTab = currentTab.next();
// Once you have the tab, click it (clicking after 2 seconds to demonstrate)
setTimeout(function() { nextTab.find("a").get(0).click()}, 2000);
// If you need to do things when a tab is clicked, create an event handler
$('a[data-toggle="tab"]').click(function(event) {
// Do something when a tab is clicked
// For example: Remove active class, and add it to active element
$('a[data-toggle="tab"]').parent().removeClass("active");
// Add active class to clicked li
$(this).parent().addClass("active");
});
});
.active a {
color: green !important;
font-weight: bold;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="mytabs">
<ul class="nav nav-tabs" id="tabs">
<li class="active"><a data-toggle="tab" href="#Personal" aria-expanded="false">Personal</a></li>
<li><a data-toggle="tab" href="#Business">Business</a></li>
<li><a data-toggle="tab" href="#Documents" aria-expanded="true">Documents</a></li>
<li><a data-toggle="tab" href="#References">References</a></li>
<li><a data-toggle="tab" href="#OrderDelivery">Order & Delivery</a></li>
</ul>
</div>
Related
This is how my code looks like:
<div class="header-nav navbar-collapse collapse ">
<ul id="navigation" class=" nav navbar-nav">
<li>
Home
</li>
<li>
About Us
</li>
</ul>
</div>
I've been trying to add the active class to each of them when the user is on that specific page but no succes so far
Tis is how my script looks like:
var i = 0;
[].forEach.call(document.querySelectorAll('li > a'), function(nav) {
console.log(nav.pathname,window.location.pathname);
if (nav.pathname === window.location.pathname){
i = 1;
console.log(i);
nav.classList.add('active')
}
else{
console.log(i)
nav.classList.removeClass('active')
}
})
The active class is set on the "a" not on "li" and i don't know how to fix this. Maybe someone can help me?
In looking at the classes, it looks like you may be using Bootstrap. I added in those libs to the snippet, and updated some of the classes. I also added in another nav item with the href equal to js since that is the pathname for the snippet window. Otherwise it won't add the active class as there would not be a pathname that would be equal.
I also changed the nav items to pills, so you can see the active link easier.
var i = 0;
document.querySelectorAll('ul.nav > li > a').forEach((nav) => {
console.log({
navPathname: nav.pathname,
windowLocationPathname: window.location.pathname,
areEqual: nav.pathname === window.location.pathname,
});
if (nav.pathname === window.location.pathname) {
nav.classList.add('active')
} else {
nav.classList.remove('active')
}
})
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">
<script src="https://cdn.jsdelivr.net/npm/bootstrap#5.0.2/dist/js/bootstrap.bundle.min.js" integrity="sha384-MrcW6ZMFYlzcLA8Nl+NtUVF0sA7MsXsP1UyJoMp4YLEuNSfAP+JcXn/tWtIaxVXM" crossorigin="anonymous"></script>
<div class="navbar navbar-light bg-light">
<ul id="navigation" class="nav nav-pills">
<li class="nav-item">
<a class="nav-link" href="index.html">Home</a>
</li>
<li class="nav-item">
<a class="nav-link" href="js">JS</a>
</li>
<li class="nav-item">
<a class="nav-link" href="about-us.html">About Us</a>
</li>
</ul>
</div>
To target the parent element, you have a few options - my favorite is element.closest(selector) which takes a starting element and finds the closest containing parent that matches selector
let els = document.querySelectorAll('li > a');
els.forEach(el => {
el.addEventListener('click', e => {
els.forEach(a => a.closest('li').classList.remove('active'));
e.target.closest('li').classList.add('active');
})
})
li.active {
background-color: green;
}
<ul>
<li><a href='#'>link 1</a></li>
<li><a href='#'>link 1</a></li>
<li><a href='#'>link 1</a></li>
</ul>
Thanks for this, i merged the two responses and made it into one that works for me, this is the script that worked without even touching the classes into the nav-bar:
document.querySelectorAll('ul.nav > li > a').forEach((nav) => {
console.log({
navPathname: nav.pathname,
windowLocationPathname: window.location.pathname,
areEqual: nav.pathname === window.location.pathname,
});
if (nav.pathname === window.location.pathname) {
nav.closest('li').classList.add('active')
} else {
nav.closest('li').classList.remove('active')
}
})
I am developing a web page wherein I have header(containing the navigational menu) in separate html file say reusableheader.html and footer in separate file i.e. reusablefooter.html.
reusableheader.html:
<style>
.nav-menu a:hover, .nav-menu .active > a, .nav-menu li:hover > a {
color: #3fbbc0;
border-color: #3fbbc0;
}
</style>
<script>
$(function(){
var current_page_URL = location.href;
$( "a" ).each(function()
{
if ($(this).attr("href") !== "#")
{
var target_URL = $(this).prop("href");
if (target_URL == current_page_URL)
{
$("a").parent("li").removeClass("active");
$(this).parent("li").addClass("active");
return false;
}
}
});
});
</script>
<nav class="nav-menu d-none d-lg-block"> //set to fixed-top.
<ul>
<li class="active"><a class="nav-link" href="/hospital/">Home</a></li>
<li><a class="nav-link" href="/hospital/aboutus">About</a></li>
<li><a class="nav-link" href="/hospital/services">Services</a></li>
<li><a class="nav-link" href="/hospital/departments">Departments</a></li>
<li><a class="nav-link" href="/hospital/doctors">Doctors</a></li>
<li class="drop-down"><a class="nav-link" href="#">Reach Us</a>
<ul>
<li><a class="nav-link" href="/hospital/contact">Contact Us</a></li>
<li><a class="nav-link" href="#">Feedback</a></li>
<li><a class="nav-link" href="#">Blogs</a></li>
<li><a class="nav-link" href="#">Newsletters</a></li>
</ul>
</li>
</ul>
</nav><!-- .nav-menu -->
I am including the below javascript code in all my other web pages:
otherpages.jsp
<script>
$(function() {
$("#header").load("reusableheader.html");
});
</script>
The above code works fine i.e. on click of link on the menu item, its becomes the active link with the color assigned(in css) but when I scroll the page down, the activeness shifts from currently active link back to the "home" link.
What am I doing wrong here?
I think the problem is with removing the active class on the li element. How can you say $("a").parent("li").removeClass("active"); when you have got so many a elements with parent li element.
Instead, create a new for loop function which removes the element if the active class is found regardless of wherever it is in the list. And also add the logic on the click event of the li element, otherwise, it keeps looking for a URL match and changes it and would behave oddly if any path gets appended to the URL.
function removeClass() {
var listItems = $(".nav-menu > ul > li");
listItems.each(function (idx, li) {
$(li).removeClass("active");
});
}
I have a menu with a submenu
The html
<ul class="nav navbar-nav float-xs-right top-nav">
<li class="nav-item"><a class="nav-link" href="/our-work/">Our Work</a></li>
<li class="nav-item dropdown">
<a class="nav-link dropdown-toggle" href="/what-we-do/">What We Do</a>
<div class="dropdown-menu">
<a class="dropdown-item" href="/what-we-do/we-develop/">We Develop</a>
<a class="dropdown-item" href="/what-we-do/we-promote/">We Promote</a>
<a class="dropdown-item" href="/what-we-do/we-support/">We Support</a>
</div>
</li>
<li class="nav-item"><a class="nav-link" href="/contact/">Contact</a></li>
</ul>
I am adding bg color using jQuery
function activeMenu() {
var curr_url = window.location.pathname ;
var curr_menu = $("a[href$='" + curr_url + "']");
$(curr_menu).css("background", "#fff");
}
activeMenu();
It is changing bg color of a tag and if it is submenu than the submenu's bg color is changing. But I want to change the bg color of the parent menu not the submenu.
Is there a possible solution to select the parent menu using jQuery?
See this jQuery method: https://api.jquery.com/parent/
In your case, I think this is what you're looking for;
function activeMenu() {
var curr_url = window.location.pathname ;
var curr_menu = $("a[href$='" + curr_url + "']");
$(curr_menu).parent(".dropdown-toggle").css("background", "#fff");
}
activeMenu();
You can do this with vanilla javascript. Let's say your <ul> has an id of "menu":
const menu = document.getElementById("menu").children;
const list = [...menu]
const currentPage = list.filter(li => li.children[0].pathname == window.location.pathname)
currentPage[0].className = "active"
I have a nav bar, this has a links to pages, I want to save the current nav active when I clicked on that, this because I have a same menu in the other pages.
<ul>
<li id="nav1" class="navigation-item"><a href="#" >Nav 1</a></li>
<li class="navigation-item"><a href="#" >Nav 2</a></li>
<li class="navigation-item"><a href="#" >Nav 2</a></li>
<li class="navigation-item"><a href="#" >Nav 2</a></li>
</ul>
I try to get from $(this) and then use after the page is reload in order to add the class active.
$(document).ready(function () {
$('.navigation-item').on('click', function (e) {
var current = $( this );
console.log(current);
console.log(JSON.stringify(current));
localStorage.setItem('activeTab', current);
});
var activeTab = localStorage.getItem('activeTab');
if (activeTab) {
// activeTab.addClass('active');
// $('#nav1').parent().addClass('active');
console.log(activeTab);
$( "ul li:nth-child(2)" ).append( "<span> - 2nd!</span>" );
}
});
jsFiddle
Best Regards.
You need to store the index of the element:
$('.navigation-item').on('click', function (e) {
var current = $(this );
console.log(current);
console.log(JSON.stringify(current));
localStorage.setItem('activeTab', $('.navigation-item').index(current));
});
And then, use the index to get back the element:
var activeTab = localStorage.getItem('activeTab');
if (activeTab) {
activeTabEL = $('.navigation-item').eq(parseInt(activeTab));
activeTabEL.addClass('active');
// $('#nav1').parent().addClass('active');
console.log(activeTabEL);
$( "ul li.navigation-item" ).eq(parseInt(activeTab)).append( "<span> - 2nd!</span>" );
}
Example: https://jsfiddle.net/xmzb7hdk/7/
You don't need much JavaScript. You can use an HTML5 custom attribute to identify each element in the nav (data-nav-item):
<ul>
<li data-nav-item="nav-1" id="nav1" class="navigation-item"><a href="#" >Nav 1</a></li>
<li data-nav-item="nav-2" class="navigation-item"><a href="#" >Nav 2</a></li>
<li data-nav-item="nav-3" class="navigation-item"><a href="#" >Nav 2</a></li>
<li data-nav-item="nav-4" class="navigation-item"><a href="#" >Nav 2</a></li>
</ul>
Then it's just a simple 3 lines of JavaScript to set the value:
$(document).on("click", "[data-nav-item]", function(event) {
localStorage.setItem("activeTab", this.getAttribute("data-nav-item"));
});
After that, you can identify the active nav using:
var activeTab = $("[data-nav-item='" + localStorage.getItem("activeTab") + "']")
You can store the id Instead of storing the whole object.
It simplifies the use on retrieval.
Fiddle here
HTML:
<ul>
<li id="nav1" class="navigation-item"><a href="#" >Nav 1</a></li>
<li id="nav2" class="navigation-item"><a href="#" >Nav 2</a></li>
<li id="nav3" class="navigation-item"><a href="#" >Nav 3</a></li>
<li id="nav4" class="navigation-item"><a href="#" >Nav 4</a></li>
</ul>
Script:
$(document).ready(function () {
$('.navigation-item').on('click', function (e) {
var currentID = $(this).attr("id");
console.log(currentID+" = stored to localStorage");
localStorage.setItem('activeTab', currentID);
});
var activeTab = localStorage.getItem('activeTab');
if (activeTab!="") {
console.log(activeTab+" = retrieved form localStorage");
$("#"+activeTab ).append( "<span> - active!</span>" );
$("#"+activeTab ).addClass('active');
}
});
HTML :
<ul id="Mydatatabs" class="nav nav-tabs nav-justified">
<li class="active"><a data-toggle="tab" href="#details" id="TabDetailsLink">Personal
Details</a></li>
<li><a data-toggle="tab" href="#tab1" id="Tabtab1Link">tab1</a></li>
<li><a data-toggle="tab" href="#tab2" id="Tabtab2Link">tab2</a></li>
<li><a data-toggle="tab" href="#tab3" id="Tabtab3Link">tab3</a></li>
<li><a data-toggle="tab" href="#tab4" id="Tabtab4Link">tab4</a></li>
</ul>
JS :
$("#Mydatatabs li").click(function (e) {
e.preventDefault();
alert(1);
var MyID = $("#MyID").val();
alert(2);
switch ($(this).children(":first").attr("href")) {
alert(3);
case "#tab1":
});
Here I am unable to recieve the click event . Looks like I am making some mistake. Can someone show me the right way.
Because the JS is loaded first the DOM is not ready yet so it could not find the Mydatatabs list, you should put your code inside ready function :
$(function(){
//Your code here
})
Hope this helps.
$(function(){
$("#Mydatatabs li").click(function (e) {
e.preventDefault();
alert(1);
var MyID = $("#MyID").val();
alert(2);
});
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link href="https://netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://netdna.bootstrapcdn.com/bootstrap/3.0.0/js/bootstrap.min.js"></script>
<ul id="Mydatatabs" class="nav nav-tabs nav-justified">
<li class="active"><a data-toggle="tab" href="#details" id="TabDetailsLink">Personal
Details</a></li>
<li><a data-toggle="tab" href="#tab1" id="Tabtab1Link">tab1</a></li>
<li><a data-toggle="tab" href="#tab2" id="Tabtab2Link">tab2</a></li>
<li><a data-toggle="tab" href="#tab3" id="Tabtab3Link">tab3</a></li>
<li><a data-toggle="tab" href="#tab4" id="Tabtab4Link">tab4</a></li>
</ul>
So, first you have to put your jquery code inside a document ready statement. See the example:
$(document).ready(function(){
//... code
});
This is to be certain that the element to which the .click() event is bound has been created when the function executes.
For further explanation, look this response: Why should $.click() be enclosed within $(document).ready()?
And is not missing any end curly braces in this click event? In between switch case and end of the function?