3

New coder here and would really appreciate your help with a problem that's got me stumped.

I'd like to write code that will recognize the link that applies to the current page and applies a different CSS style to that current link. I've researched this problem and have found that it's best accomplished using jQuery to identify the current link and then apply a new class to it (e.g., ".current"). However, when I've tried to implement this on the site it hasn't worked.

This is the HTML I'm working with:

<nav class="main-nav">
   <a href="http://website.com" class="main-nav-link">
      <span class="main-nav-item" id="nav-content"></span>
   </a>
   <a href="http://website.com/calendar" class="main-nav-link">
      <span class="main-nav-item" id="nav-calendar"></span>
   </a>
   <a href="http://website.com/profile" class="main-nav-link">
      <span class="main-nav-item" id="nav-profile"></span>
   </a>
</nav>

And this is the CSS I've applied:

.main-nav .main-nav-item {
  height: 50px;
  width: 150px;
}

.main-nav #nav-content {
  background: url('/images/content-inactive.png') no-repeat center;
}

.main-nav #nav-calendar {
  background: url('/images/calendar-inactive.png') no-repeat center;
}

.main-nav #nav-profile {
  background: url('/images/profile-inactive.png') no-repeat center;
}

My goal is to change the background: for the span within the current page's <a>.

Here are some other StackOverflow threads that have addressed this problem, but haven't helped me to reach a solution:

It's not completely clear to me where I'm supposed to be putting the Javascript, but I currently have it between <script type="text/javascript"> and </script> in the <header> section.

Thanks in advance for your assistance. :)

--

UPDATE:

I currently have the following code in the page, but it's not working.

The Javascript:

<script>

      $(document).ready(function() {

     // Get the current URL
            var currentUrl = window.location.href;

            // Get the span you want with a combination class and attribute and child jQuery selector
            var currentMenuItem = $(".main-nav-link[href='" + currentUrl + "'] > .main-nav-item");

            // Then add your class
            currentMenuItem.addClass("current");

        });

</script>

And the CSS:

#nav-content.current {
  background: url('/images/content-active.png') no-repeat center -94px;
}

The jQuery isn't adding the .current class to the active link, so the CSS doesn't even have the opportunity to work.

Community
  • 1
  • 1
Max
  • 73
  • 1
  • 3
  • 10
  • FYI, there is [no need to use `type=` in your script tags](http://www.youtube.com/watch?feature=player_detailpage&v=Y2Y0U-2qJMs#t=936s), in fact `text/javascript` is not the MIME type for JS. – Useless Code Apr 16 '13 at 02:14

3 Answers3

2

The common way to do this, is to add a class like "active" to your active page-link server side. You could then style the element with jQuery like so:

$('.active').css('background-image','images/activebg.png');

But as you mentioned, you would need a different background for each "active" element, and you want to use the link. (I suppose you mean the URL).

You can get the current page's URL like this:

var current_url = window.location.href;

You can then select the link with the current URL like this:

var $link = $('.main-nav a[href='+current_url +']');

So now you can set the background active for the current page link like this:

$link.css('background-image','images/activebg.png');

Now, if you have a custom active background for each link, I would suggest you create your own attribute hover_img or something in which you provide the hover url:

<a href="http://website.com" class="main-nav-link" hover_img="/images/hover-home.png" > ....
<a href="http://website.com/calendar" class="main-nav-link calendar" hover_img="/images/hover-calendar.png"> ....

and so on.

Then, you can change my last line of code to:

$link.css('background-image',$link.attr('hover_img'));
Jules Colle
  • 11,227
  • 8
  • 60
  • 67
  • Thanks for replying, but I'm a bit confused by your answer. I get the first part about defining the "current_url" variable as the active page and I think I understand the second part about defining the "$link" variable as the link pointing to the "current_url" (though I'm not sure why you used the dollar sign). However, you lost me after that when you suggested I create my own attribute. Wouldn't it just be easiest to use the `.addClass` function to give a distinct class to the active `` or to the `` within the active ``? – Max Apr 16 '13 at 17:01
  • I just add a $ to variables whenever the variable is a jQuery object. You don't need to do that. But it makes things clearer if you work with jQuery often. Also, you can indeed set the class to active with addClass. My last two blocks of code are only useful if you need a different background-image for each active link. If you don't need that, you could just go `$link.addClass('.active')` and define the appropriate background in CSS. – Jules Colle Apr 17 '13 at 06:52
