JavaScript to highlight active page - javascript

I am trying to utilize JavaScript to highlight the current page. I have a main menu and a sub menu on the page. I want the highlighted main menu to look different from the sub menu. Here is the JavaScript I came up with the apply a css class to the current page. How do I get the JavaScript to differentiate the two different classes?
<script src="http://code.jquery.com/jquery-1.8.3.min.js"></script>
<script>
$(function(){
$('a').each(function() {
if ($(this).prop('href') == window.location.href) {
$(this).addClass('main_current');
}
});
});
</script>
<script>
$(function(){
$('a').each(function() {
if ($(this).prop('href') == window.location.href) {
$(this).addClass('sub_current');
}
});
});
</script>

It really depends on the page/code structure you're going for. I usually don't check window.location, but instead set rel attribute on the page body. On homepage body will have rel="home", on some other page rel='other-page and so forth.
This way you can check for body's rel attribute and change menu/submenu's status based on that.
(function(){
var currentLocation = $('body').attr('rel');
switch(currentLocation){
case 'home':
//add class to the home link
break;
case 'other-page':
//add class to the other link
break;
}
})();

Specify better the selector when you iterate over the submenu and override some properties with 'sub_current'. EG:
If you have
<ul id="menu">
<li>ThisMenu
<ul id="sub-menu">
<li>ThisSubMenu</li>
</ul>
</li>
</ul>
you could specify with $('#sub-menu a').
I hope it helps.
cheers

The method below will do the same thing
$(function() {
var url = document.location.href;
if (url.indexOf("about") > -1) {
$('#nav-bar ul li:contains("About")').addClass('sub_current');
}
else if (url.indexOf("index") > -1) {
$('#nav-bar ul li:contains("Home")').addClass('main_current');
}
else {
// do something else
}
});
Note: :contains selctor is case sensitive.

Related

Open page based on $(this) selector

I'm modifying a wordpress site and have a menu with four anchor tags (buttons) to the left of a slider. When a user selects a button, the slide associated with the button shows. Now, I'd like to open a page when the user clicks the button, instead of showing the slide. Here is the code so far:
$('#slidernavigation > a').on('click', function(e){
e.preventDefault();
$a = $(this);
$(this).showSlide();
if($a.id == $('#slide-1285')){
console.log('testing');
}
else{
console.log('not-testing');
}
});
Here I'm testing to see if I can click on the anchor with the id '#slide-1285' and log it to the console. It always says 'not testing'. I'm going to set up conditions for all id's so a user is redirected to the correct page. Something like this:
$('#slidernavigation > a').on('click', function(e){
e.preventDefault();
$(this).showSlide();
if($a.id == $('#slide-1285')){
window.location.href = "http://webpage1";
}
elseif($a.id == $('#slide-1286')){
window.location.href = "http://webpage2";
}
elseif($a.id == $('#slide-1287')){
window.location.href = "http://webpage3";
}
else($a.id == $('#slide-1288')){
window.location.href = "http://webpage4";
}
});
Any ideas? Thanks in advance.
To get the id of the element that was clicked, you can do:
$(this).attr('id');
That will return a string. So you could do:
if($(this).attr('id') === 'slide-1285') { do something }
$('#slide-1285') would return a jquery element, but you want just the id. I think the code above is more what you are looking for.
You can add a new data attribute to each of your link and then get that value and redirect.
<a data-webpage="http://webpage1" href="whatever" id="slide-123"></a>
<a data-webpage="http://webpage2" href="whatever" id="slide-456"></a>
.....
and then
// this will bind all ids starting with slide-
$('[id^=slide-]').on('click', function(e){
// some code.
window.location.href = $(this).data('webpage');
}
1) you are comparing $a.id, that is string, to object $('#slide-1285');.
2) To simplify:
$(document).ready(function(){
$('.a').click(function(e){
e.preventDefault();
window.location = $(this).attr('href');
});
});
<a href='http://google.com' class='a'>Google!</a><br/>
<a href='http://stackoverflow.com' class='a'>SO!</a><br/>
jQuery objects have no id property. You need to do attr('id'), or just get the id property of the plain DOM object. Additionally, jQuery objects are never going to equal each other. Third, you want to check if the clicked element has a certain ID, which can be done using .is().
In sum, you could do one of these:
Comparing strings:
$('#slidernavigation > a').on('click', function(e){
if(this.id == '#slide-1285'){
console.log('testing');
}
else{
console.log('not-testing');
}
});
Using .is():
$('#slidernavigation > a').on('click', function(e){
if($(this).is('#slide-1285')){
console.log('testing');
}
else{
console.log('not-testing');
}
});
Or, just let the browser do its thing. Give your <a>s href attributes, and they'll function as links, even without JS.
instead of writing $.id
you should write
$a.attr('id')
and this should be checked like this :-
if( $a.attr('id') == slide-1285)
not the way you are doing :)
Try
var pages = [{"slide-1285" : "http://webpage1"}
, {"slide-1286" : "http://webpage2"}
, {"slide-1287" : "http://webpage3"}
, {"slide-1288" : "http://webpage4"}
];
$('#slidernavigation > a').on('click', function(e) {
e.preventDefault();
var nav = e.target.id;
$.grep(pages, function(page) {
if (nav in page) {
window.location.href = page[nav];
}
})
});
jsfiddle http://jsfiddle.net/guest271314/2nf97dfr/
<div id="a">
dhjdfd
</div>
$('#a').on('click',function(e){
var clickedElement= e.srcElement;
if($(clickedElement).attr("id") == "abc"){
//do something
}
});
just use e.srcElement to get the element reference and then get its id.. and btw u can use switch case rather than multiple if else statements ..
working fiddle link

