views:

120

answers:

3

how can i select the current link via jquery if I have a div like this:

<div id='navigation'>
  <a href='users/home'>home</a> |
  <a href='projects/browse'>home</a>
  <a href='discussions/browse'>home</a>
  <a href='search/dosearch'>home</a>
</div>

Note I've tried:

$(document).ready(function(){
    $("#navigation a").click( function(event)
    {
       var clicked = $(this); // jQuery wrapper for clicked element
       // ... click-specific code goes here ...
       clicked.addClass('selected');
    });
});

But when I click on a link it selects a link and adds the class .selected but it reloads the page in order to navigate to a page and then it all disappears. Any tips?

Thanks

+1  A: 

Yep, take the event from your click() callback arguments and use e.preventDefault(); (see there).

Or return false.

Or add a target='_blank' attribute to your links so that they open the link in some other page or tab, if you still want the link to be opened by the browser somewhere.

subtenante
+5  A: 

This should work:

$(document).ready(function() {
    var loc = window.location.href; // The URL of the page we're looking at
    $('#navigation a').each(function() {
     if (loc.indexOf(this.href) !== -1) { // If the URL contains the href of the anchor
      $(this).addClass('selected'); // Mark it as selected
     }
    });
});

It basically loops over the navigation items, and if the URL of the current page contains the href of the anchor, it adds the class selected to the anchor.

moff
Yes but it will still reload the page because the default event attached on the link will still be activated.
subtenante
Right, but the question (as I understood it) was how to select the current link, and not how to stay on the current page. I don't know if I'm right, though.
moff
@Moff - That's a nifty piece of code
Dan F
@Dan - Thanks :)
moff
@Moff - You rule man! This totally works. Awesome piece of code! Thanks a lott!!
Emil Hajric
A: 
$(document).ready(function(){
    $("#navigation a").click( function(event)
    {
       var clicked = $(this); // jQuery wrapper for clicked element
       // ... click-specific code goes here ...
       clicked.addClass('selected');
       return false;
    });
});

Don't forget to return false!

thezachperson31