CSS and jQuery links navigation: how to update the <li> class
I have this jQuery code that retrieves external content using ajax without linking to the page, and I also have navigation links that have a different background color when the user is on the current page.
JQuery Code:
function loadPage(url) //the function that loads pages via AJAX
{
url=url.replace('#page',''); //strip the #page part of the hash and leave only the page number
//$('#loading').css('visibility','visible'); //show the rotating gif animation
$('.counter').html('<img src="img/ajax_load.gif" width="16" height="16" style="padding:12px" alt="loading" />');
$.ajax({ //create an ajax request to load_page.php
type: "POST",
url: "load_page.php",
data: 'page='+url, //with the page number as a parameter
dataType: "", //expect html to be returned
success: function(msg){
if(parseInt(msg)!=0) //if no errors
{
$('#change-container').html(msg); //load the returned html into pageContet
}
}
});
}
html navigation code:
<ul>
<li class="current"><a href="#page1">Home</a></li>
<li><a href="#page3">Replies</a></li>
<li><a href="#page4">Favorites</a></li>
</ul>
Therefore, when someone clicks on the answer link, I want the class to lichange to the current one to indicate that you are on this page.
+3
2 answers
Example: http://jsfiddle.net/4cs9h/
$('ul > li > a').click(function() {
var $th = $(this).parent();
if( !$th.hasClass('current') ) {
$th.addClass('current')
.siblings('.current').removeClass('current');
loadPage(this.href);
}
return false;
});
The variable $threfers to the parent <li> <a>that was clicked.
<li> current, , , loadPage(), href <a>.
, , <ul> .
$('#navigation > li > a').click(function() {...
HTML
<ul id="navigation">
<li class="current"><a href="#page1">Home</a></li>
<li><a href="#page3">Replies</a></li>
...
-, , loadPage().
var hash = window.location.hash;
if( !hash || hash === '#' )
hash = "#page1";
loadPage( hash );
+2
:
$('ul a').click(
function(){
$('.current').removeClass('current');
$(this).addClass('current');
return false;
}
);
:
idul, ( )ul,- , - (
a)ul,current. , , , , .
:
ul a id ( , ), "", jQuery .
$('#navigation a').click(
function() {
$('.current','#navigation').removeClass('current');
$(this).addClass('current');
return false;
}
);
, @Alec, id , .current, .
+1