Find if current windows.pathname contains location to li a href

I have this code to add an active class on the link to the current page:
jQuery(function() {
jQuery('.topmenu li').each(function() {
var href = jQuery(this).find('a').attr('href');
if (href === window.location.pathname) {
jQuery(this).find('a').addClass('active');
}
});
});
This works great for matching exactly the pathname, but how can I see if the page I'm on, is a subpage for a link?
When I have a link like this: Sub page 1 the code works.
When Im on /top-page-1/sub-page-1/, but when I'm on /top-page-1/sub-page-1/sub-sub-page-1/, I don't get an active class on the link. Is there any way to this?
try this in your code:
jQuery(function() {
jQuery('.topmenu li').each(function() {
var href = jQuery(this).find('a').attr('href');
if (window.location.pathname.indexOf(href)>-1) {
jQuery(this).find('a').addClass('active');
}
});
});

add class on li remove after page load

I am using jquery to add the class to active css on "li" and also navigate to an html page.but after page navigates the class disappers on "li". I have tried different ways to resolve this but couldn't get the point.
$(document).ready(function(){
$( '#topList ul li' ).click(function() {
alert($(this).attr('id'));
if($(this).attr('id') == "add") {
document.location.href = 'localhost:8080/add';
$(this).attr('id').addClass("active");
}
});
});
here is the menu list, what I want is when I click on li it should call a page add and also add a class on that li.
html code
<ul class="nav">
<li class="" id="add"></i> Add </li>
<ul>
You need to add class for the li in the page you are calling ie, the page will be rendered when you call localhost:8080/add.
Because in your code setting up of active class wont be called since the localhost:8080/add will start loading in the previous line of code (document.location.href = 'localhost:8080/add';)
If the page to be rendered is static page then, add this code in that page.
$(document).ready(function(){
$('#add').addClass("active");
});
Use the following script on the page where you have menu or the links.
<div id="cssmenu">
<a href="blah blah" > Test page</a>
<a href="blah blah" > Test page</a>
</div>
$(document).ready(function () {
var pageTitle = window.location.pathname.replace(/^.*\/([^/]*)/, "$1");
$('#cssmenu a').each(function () {
if ($(this).attr('href').toLowerCase() == pageTitle.toLocaleLowerCase())
$(this).addClass('active');
});
});
I solved this problem on my website by looking at the URL and deciding which of the navigation elements was best to add.
function showContent(target) {
var e = $('#'+target);
$(".content").hide();
$("#nav li.active").removeClass("active");
$("#nav li[target='"+target+"']").addClass("active");
e.toggle();
ga('send','pageview',window.location.pathname+"#"+target);
}
// this looks at the URL (by the #...) and decides which view is active
// this gets called on ready and if the client hits the link
// (which dynamically loads instead of making a trip for a new page to the server)
$(window).hashchange(function() {
var which=window.location.hash.substring(1);
switch( which) {
default:
which="profile";
case "profile":
case "resume":
case "projects":
case "contact":
showContent( which);
}
});

adding specific class to element on click jquery

