How to change element's class to active? - javascript

I'm using a bootstrap template for a side navbar as a partial in EJS which is then included on all pages that use it. Is was taken from their Dashboard template. The HTML is
<nav class="col-sm-3 col-md-2 hidden-xs-down bg-faded sidebar">
<ul class="nav nav-pills flex-column">
<li class="nav-item">
<a class="nav-link active" href="/profile">Overview</a>
</li>
<li class="nav-item">
<a class="nav-link" href="/accountdetails">Account Details</a>
</li>
<li class="nav-item">
<a class="nav-link" href="/admin">Admin</a>
</li>
<li class="nav-item">
<a class="nav-link" href="/transactions">Transactions</a>
</li>
<li class="nav-item">
<a class="nav-link" href="/contract">Contract</a>
</li>
</ul>
</nav>
Whichever link has the active class has particular styling with darker blue in the background. I now want to change this programatically when navigating to the different links.
They're all going to different pages so I could just change there the issue is that I'm including the whole sidebar code as an EJS partial so that wouldn't work. I also tried this answer but it didn't work (flashes the active styling but disappears - probably because it is routing to another page?).
There are plenty of questions here about changing an HTML element programatically but they usually use document.getElementById which seems like too much work (giving each an ID, checking all, etc). Is there a quicker / correct way of doing this?

