I have a navigation bar which is being loaded into each of my pages using a JQUERY '.load'
However, the active link will be different for each page. Is there a way i can override the active link from the page that has loaded the Navbar?
Any help would be much appreciated :)
Below is an example of the Navbar links
<nav class="navbar navbar-toggleable-sm">
<button type="button" data-toggle="collapse" data-target="#mai-navbar-collapse" aria-controls="#mai-navbar-collapse" aria-expanded="false" aria-label="Toggle navigation" class="navbar-toggler hidden-md-up collapsed">
<div class="icon-bar"><span></span><span></span><span></span></div>
</button>
<div id="mai-navbar-collapse" class="navbar-collapse collapse mai-nav-tabs">
<ul class="nav navbar-nav">
<li class="nav-item parent open"><span class="icon s7-home"></span><span>Training</span>
<ul class="mai-nav-tabs-sub mai-sub-nav nav">
<li class="nav-item"><span class="icon s7-monitor"></span><span class="name">Written Guides</span></li>
<li class="nav-item"><span class="icon s7-video"></span><span class="name">Video Guides</span></li>
</ul>
</li>
<li class="nav-item parent"><span class="icon s7-users"></span><span>Support</span>
<ul class="mai-nav-tabs-sub mai-sub-nav nav">
<li class="nav-item"><span class="icon s7-id"></span><span class="name">Signing Up</span></li>
<li class="nav-item"><span class="icon s7-search"></span><span class="name">FAQS</span></li>
</ul>
</li>
</ul>
</div>
</nav>
JQUERY
<script>
$(function(){
$("#nav-placeholder").load("../../navbarL1.aspx");
$('.dropdown-toggle').dropdown()
});
</script>
Try to run this code. I hope it will work.
function getURL() {
// get the whole URL
var currentURL = window.location.href;
// get the file name after = sign
var activeTemplate = currentURL.substr(currentURL.indexOf("=") + 1);
// add active class to url
$('a[href="/teams/Training/sitepages/training/'+ activeTemplate +'"]').addClass('active');
})
You can use .toggleClass() with a toggle state value as the second param. At that point it's a matter of figuring out how to compare the href with the current URL. You can use location.pathname, but you may want to get the href using getAttribute so it doesn't include the hostname. Otherwise you could also use this.href === location.href. It is important, however, to include this code in a callback to .load() so you don't encounter a race condition.
$(function(){
$("#nav-placeholder").load("../../navbarL1.aspx", function(){
$('.mai-sub-nav li a').each(function(){
$(this).toggleClass('active', this.getAttribute('href') === location.pathname);
})
});
$('.dropdown-toggle').dropdown()
});
You have to follow this kind of technique to achieve that
Here is my nav bar
<ul class="nav navbar-nav">
<li class="active" data-pos="1">
Home
</li>
<li data-pos="2">
About Egypt
</li>
<li data-pos="3">
Accomodation
</li>
<li data-pos="4">
Nile Cruises
`enter code here`
</li>
<li data-pos="5">
Tour Packages
</li>
<li class="dropdown" data-pos="6">
<a href="javascript:void(0)" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true">FAQ</span>
</a>
<ul class="dropdown-menu">
<li>Thing to do</li>
<li><a href="{{ route('site.page',['travel-tip']) }}">How to travel</a</li>
<li>Travel Help</li>
</ul>
</li>
</ul>
Here is my script logic in which i get full url and spilt on the base of '/' seprator
to get an array and check second last and last segment
var url = window.location.href;
var urlArray = url.split("/");
var lastUrlString = urlArray[urlArray.length-1];
var pageName = urlArray[urlArray.length-2];
After getting last and second last segment i loop through navbar li elements and add or remove class on the basis of page names
var navLinks = $('ul.nav li');
navLinks.each(function(index,element){
var position = $(element).data('pos');
if(lastUrlString == 'home')
{
if($(element).data("pos") == 1)
{
if(!$(element).hasClass("active") )
{
$(element).addClass('active');
}
}
else
{
$(element).removeClass("active");
}
}
else if(lastUrlString == 'about')
{
if($(element).data("pos") == 2)
{
if(!$(element).hasClass("active") )
{
$(element).addClass('active');
}
}
else
{
$(element).removeClass("active");
}
}
else if(lastUrlString == 'page' && pageName == 'accomodation')
{
if($(element).data("pos") == 3)
{
if(!$(element).hasClass("active") )
{
$(element).addClass('active');
}
}
else
{
$(element).removeClass("active");
}
}
else if(lastUrlString == 'page' && pageName == 'nile_curises')
{
if($(element).data("pos") == 4)
{
if(!$(element).hasClass("active") )
{
$(element).addClass('active');
}
}
else
{
$(element).removeClass("active");
}
}
else if(lastUrlString == 'page' && pageName == 'tour_packages')
{
if($(element).data("pos") == 5)
{
if(!$(element).hasClass("active") )
{
$(element).addClass('active');
}
}
else
{
$(element).removeClass("active");
}
}
else
{
$(element).removeClass("active");
}
});
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 want to get the user url on my site. I want to show if the user url is the root domain, add active class to the id home-item-menu. If not, don't do nothing.
I was using window.location.href and window.location.host but didn't work.
For the rest of section's I was using indexof (and the string that the url has), but because the root domain don't have any string I don't know how to do it.
<nav class="cl-effect-5">
<li class="nav-item" id="home-item-menu">
<a class="nav-link menu-rucab js-scroll-trigger" href="#home"><span data-hover="HOME">HOME</span></a>
</li>
</nav>
<nav class="cl-effect-5">
<li class="nav-item" id="rucab-item-menu">
<a class="nav-link menu-rucab js-scroll-trigger" href="#rucab"><span data-hover="RUCAB">RUCAB</span></a>
</li>
</nav>
<nav class="cl-effect-5">
<li class="nav-item" id="inscripciones-item-menu">
<a class="nav-link menu-rucab js-scroll-trigger" href="#inscripciones"><span data-hover="INSCRIPCIONES">INSCRIPCIONES</span></a>
</li>
</nav>
<nav class="cl-effect-5">
<li class="nav-item" id="habitaciones-item-menu">
<a class="nav-link menu-rucab js-scroll-trigger" href="#habitaciones"><span data-hover="HABITACIONES">HABITACIONES</span></a>
</li>
</nav>
<nav class="cl-effect-5">
<li class="nav-item" id="staff-item-menu">
<a class="nav-link menu-rucab js-scroll-trigger" href="#staff"><span data-hover="STAFF">STAFF</span></a>
</li>
</nav>
<nav class="cl-effect-5">
<li class="nav-item" id="blog-item-menu">
<a class="nav-link menu-rucab js-scroll-trigger" href="#contact"><span data-hover="BLOG">BLOG</span></a>
</li>
</nav>
<nav class="cl-effect-5">
<li class="nav-item" id="contacto-item-menu">
<a class="nav-link menu-rucab js-scroll-trigger" href="#contacto"><span data-hover="CONTACTO">CONTACTO</span></a>
</li>
</nav>
JQuery/Javascript
$( document ).ready(
function() {
var url = window.location.href;
var host = window.location.host;
if(url.indexOf('http://' + host + '/') != -1) {
document.getElementById("home-item-menu").classList.add("active");
}
if (document.URL.indexOf("habitaciones") > -1)
{
document.getElementById("habitaciones-item-menu").classList.add("active");
} else if (document.URL.indexOf("contacto") > -1) {
document.getElementById("contacto-item-menu").classList.add("active");
} else if (document.URL.indexOf("rucab") > -1) {
document.getElementById("rucab-item-menu").classList.add("active");
} else if (document.URL.indexOf("inscripciones") > -1) {
document.getElementById("inscripciones-item-menu").classList.add("active");
} else if (document.URL.indexOf("staff") > -1) {
document.getElementById("staff-item-menu").classList.add("active");
} else if (document.URL.indexOf("blog") > -1) {
document.getElementById("blog-item-menu").classList.add("active");
}
});
You can use the condition window.location.pathname === '/':
if(window.location.pathname === '/') {
document.getElementById("home-item-menu").classList.add("active");
}
Hi #Pedro Corchero Murga you can use javascript sessions to achieve this set the text of the nav item to javascript session and get that session on load function and check the conditions if you don't familiar with javascript sessions you can see this link : https://www.w3schools.com/jsref/prop_win_sessionstorage.asp
First of all, define how you want to tell your application if this is my root URL, which one way to achieve this is as follows;
function isAtRoot () {
// Let's say you're currently at 'https://myhome.domain/',
// and this is your root.
var href = window.location.href,
urlWithoutQueryString = href.split('?')[0],
host = window.location.host,
regexp = new RegExp("^https?://" + host + "/?$", "i");
return !!urlWithoutQueryString.match(regexp);
}
Or you can also use window.location.pathname for this.
Then, run your javascript like above as follows,
if (isAtRoot()) {
document.getElementById("home-item-menu").classList.add("active");
}
However, I'd suggest that you have a list of paths for your site and give it an alias or name to it. Then, run something like isAtRoot against it instead, which will have more trust-able precision for future references.
I need to enable and disable tab based select results.Below the code I am working.If device B status is On-Line I need to disable Device-V tab.How to implement this using JavaScript/jQuery.
jQuery:
if(result.includes("On-line") ){
$(selected_device_id).html("");
//Need to implement disable function here
$(selected_device_id).append(result+" ✅");
HTML File:
<div class="panel">
<br>
<ul class="nav nav-pills nav-tabs">
<li class="active">
<a
data-toggle="tab"
href="#Device-B"
onclick="document.getElementById('Object').value = '';
document.getElementById('first_i').value = '';
document.getElementById('second_i').value = '';
document.getElementById('third_i').value = '';">
<i>
<b>Device B</b>
</i>
</a>
</li>
<li>
<a
data-toggle="tab"
href="#Device-V"
onclick="document.getElementById('tr181_object').value = '';
document.getElementById('first_i').value = '';
document.getElementById('second_i').value = '';
document.getElementById('third_i').value = '';">
<i>
<b>Video</b>
</i>
</a>
</li>
</div>
$(document).ready(function()
{
var switch_ch = 0 ;
$(".linktoggle").on("click",function(){
i = $(this).index(".linktoggle") ;
if( $(".linktoggle").attr("href") === "#Device-B")
{
if( switch_ch === 0 )
{
$(".linktoggle:eq(0)").show();
$("li:eq(0)").show();
$(".linktoggle:eq(1)").hide();
$("li:eq(1)").hide();
switch_ch = 1 ;
}
else
{
$(".linktoggle:eq(1)").show();
$("li:eq(1)").show();
switch_ch = 0 ;
}
}
if( $(".linktoggle").attr("href") === "#Device-V")
{
$(".linktoggle:eq("+i +")").hide();
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="panel">
<br>
<ul class="nav nav-pills nav-tabs">
<li class="active">
<a
class="linktoggle"
href="#Device-B" >
<i>
<b>Device B</b>
</i>
</a>
</li>
<li>
<a
class="linktoggle"
data-toggle="tab"
href="#Device-V"
>
<i>
<b>Video</b>
</i>
</a>
</li>
</div>
please take a look at the image, here I am tried to do
If I click on "Fan Panels" The other two menus will be visible. Which is currently working fine. and here three menus will be visible.
If I click on "Entertain Art" menu the "Score Art" and "Fan Panels" need to be hidden, but the "Entertain Art" still need to show.
If I click on "Score Art" the "Fan Panels" and "Entertain Art" menu need to hidden, but the "Score Art" still need to show.
If you think about the code here it is :
{{#each categories}}
<li class="nav-list__item">
<a class="nav-list__item-link" href="{{url}}" title="{{name}}">{{name}}</a>
</li>
{/each}}
The website is under preview mode
Tts Big-commerce so menu displaying frontend with the dynamic syntax I think we can do it with javascript and jquery to find text and hide them what you suggest?
FOR EXAMPLE CODE:
<ul id="primeNav" class="nav-list nav-list--prime">
<li class="nav-list__item">
<a class="nav-list__item-link" href="#" title="Fan Panels">Fan Panels</a>
<li class="nav-list__item">
<a class="nav-list__item-link" href="#" title="Entertain Art">Entertain Art</a>
<li class="nav-list__item">
<a class="nav-list__item-link" href="#" title="Score Art">Score Art</a>
</ul>
Thanks in Advance
You can try this code alternatively -
Edit 3 -
Here's the newly updated code
/* Conditional Page Options */
var url = window.location.href;
var url = url.replace(/\//g, '');
var sub_url = location.protocol + location.host;
var page = url.replace(sub_url, '');
/* conditional click actions */
if (page == "entertain-art") {
$("#primeNav .nav-list__item").hide();
$("#primeNav .nav-list__item:nth-child(2)").show(); // revised
} else if (page == "score-art") {
$("#primeNav .nav-list__item").hide();
$("#primeNav .nav-list__item:nth-child(3)").show(); // revised
} else {
$("#primeNav .nav-list__item-link").on('click', function() {
var index = $(".nav-list__item-link").index(this);
if (index == 0) {
$("#primeNav .nav-list__item").show();
} else {
$("#primeNav .nav-list__item").hide();
$(this).parent().show();
}
});
}
$("#primeNav .nav-list__item:nth-child(4)").show(); // revised
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul id="primeNav" class="nav-list nav-list--prime">
<li class="nav-list__item">
<a class="nav-list__item-link" href="#" title="Fan Panels">Fan Panels</a>
</li>
<li class="nav-list__item">
<a class="nav-list__item-link" href="#" title="Entertain Art">Entertain Art</a>
</li>
<li class="nav-list__item">
<a class="nav-list__item-link" href="#" title="Score Art">Score Art</a>
</li>
</ul>
try it.
**UPDATE* : without adding new class name
//Without any new class name
$("#primeNav li").click(function(){
if($(this).text().trim()!="Fan Panels") //For Point 1, if click on FanPanel then show all
{
$("#primeNav li").hide(); // hide all item
$(this).show(); // Show item which is clicked
}
})
//Added **menu** as classname to all anchor tag, also added another unique class name to handle individual.
//Older try
$(".menu2").click(function(){
console.log($(this).text());
if($(this).hasClass("menuFan")==false) //For Point 1, if click on FanPanel then show all
{
$(".menu").hide(); // hide all item
$(this).show(); // Show item which is clicked
}
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul id="primeNav" class="nav-list nav-list--prime">
<li class="nav-list__item">
<a class="nav-list__item-link menu menuFan" href="#" title="Fan Panels">Fan Panels</a>
<li class="nav-list__item">
<a class="nav-list__item-link menu menuEnt" href="#" title="Entertain Art">Entertain Art</a>
<li class="nav-list__item">
<a class="nav-list__item-link menu menuScore" href="#" title="Score Art">Score Art</a>
</ul>
I have a site (www.mhk.me). In this site(html) navigation bar focus is change when the page change.
But now I am going make a back-end of this site (Converting on php).
I made a file name(Navigation.php) and then I include with all file.
The problem is that in php site the focus in this is always on HOME not change to other navigation when I change the page.
<div class="navbar-collapse nav-main-collapse collapse">
<div class="container">
<nav class="nav-main mega-menu">
<ul class="nav nav-pills nav-main" id="mainMenu">
<li class="active">
<a class="dropdown-toggle" href="index.html">
Home
</a>
</li>
<li>
<a class="dropdown-toggle" href="about.html">
About Me
</a>
</li>
<li>
<a class="dropdown-toggle" href="services.html">
Services
</a>
</li>
<li>
<a class="dropdown-toggle" href="portfolio.html">
Portfolio
</a>
</li>
<li>
<a class="dropdown-toggle" href="http://demo.mhk.me">
My Templates
</a>
</li>
<li>
<a class="dropdown-toggle" href="contact.html">
Contact
</a>
</li>
</ul>
</nav>
</div>
</div>
You will need a script that can compare the url ,so that you can assign .active class to the menu.
$(function() {
var pgurl = window.location.href.substr(window.location.href
.lastIndexOf("/")+1);
$(".nav-main li a").each(function(){
if($(this).attr("href") == pgurl || $(this).attr("href") == '' ){
$(this).parent().addClass("active");}
if($(this).attr("href") == 'index.php' && pgurl == '' ) {
$(this).parent().addClass("active");
}
})
});
Math3w, Your code need to be slightly changed.
$(function () {
var pgurl = window.location.href.substr(window.location.href.lastIndexOf("/") + 1);
$(".nav-main li a").each(function () {
if ($(this).attr("href") == pgurl) {
$(this).parent().addClass("active");
}
if ((($(this).attr("href") == 'index.php')||($(this).attr("href") == '')) && (pgurl == '')) {
$(this).parent().addClass("active");
}
})
});
<html>
<head>
<style>ul{
list-style:none;
}
li{
cursor:pointer;
float:left;
padding:10px;
background-color:grey;
border-radius:5px;
margin:10px;
}
ul>.active{
background-color:green;
}
</style>
</head>
<body><nav>
<ul class="nav-main">
<li>Home</li>
<li>About</li>
<li>Contact</li>
</ul>
</nav>
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
<script>
$(function () {
var pgurl = window.location.href.substr(window.location.href.lastIndexOf("/") + 1);
$(".nav-main li a").each(function () {
if ($(this).attr("href") == pgurl) {
$(this).parent().addClass("active");
}
if ((($(this).attr("href") == 'index.php')||($(this).attr("href") == '')) && (pgurl == '')) {
$(this).parent().addClass("active");
}
})
});
</script>
</body>
</html>
Save the above code as index.php or about.php or contact.php and check the output.