jQuery Highlight Nav Item on Load - javascript

I'm new to HTML/CSS/JS and I'm doing some testing and fiddling around with stuff and decided to highlight a nav element when on that page. I decided to use jQuery for this because from what I read it was the easiest solution. It's worked great so far, but my issue is that it doesn't highlight the main "chat" page on load because it's just the url, without the /index.html. I'd appreciate any help on how to get it to add the active class to the index.html element on load.
HTML:
<aside>
<nav>
<ul>
<li>Chat</li>
<li>Friends</li>
<li>Settings</li>
</ul>
</nav>
</aside>
JQuery:
jQuery(function($) {
var path = window.location.href;
$('aside nav ul li a').each(function() {
if (this.href === path) {
$(this).addClass('active');
}
});
SCSS:
.active {
border-right: 10px solid $accent-two;
}

First, your pathname includes the entire URL, so it will never match with href in your a tag. You need to get just the page name.
Next, you should check for the href attribute of the a tag and not the href itself.
The example below uses a dummy link to aid as a demo. I had to add in the href in JS because of the snippet.
jQuery(function($) {
var path = window.location.pathname;
var page = path.split("/").pop();
//
// The line below is for demo on stackoverflow purposes
$("#forDemoOnStackPurpose").attr("href", page);
//
$('aside nav ul li a').each(function() {
if ($(this).attr("href") === page) {
$(this).addClass('active');
}
});
});
.active {
border-right: 10px solid red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<aside>
<nav>
<ul>
<li><a id="forDemoOnStackPurpose" href="">This test page</a></li>
<li>Chat</li>
<li>Friends</li>
<li>Settings</li>
</ul>
</nav>
</aside>

I give you an example of how i will dot it. Note that i had to simulate location change with some code, but every time you run the example, it will highlight a different anchor tag.
$(document).ready(function()
{
// Simulate change on "windows.location.href"
//===========================================================
var paths = ["/index.html","/friends.html","/settings.html"];
var idx = Math.floor(Math.random() * 3) + 0;
console.log("Random idx = " + idx);
//===========================================================
var path = paths[idx];
//var path = window.location.href;
$("a").removeClass('active');
$("a[href='" + path + "']").addClass('active');
});
.active {
border-right: 10px solid blue;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<aside>
<nav>
<ul>
<li>Chat</li>
<li>Friends</li>
<li>Settings</li>
</ul>
</nav>
</aside>

Related

Change url doesn't change tab selected

I was implementing that if i refresh the page, it should make active to previously selected tab(preserve selected tab) . So I Create a simple html page and add some jQuery.
But if i change URL manually like file:///home/2.html#news to file:///home/2.html#home
it changes only content of page but doesn't change tab ,that was selected. .
Here is my code.
<body>
<ul>
<li id="first">Home</li>
<li id="second">News</li>
<li id="third">Contact</li>
<li id="forth">About</li>
</ul>
<p id="home">
home section
</p>
<p id="news">
news section
</p>
<p id="contact">
contact section
</p>
<p id="about">
about section
</p>
</body>
<style>
p{
display: none;
}
:target {
display:block;
border: 2px solid #D4D4D4;
background-color: #e5eecc;
}
</style>
<script type="text/javascript">
$(document).ready(function(){
if(localStorage.getItem("active_state") == null ){
activeStateId = "first";
}
else{
activeStateId = localStorage.getItem("active_state")
}
$('#'+activeStateId).addClass('active');
$('li').click(function(){
$('.active').removeClass('active');
$(this).addClass('active');
localStorage.setItem("active_state", $(this).attr('id'));
});
});
</script>
When you got link hashes, you dont actually reload the page, but the browser just triggers those links. You rely on CSS :target change rule which evaluates every time the #hash changes on the url.
p {
display: none;
}
:target {
display:block;
border: 2px solid #D4D4D4;
background-color: #e5eecc;
}
Thus, you have all the sections updated properly even without refreshing the page. In order to have such functionality, you don't need to store any data to the local or remote machine since you are using hashes on the url. Just use the hashes and handle the hashchange event to add the .activate class to the links like this:
$(document).ready(function() {
var hash = window.location.hash;
if(hash.length > 0) {
hash = hash.substring(1);
$('li a[href$='+hash+']').parent().addClass('active');
}
$(window).on('hashchange', function() {
$('.active').removeClass('active');
var hash = window.location.hash
if(hash.length > 0) {
hash = hash.substring(1);
$('li a[href$='+hash+']').parent().addClass('active');
}
});
});
Check my working example here: http://zikro.gr/dbg/html/urlhash.html#about

Calling a JS script in HTML

Hello there I have this code and I want to display active links in purple. I have that in a js file however, does not seem to work as expected. I am not sure where exactly I am doing wrong. Everything else is working properly but when you clink a link it fails to highlight to purple as is in the css. I have provided the necessary code only, Anyone?
html
<html>
<head>
<link href="site.css" rel="stylesheet"> <script src="color.js"></script>
</head>
<body>
<div class="nav-container">
<ul class="navigation-menu">
<li><a href='start.php'>Home</a></li>
<li><a href='pay.php'>C2B Payments</a> </li>
<li><a href='sms.php'>C2B SMS</a></li>
<li><a href='#'>B2C Payments</a>
<ul>
<li> B2C Payments</li>
<li> Make Payments</li>
</ul>
</li>
<li><a href='bsms.php'>B2C SMS</a></li>
<li><a href='index.php'>Log Out</a></li>
</ul>
</div>
</body>
</html>
css (site.css)
.navigation-menu li.active a {
background-color: purple;
color:#fff;
}
.navigation-menu li ul {
display: none;
}
.navigation-menu li a:hover{
background-color:black;
color: white;
}
.navigation-menu li a.active {
background-color: purple;
color:#fff;
}
javascript (color.js)
$(document).ready(function(){
$('ul li a').click(function(){
$('li a').removeClass("active");
$(this).addClass("active");
});
});
You have two problems.
First, you haven't included jQuery on the page, so when the JS runs, it throws an error because $ isn't defined.
If you were to fix then this would be the order of events:
The link is clicked
The JavaScript starts running
The JavaScript modifies the DOM of the page
The JavaScript finishes
The browser follows the link
The page with the modified DOM is discarded
A new page is loaded
… and the new page hasn't been modified by the JavaScript.
Put the active class in the HTML of the new page.
You have to check the page url and match href in the element and add class active to respective element
You have to include jQuery Lib
Replace test.html page2.html by the name of page u have
$(document).ready(function() {
var pageURL = $(location).attr('href'),
pageName= [ /test.html/, /page2.html/, /page3.html/],
links = $('a'),
LinksToActive;
for( var i=0; i < $(pageName).size(); i++){
for( var j=0; j < $(links).size(); j++){
var str = $(links[j]).attr('href');
if( 'str:contains(pageName[i])' ){
LinksToActive = $(links[j]);
break;
}
else{
continue
}
}
}
$(LinksToActive).addClass('active');
});
Change/ Add page name in pageName variable nad this script just before closing of body tag

Bootstrap navbar menu item li a change the active class when in the specific page

Using pure CSS and some javascript, how can I manage to remove and add the class 'active' to my li item? I tried using the 'onclick' function in javascript. It changes the color of the item but it doesn't redirect me to the link of my the selected item.
<div class="main_navs">
<ul class="nav navbar-nav">
<li>Home</li>
<li>Products</li>
<li>Services</li>
<li> Wishlist</li>
<li> Register</li>
<li> Gift Card</li>
<li><a href="cart.php" class="main_navmenu"
<i class="fa fa-shopping-cart"></i> Cart <span class="badge">0</span></a></li>
</ul>
</div>
<script type="text/javascript">
$('#main_menu_items li a').on('click', function(){
$('li a.active').removeClass('active');
$(this).addClass('active');
});
</script>
CSS:
.main_navs ul li a.active{
background: rgba(255,255,255,0.2);
color: #333;
}
.main_navs ul li a{
background: rgba(0,0,0,1);
color: #fff;
}
I think this should help you out. It should add the class active to the matching anchor in your menu on page load.
<script>
$(function() {
var url = window.location.pathname,
urlRegExp = new RegExp(url.replace(/\/$/, '') + "$");
$('.main_navs a').each(function() {
if (urlRegExp.test(this.href.replace(/\/$/, ''))) {
$(this).addClass('active');
}
});
});
</script>
Remove trailing slash first and then it would equal to the url that you want to match.
My solution is:
var current = window.location.href;
var current_url = current.replace(/\/$/, "");
$('.navbar-nav a').each(function(){
var $this = $(this);
// if the current path is like this link, make it active
if($this.attr('href').indexOf(current_url) !== -1){
$this.addClass('active');
}
});

Adding a class to a link inside a <li> element on scrolling

Is it possible to add a class to a link inside a li element when a certain part of the page is active?
I have a one page website and would like to change the color of the link when that specific part of the page is reached via scroll.
Here's my HTML:
<header id="header">
<section class="container">
<nav>
<a class="logo" href="index.html">Logo</a>
<div id="menu">
<ul id="links">
<li>Services</li>
<li>About</li>
<li>Clients</li>
<li class="last">Contact</li>
</ul>
</div>
</nav>
</section>
</header>
And here's the CSS:
#menu li a {
color:#7a7a7a;
text-decoration: none;
font-size: 12px;
margin-right:20px;
}
#menu li.last a {
color:#7a7a7a;
text-decoration: none;
font-size: 12px;
margin-right:0px;
}
#menu li.current a {
color: #0086be;
}
What I would like to do is to add the class .current to the link inside the li element whenever that specific part of the page is reached.
I believe this is only possible with Javascript, can anyone point me the right path to achieve this?
Thanks in advance
I think you want something like scrollspy in bootstrap,
you can use it or you can find https://gist.github.com/pascaldevink/2380129 bypascaldevink
or here is the fiddle http://jsfiddle.net/ia_archiver/Kb7xq/
You will require jquery for this,
$.fn.scrollspy = function ( option ) {
return this.each(function () {
var $this = $(this)
, data = $this.data('scrollspy')
, options = typeof option == 'object' && option
if (!data) $this.data('scrollspy', (data = new ScrollSpy(this, options)))
if (typeof option == 'string') data[option]()
})
}
$.fn.scrollspy.Constructor = ScrollSpy
$.fn.scrollspy.defaults = {
offset: 10
}
$(function () {
$('[data-spy="scroll"]').each(function () {
var $spy = $(this)
$spy.scrollspy($spy.data())
})
})
}(window.jQuery);
Using hover function you can achieve this.i.e. on hover of specific part of the page you add the class to the link present inside the li. e.g.
$('#specificPartOfPageId').hover(function(){
$('#links').children().children('a').addClass('current');
});
This would add .current class to every link present inside that UL element.
Hope this helps.
If I have understood correctly, I guess this is what you require: jsFiddle. The CSS and the HTML code remains the same and this is the jQuery code which I've used:
$(window).scroll(function() {
var scroll = $(window).scrollTop();
if (scroll > 500) {
$("#links li:first-child").addClass("current");
}
if (scroll > 750) {
$("#links li:first-child").removeClass("current");
$("#links li:nth-child(2)").addClass("current");
}
var scrollBottom = $(window).scrollTop() + $(window).height();
if (scroll < 500) {
$("#links li:first-child").removeClass("current");
}
if (scroll < 750) {
$("#links li:nth-child(2)").removeClass("current");
}
});
Basically what happens is that when you scroll down to 500px, the li:first-child is automatically assigned the current class. You can modify the jQuery to suit your needs by adding more if queries as per your needs. You can target different <li>'s in your list using different child-selectors like li:first-child, li:nth-child(2) etc.