You could do the following:
Set a click event on .nav-item, to add .active class.
Remove .active class from any other sibling element.
$('.nav-item').on('click', function() {
$(this).addClass('active').siblings('li').removeClass('active');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<nav class="col-sm-3 col-md-2 hidden-xs-down bg-faded sidebar">
<ul class="nav nav-pills flex-column">
<li class="nav-item active">
<a class="nav-link" href="#">Overview</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">Account Details</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">Admin</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">Transactions</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">Contract</a>
</li>
</ul>
</nav>

Some people answering are a bit confused, thinking you are staying on the same page, and changing the class of your <a> tags. But I think your clicks on these navigate to new pages, and you want the appropriate <a> to have class active when the page loads.
This might help:
<script>
var path = location.pathname; // ex: '/profile';
var activeItem = document.querySelector("a[href='" + path + "']");
activeItem.class += ' active';
</script>
And of course with jquery it's even easier:
$(function() {
var path = location.pathname;
$("a[href='" + path + "']").addClass('active');
})

This is a code for helping you.
<nav class="col-sm-3 col-md-2 hidden-xs-down bg-faded sidebar">
<ul class="nav nav-pills flex-column">
<li class="nav-item">
<a class="nav-link active" href="#">Overview</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">Account Details</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">Admin</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">Transactions</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">Contract</a>
</li>
</ul>
</nav>
<script type="text/javascript">
$(function () {
$(".nav-item").click(function () {
$(".nav-item").each(function () {
$(this).find("a").removeClass("active");
});
$(this).find("a").addClass("active");
});
});
</script>

If your using EJS you can probably do something like the following
<a class="nav-link<% if (page_name === 'profile') { %> active<% } %>" href="/profile">Overview</a>
This is untested but should get you going on the right path. Just do a if statement using EJS's syntax to check if you are on the correct page and add the word active.

Related

How can I go to href on tag with hide attribute value?

How can I go to href on tag with hide attribute value?
here is my navigation bar
$(function() {
$('#p10').hide();
$('#p11').hide();
$('#p12').hide();
$('#p13').hide();
$('#p14').hide();
$('#p15').hide();
$('#p16').hide();
$('#p17').hide();
$('#p18').hide();
$('#p19').hide();
$('#p20').hide();
$('#p21').hide();
$('#hideshow').click(function() {
$('#p10').toggle();
$('#p11').toggle();
$('#p12').toggle();
$('#p13').toggle();
$('#p14').toggle();
$('#p15').toggle();
$('#p16').toggle();
$('#p17').toggle();
$('#p18').toggle();
$('#p19').toggle();
$('#p20').toggle();
$('#p21').toggle();
});
$('#navbarNav').click(function() {
console.log($(this));
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="collapse navbar-collapse" id="navbarNav">
<ul class="navbar-nav">
<li class="nav-item active">
<a class="nav-link " href="#section2">Home</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#p1">Subway congestion prediction app</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#p2">Image classification</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#p3">Community site</a>
</li>
...
<li class="nav-item">
<a class="nav-link" href="#p17">Assembly</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#p18">Data structure</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#p19">Concave</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#p20">Contact</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#section5">Contact</a>
</li>
</ul>
</div>
When loading the page here, p10 to p21 are hidden.
In this situation, if you click from 10 to 21 of the navigation bar, it is hidden and you cannot move to href.
How can I remove the hide attribute when clicking p10 to p21 of the navigation bar (click the #hideshow button at the time of the hide attribute) and move to p10 to p21?
<button type="button" class="btn btn-dark btn-lg " style="font-size:3rem; margin-bottom:100px; background-color:#3e454e" id="hideshow">Want to see more?</button>
#showhide button is between #p9 #p10
The jquery-selector is used in this way:
$('#<id>').hide();
-> the <id> (after the #) must be the id of the element. In your HTML it is the given href.
In your given code the #hideshow button is missing.
You try to select with jQuery IDs (10 - 21) but the HTML doesn't contain these IDs. Furthermore: The click event listener is assigned to the button #hideshow which doesn't exist.
If you define the IDs and add the button #hideshow it works:
$(function() {
$('#p10').hide();
$('#p11').hide();
$('#p12').hide();
$('#p13').hide();
$('#p14').hide();
$('#p15').hide();
$('#p16').hide();
$('#p17').hide();
$('#p18').hide();
$('#p19').hide();
$('#p20').hide();
$('#p21').hide();
$('#hideshow').click(function() {
$('#p10').toggle();
$('#p11').toggle();
$('#p12').toggle();
$('#p13').toggle();
$('#p14').toggle();
$('#p15').toggle();
$('#p16').toggle();
$('#p17').toggle();
$('#p18').toggle();
$('#p19').toggle();
$('#p20').toggle();
$('#p21').toggle();
});
$('#navbarNav').click(function() {
console.log($(this));
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="collapse navbar-collapse" id="navbarNav">
<ul class="navbar-nav">
<li class="nav-item active">
<a class="nav-link " href="#section2">Home</a>
</li>
<li id="1p17" class="nav-item">
<a class="nav-link" href="#p1">Subway congestion prediction app</a>
</li>
<li id="p2" class="nav-item">
<a class="nav-link" href="#p2">Image classification</a>
</li>
<li id="p3" class="nav-item">
<a class="nav-link" href="#p3">Community site</a>
</li>
...
<button type="button" id="hideshow">Want to see more?</button>
...
<li id="p17" class="nav-item">
<a class="nav-link" href="#p17">Assembly</a>
</li>
<li id="p18" class="nav-item">
<a class="nav-link" href="#p18">Data structure</a>
</li>
<li id="p19" class="nav-item">
<a class="nav-link" href="#p19">Concave</a>
</li>
<li id="p20" class="nav-item">
<a class="nav-link" href="#p20">Contract</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#section5">Contact</a>
</li>
</ul>
</div>

Reloading page when fetching new tab item in bootstrap card

I have this code in javascript that allows me to visit a page with a hashbang on it to visit a tab
// Javascript to enable link to tab
var url = document.location.toString();
if (url.match('#')) {
$('.nav-tabs a[href="#' + url.split('#')[1] + '"]').tab('show');
}
// Change hash for page-reload
$('.nav-tabs a').on('shown.bs.tab', function (e) {
window.location.hash = e.target.hash;
})
This is an example link http://localhost/centosapp/info/configure#description
I am showing a tab on click using
$('#bologna-list a').on('click', function (e) {
e.preventDefault()
$(this).tab('show')
});
this is the html
<div class="card">
<div class="card-header">
<ul class="nav nav-tabs card-header-tabs" id="bologna-list" role="tablist">
<li class="nav-item">
<a class="nav-link active" href="<?php echo base_url('info/configure'); ?>#description" role="link" aria-controls="description" aria-selected="true">Devices</a>
</li>
<li class="nav-item">
<a class="nav-link" href="<?php echo base_url('info/configure'); ?>#history" role="link" aria-controls="history" aria-selected="false">Add Asset</a>
</li>
<li class="nav-item">
<a class="nav-link" href="<?php echo base_url('info/configure'); ?>#deals" role="link" aria-controls="deals" aria-selected="false">My Assets</a>
</li>
</ul>
</div>
<div class="card-body">
<div class="tab-content mt-3">
<div class="tab-pane active" id="description" role="tabpanel">
...items are shown here
</div>
</div>
I want to be able to reload page so that to get new content from server when i click on a tab.How can i reload and show the tab clicked on bootstrap?
Solved it this way using a html data-* tag.
<div class="card-header">
<ul class="nav nav-tabs card-header-tabs" id="bologna-list" role="tablist">
<li class="nav-item">
<a class="nav-link active" href="#description" data-link="http://localhost/centosapp/info/configure#description" role="link" aria-controls="description" aria-selected="true">Devices</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#history" data-link="http://localhost/centosapp/info/configure#history" role="link" aria-controls="history" aria-selected="false">Add Asset</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#deals" data-link="http://localhost/centosapp/info/configure#deals" role="link" aria-controls="deals" aria-selected="false">My Assets</a>
</li>
</ul>
</div>
and js
$('#bologna-list a').on('click', function (e) {
e.preventDefault()
$(this).tab('show');
var links = $(this).attr("data-link");
window.location.href = links;
});
Works but a solution inside bootstrap would have worked better.

Jquery function to set active nav tab using url is selecting more than it should

I have a Jquery function which I use to set the 'active' class on my nav anchors, it uses the URL to do so. The function works for the most part but the problem is that when tab 1 is active it's also setting tabs 10, 11 and 12 as active too.
The code below is what I'm using and it's correctly outputting the page in the console.log, it also works as it should for all other links except Item 1 as seen in the screenshot.
$(function(){
var url = window.location.href;
var page = url.substr(url.lastIndexOf('/')+1 );
$('.nav-item a[href*="'+page+'"]').addClass('active');
console.log(page);
});
The nav is fairly large so I'll share a condensed version, just keep in mind that middle ul actually contains a total of 12 Items and each item shares the url
article.php?contentID=
After the = comes the item number from 1 to 12.
<nav class="navbar navbar-expand-lg navbar-dark bg-primary">
<ul class="navbar-nav" >
<li><a class="navbar-brand" href="articles.php">Twist</a></li>
</ul>
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarSupportedContent">
<ul class="navbar-nav">
<li class="nav-item">
<a class="nav-link " href="article.php?contentID=1">Item 1</a>
</li>
</ul>
<ul class="navbar-nav ml-auto">
<li class="nav-item">
<a class="nav-link" href="commentary.php">Commentary</a>
</li>
<li>
<a id="logLink" class="nav-link" href="logout.php">Log out</a>
</li>
</ul>
</div>
</nav>
Any help would be appreciated and I'm pretty sure it's something obvious but I'm just not seeing it.
Thanks in advance.
Twist
You are using the 'attribute contains' selector which selects any that have the given sub-string "article.php?contentID=1".
So this matches all of the following
"article.php?contentID=1",
"article.php?contentID=10",
"article.php?contentID=11",
"article.php?contentID=12", and
"some_article.php?contentID=1whatever"
Just remove the *
'.nav-item a[href="'+page+'"]'
Interesting question... The key was to have href$="='+page+'" so that the statement which adds the active class becomes:
$('.nav-item a[href$="=' + page + '"]').addClass('active');
Working snippet below - change the hardcoded value of page to test yourself:
$(function() {
var url = window.location.href;
var page = 1 //url.substr(url.lastIndexOf('/')+1 );
$('.nav-item a[href$="=' + page + '"]').addClass('active');
console.log('looking for page#:', page);
});
a.nav-link.active {
background: lightgreen;
}
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<div class="container">
<h2>Nav</h2>
<p>Basic horizontal menu:</p>
<ul class="nav">
<li class="nav-item">
<a class="nav-link" href="#article.php?contentID=1">Link</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#article.php?contentID=2">Link</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#article.php?contentID=10">Link</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#article.php?contentID=11">Link</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#article.php?contentID=21">Link</a>
</li>
<li class="nav-item">
<a class="nav-link disabled" href="#">Disabled</a>
</li>
</ul>
</div>

how do i set navbar item to be active by default before the user clicks a nav link?

i have a site i'm working on and i have the nav-items set so that when you click on a nav-link it changes the active class to the link that you clicked.
with this said how do I set a certain link to be active by default in the navbar?
Code:
$(".nav-item a").on("click", function() {
$(".nav-item a").removeClass("active");
$(this).addClass("active");
});
.nav-item a.active {
color: red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<nav class="navbar navbar-expand-lg navbar-light bg-light fixed-top">
<div class="collapse navbar-collapse" id="navbarResponsive">
<ul class="navbar-nav ml-auto">
<li class="nav-item">
<a class="nav-link" href="#">Home
<span class="sr-only">(current)</span>
</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">About</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">Services</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">Contact</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">Shop</a>
</li>
</ul>
</div>
</nav>
I am still quite new to javascript so any help will be great (even if it doesnt work)
Edit: It appears i didnt add enough detail, i'm sorry.
I would like to have the Home nav-link stay active until the user clicks another nav-link to another part of the page (im thinking about on scroll over different parts of the site but thats a different question altogether). with this in mind i want to have the site functionality to stay the same but have the default active link changed when a different one is clicked.
Just add active class to nav-link
$(".nav-item a").on("click", function() {
$(".nav-item a").removeClass("active");
$(this).addClass("active");
});
.nav-item a.active {
color: red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<nav class="navbar navbar-expand-lg navbar-light bg-light fixed-top">
<div class="collapse navbar-collapse" id="navbarResponsive">
<ul class="navbar-nav ml-auto">
<li class="nav-item">
<a class="nav-link" href="#">Home
<span class="sr-only">(current)</span>
</a>
</li>
<li class="nav-item">
<a class="nav-link active" href="#">About</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">Services</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">Contact</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">Shop</a>
</li>
</ul>
</div>
</nav>
your code is about CLICK action and you dont want it . you should use
$('.nav-item a').addClass("active");
in out of function click body:
<script
src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js">
</script>
<nav class="navbar navbar-expand-lg navbar-light bg-light fixed-top">
<div class="collapse navbar-collapse" id="navbarResponsive">
<ul class="navbar-nav ml-auto">
<li class="nav-item">
<a class="nav-link" href="#">Home
<span class="sr-only">(current)</span>
</a>
</li>
<li class="nav-item">
<a class="nav-link active" href="#">About</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">Services</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">Contact</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">Shop</a>
</li>
</ul>
</div>
</nav>
CSS:
.nav-item a.active
{
color: red;
}
JAVASCIPT:
<script>
$('.nav-item a').addClass("active");
</script>

Storing active class in local storage when using bootstrap 4 tabs

I am having some trouble with the tab list below:
<ul class="nav nav-tabs" data-tabs="tabs" role="tablist">
<li class="nav-item">
<a class="nav-link active" href="{$PageUrl}" role="tab">View</a>
</li>
<li class="nav-item">
<a class="nav-link" href="{$PageUrl}?action=edit" role="tab">Edit</a>
</li>
<li class="nav-item">
<a class="nav-link" href="{$PageUrl}?action=diff" role="tab">History</a>
</li>
<li class="nav-item">
<a class="nav-link" href="{$PageUrl}?action=print" role="tab">Print</a>
</li>
<li class="nav-item">
<a class="nav-link" href="{$PageUrl}?action=attr" role="tab">Attributes</a>
</li>
<li class="nav-item dropdown">
<a class="nav-link dropdown-toggle" href="#" id="dropdown2" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">Dropdown</a>
<div class="dropdown-menu" aria-labelledby="dropdown2">
<a class="dropdown-item" data-toggle="tab" href="#fat2" role="tab">#fat</a>
<a class="dropdown-item" data-toggle="tab" href="#mdo2" role="tab">#mdo</a>
</div>
</li>
</ul>
Everything displays fine but this differs from how a lot of people implement tabs. Most examples i see have 'tab-content' and that shows the content for each tab. In my case i am using tabs to link alternate pages all together. This is where my issue comes in, When clicking on 'Edit' tab it does indeed load the edit page but with the active class or the 'View' tab still active. I cannot get the active class to switch between the tabs. I think this is because the page is reloading therefore eliminating the active data and setting it to default. How can I get around this and have it show the correct active tab after the newly selected page loads? Thanks for any help!
Edit:
Previously I was trying to use this at the bottom of my body with no luck:
$(function(){
var current = location.pathname;
$('#nav 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');
}
})
})
Here is a possible solution:
<ul class="nav nav-tabs" data-tabs="tabs" role="tablist">
<li class="nav-item">
<a class="default nav-link" href="{$PageUrl}" role="tab">View</a>
</li>
<li class="nav-item">
<a class="edit nav-link" href="{$PageUrl}?action=edit" role="tab">Edit</a>
</li>
<li class="nav-item">
<a class="diff nav-link" href="{$PageUrl}?action=diff" role="tab">History</a>
</li>
<li class="nav-item">
<a class="print nav-link" href="{$PageUrl}?action=print" role="tab">Print</a>
</li>
<li class="nav-item">
<a class="attr nav-link" href="{$PageUrl}?action=attr" role="tab">Attributes</a>
</li>
<li class="nav-item dropdown">
<a class="nav-link dropdown-toggle" href="#" id="dropdown2" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">Dropdown</a>
<div class="dropdown-menu" aria-labelledby="dropdown2">
<a class="dropdown-item" data-toggle="tab" href="#fat2" role="tab">#fat</a>
<a class="dropdown-item" data-toggle="tab" href="#mdo2" role="tab">#mdo</a>
</div>
</li>
</ul>
<script>
$(function() {
var action = (location.search.match(/(\^?|&)action=(.*?)($|&)/i) || [])[2]
if(action) {
$('a.nav-link.'+action).addClass('active')
} else {
$('a.nav-link.default').addClass('active')
}
})
</script>
Does not add active class to any of the tabs by default.
All tab links have their action as class, to make it easy
On load it thecks the query in the window's address, and sets the active class accordingly

Categories