I'm having trouble with a simple nav bar that uses jQuery to add and remove a specific class when a certain page is active. I want a class to append to my aLink class depending on which ID is click. If I click on #aboutLink I want .linkActive to be added, but if I click on #sasLink I want .link2Active to be added. The tutorials I've looked at all have a single class being added, but since both my classes are different I need a specific one to be added depending on which ID is click.
HTML:
<div id="mainNav">
<ul id="nav">
<a id="mainLogo" href="/"><li></li></a>
<a id="aboutLink" class="aLink" href="/"><li></li></a>
<a id="sasLink" class="aLink" href="/savings-and-support"><li></li></a>
<a id="external" href="/"><li></li></a>
</ul>
</div><!--/#mainNav-->
I know my jQuery doesn't make sense, but it's all I could come up with. Logically I get it, but I'm lost on the syntax.
jQuery:
$(function () {
$(".aLink").click(function () {
if ($(this) == $("#aboutLink")
$(this).addClass('activeLink');
else $(this).addClass('active2Link');
});
});
Thanks for any input or direction.
var idToClass = {
'aboutLink' : 'linkActive',
'sasLink' : 'link2Active'
}
$('#nav a').click(function(){
e.preventDefault();
$(this).addClass(idToClass[this.id]);
});
JS Fiddle demo.
You could, instead, use toggleClass() to allow for those classes to be removed by a second click:
var idToClass = {
'aboutLink' : 'linkActive',
'sasLink' : 'link2Active'
}
$('#nav a').click(function(e){
e.preventDefault();
$(this).toggleClass(idToClass[this.id]);
});
JS Fiddle demo.
Edited in response to question, from the OP, in comments, below:
How would I remove the class so that both links don't appear to be active at the same time?
There's a few ways, but because you're adding different class-names to denote the 'active' state, they're a little inefficient. The first approach is to use a brute-force method, effectively looking for all a elements that have a class attribute and setting that attribute to the empty string, and then adding the linkActive/link2Active class-name to the clicked-on a element:
$('#nav a').click(function(e){
e.preventDefault();
var self = $(this);
self.closest('ul').find('a[class]').attr('class', '');
self.toggleClass(idToClass[this.id]);
});
JS Fiddle demo.
The alternative is to remove the specific classes from the elements who have their id listed in the idToClass object. This is, however, somewhat expensive in that it needs to iterate over the object, retrieving the id, finding the element with that id and then removing a class-name:
$('#nav a').click(function(e){
e.preventDefault();
for (var id in idToClass) {
if (idToClass.hasOwnProperty(id)){
$('#' + id).removeClass(idToClass[id]);
}
}
$(this).addClass(idToClass[this.id]);
});
JS Fiddle demo.
If, of course, you use a common class-name then it all becomes much easier:
$('#nav a').click(function (e) {
e.preventDefault();
var self = $(this);
self.closest('ul')
.find('.commonActiveClassName')
.removeClass('commonActiveClassName');
self.addClass('commonActiveClassName');
});
JS Fiddle demo.
References:
addClass().
closest().
event.preventDefault().
find().
removeClass().
toggleClass().
Since you already have ID tags to easily reference... I think you want something more like this?
$(function () {
$("#aboutLink").click(function () {
$(this).addClass('activeLink');
});
$("#sasLink").click(function () {
$(this).addClass('active2Link');
});
});
Try using this instead:
$(function () {
$(".aLink").click(function () {
var currentId = this.id;
if ( currentId == "aboutLink"){
$(this).addClass('activeLink');
else if( currentId == "sasLink") {
$(this).addClass('active2Link');
}
});
});

compare url string and menu string then add class using jquery

I have a URL which looks like this:
http://www.website.co.uk/en-us/aboutus/thegroup/test.aspx
I have a UL LI menu on the page:
<ul>
<li>Test</li>
<li>Hello</li>
<li>Bye</li>
<li>Something</li>
<li>Cars</li>
</ul>
I am having the menu on every page and would like to use jquery to check that im on that page. If i am then make the A/li bold so the user knows they are on the page.
I have tried the following:
$(document).ready(function () {
if(window.location.href.indexOf("test")) //
{
alert("your url contains the name test");
}
});
But id like something that doesnt involve hard coding the values of the URL string. As if the user decides to add more links to the UL/LI the jquery needs to check the link and the url automatically and add a class to the LI (so that i can style it).
Hopefully thats enough infomation.
The issue is because the indexOf() method returns -1 when the value is not found. You need to check for that value, not coerce the result to a boolean as you currently are. Try this:
$(document).ready(function () {
var loc = window.location.href;
$("ul a").each(function() {
if (loc.indexOf($(this).attr("href")) != -1) {
$(this).addClass("current");
}
});
});
You would need to make the selector a bit more specific, something like #menu a
This?
$('ul#menu a').each(function() {
if(window.location.href.indexOf($(this).attr('href')) !== -1) {
$(this).closest('li').addClass('yourClass');
}
});
I added an id menu to your ul to basically differentiate your menubar with other uls that may be in the same page. also !== -1 as indexOf returns -1 if it can't find the string searched in the argument.
indexOf returns -1 if the string is not contained:
(document).ready(function () {
if(window.location.href.indexOf("test") != -1) //
{
alert("your url contains the name test");
}
});
$(document).ready(function () {
var liTest = $('ul > li'); // ' was missing
liTest.each(function() {
if(window.location.href == $('a', this).attr('href')) //
{
$(this).css('font-weight', 'bold');
return;
}
});
});

Categories

Resources