2

window.location.href will get your current URL. Then you need to use a jQuery selector that finds the <span class="main-nav-item"> child of the <a class="main-nav-link"> element with that href attribute. Apply your class "current" to that element, and you should be good to go. So how about this JavaScript:

// Get the current URL
var currentUrl = window.location.href;

// Get the span you want with a combination class and attribute and child jQuery selector
var currentMenuItem = $(".main-nav-link[href='" + currentUrl + "'] > .main-nav-item");

// Then add your class
currentMenuItem.addClass("current");

Put that in your script tags and give it a try.

Once you have it working, make sure you add the proper CSS rules. For example, add a rule that loads a different background image for #nav-content.current (and another all the rest).

(A note about your current CSS: It looks like you're overqualifying your selectors. If you don't have to worry about .main-nav-items anywhere else on the page, don't bother qualifying that class with the .main-nav before it. And your id selectors (e.g. #nav-content) certainly don't need to be qualified, since they're unique identifiers.)

Hope that makes sense to you and helps.

davidtheclark
  • 4,666
  • 6
  • 32
  • 42
  • Thanks, Dave. This makes sense and I followed it, but it isn't applying the `current` class to the span within the active link. I'm not sure why that this... – Max Apr 16 '13 at 16:53
  • I copy and pasted your exact code between my ` – Max Apr 16 '13 at 16:54
  • I made a JS fiddle and the code worked for me: http://jsfiddle.net/HwW72/. Did you include jQuery BEFORE the script tag? And did you wrap the code above in a $(document).ready(function() {}) (see tymeJV below) -- which you always should do when manipulating DOM elements (otherwise the script might run before your elements are populated on the page)? – davidtheclark Apr 16 '13 at 18:40
  • I've tried the script before and after. Neither worked. (Which one was I supposed to do?) I've also tried inserting the script in localized-js.php (I'm working with WordPress and that puts the Javascript at the bottom of the page) and that didn't work either. – Max Apr 16 '13 at 19:40
  • I've updated the question so that you can can see the exact code that I currently have on the page. – Max Apr 16 '13 at 19:45
  • Also, I do see that there are a bunch of external Javascript files called in the header that are part of theme I'm working with. – Max Apr 16 '13 at 20:00
  • Because the code works in the JS Fiddle I'm pretty sure it should work on your site; so the problem is probably that Wordpress is being tricky. Do you know how to use Chrome's devtools (or another debugger) to check whether jQuery is loading, what the value of a variable is, etc.? If not, you should learn how to use that: it will help you identify exactly where things are going wrong. You will use a debugger on every project you ever work on. I don't know how to figure out remotely what's going wrong at this point -- but if you could get more info with a debugger, I might be able to help. – davidtheclark Apr 16 '13 at 21:03
  • I right click and inspect element in Chrome. That's how I can see that the "current" class isn't being applied to the active link. Are those the devtools you're referring to? (Is there a way for me to send you a private message on here? The site isn't live, but I can send you the URL and the password you need to view it.) Thanks for all of your help here. Really appreciate it. – Max Apr 17 '13 at 01:08
  • Got it. Sending shortly. Thanks again. – Max Apr 19 '13 at 00:27
1

Inside your script page tags you can use the following:

$(document).ready(function() {
    var currentPage = "content"; // <--Change this to the id of your span after the nav-

    //Change the background color now
    $("#nav-" + currentPage).addClass("className");
});
tymeJV
  • 103,943
  • 14
  • 161
  • 157
  • Why not just do this in CSS? – ahren Apr 16 '13 at 02:19
  • OP said he was looking into jQuery, this is what I provided. – tymeJV Apr 16 '13 at 02:20
  • Thanks for your reply, tymeJV. However, I'm simply looking to add a class to the span within the active link (rather than apply the new background directly using jQuery.) The reason for this is that there are different backgrounds for the different links depending upon which one is active. – Max Apr 16 '13 at 16:40