changing style sheet of clicked menu item asp.net master page

I have an asp.net master page with a menu like this:
<menu id="menu">
<nav id="main_nav">
<ul id="menu-primary">
<li >Home</li>
<li>Staff</li>
<li>Sales</li>
<li>Support</li>
<li>Administration</li>
</ul>
</nav>
</menu>
In master page, I want to change css for the menu item clicked. I have this jquery:
<script type="text/javascript">
jQuery(document).ready(function () {
$('ul li a').each(function () {
var text_splited = $(this).text().split(" ");
$(this).html("<span>" + text_splited.shift() + " " + text_splited.join(" ") + "</span> ");
});
// click on the first item on page load
$('#menu-primary li').eq(0).click();
$('#menu-primary li').click(function (e) {
alert('here');
// remove all active classes
$('#menu-primary li').removeClass('current-menu-item');
// add active class to clicked item
$(this).addClass('current-menu-item');
});
});
</script>
Here is the css
nav#main_nav ul li.current-menu-item a,
nav#main_nav ul li a:hover {background: url("../images/menu_bg.png") no-repeat scroll 0 -149px transparent; border-bottom:1px solid #edf7ff}
nav#main_nav ul li.current-menu-item a span,
nav#main_nav ul li a:hover span{background: url("../images/menu_bg.png") no-repeat scroll 100% -118px transparent;}
This one works :
// click on the first item on page load
$('#menu-primary li').eq(0).click();
$('#menu-primary li').click(function (e) {
// remove all active classes
alert($('#menu-primary li').html());
$('#menu-primary li').removeClass('current-menu-item');
// add active class to clicked item
$(this).addClass('current-menu-item');
return false;
});
But the page is not loaded because th efunction return false.
The alert is shown but the css is not applied to the clicked item.
Can you try doing something like this
$("#menu-primary li.current-menu-item").removeClass("current-menu-item");
$(this).addClass("current-menu-item");
To set first menu item to be selected by default add current-menu-item class to it like this
<li class="current-menu-item">Menu Item</li>
See Working Sample
Alternative approach based on Page URL
$('#menu-primary li a').each(function() {
var path = window.location.href;
var current = path.substring(path.lastIndexOf('/'));
var url = $(this).attr('href');
if(current=="")
$('#menu-primary li a').first().addClass('current-menu-item');
if (url == current) {
$(this).addClass('current-menu-item');
};
});

Categories

Resources