Reputation: 65
How can I stay the Jquery functions when it leaves the page? The code below is running good when the link is blank/#, but When I change the # and make it the path link, the jquery seems not running properly. I click it, it change the background but when it goes to the link the background was gone, is there something I miss in the code?
$(document).ready(function(e){
$('#main-menu li a').click(function(e) {
$('#main-menu li a').removeClass('active');
$(this).addClass('active');
});
});
#main-menu li {
display: inline-block;
font-family: 'Raleway', sans-serif;
padding: 17px 25px;
}
#main-menu li a {
color:#333333;
font-size:15px;
}
#main-menu li.active a {
color:#0198cf;
}
#main-menu li:last-child {
padding-right: 0;
}
.active{
background-color:#ccc;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul class="topnav" id="main-menu">
<li ><a href="#" class="active" ><i class="fa fa-home" aria-hidden="true"></i> Home</a></li>
<li><a href="#" ><i class="fa fa-file" aria-hidden="true"></i> Home2</a></li>
<li><a href="#" ><i class="fa fa-codepen" aria-hidden="true"></i> Home3</a></li>
<li><a href="#" ><i class="fa fa-globe" aria-hidden="true"></i> Home4</a></li>
</ul>
Upvotes: 2
Views: 626
Reputation: 4251
Add this script:
$(function () {
var url = window.location.pathname,
urlRegExp = new RegExp(url.replace(/\/$/, '') + "$");
$('#main-menu li a').each(function () {
if (urlRegExp.test(this.href.replace(/\/$/, ''))) {
$(this).addClass('active');
$(this).parent().previoussibling().find('a').removeClass('active');
}
});
});
Upvotes: 4
Reputation: 1370
You need to stop default behavior of a element. You should call preventDefault
function for your a click event:
$(document).ready(function(e){
$('#main-menu li a').click(function(e) {
e.preventDefault();
$('#main-menu li a').removeClass('active');
$(this).addClass('active');
});
});
Upvotes: 4
Reputation: 648
If the user is traveling off of the current page, the styles modified by jQuery will be gone permanently, as they are not saved anywhere.
However, using javascript you can store cookies, and if that cookie exists, you can add the background style you desire.
See https://www.w3schools.com/js/js_cookies.asp for more insight into storing cookies.
Upvotes: 2