I have a list with 3 items, and I have made a jQuery click event to add a css class to it.
But when I click one of the items the class attribute is set but disapperas directly after.
Any ideas why?
Code:
<ul>
<li><a id="home" href="home.php">Home</a></li>
<li><a id="apps" href="apps.php">Apps</a></li>
<li><a id="support" href="support.php">Support</a></li>
</ul>
$(document).ready(function() {
$('#home').click(function (){
$(this).addClass('btnActive');
});
});
Updated Answer:
When you follow a link, the entire DOM of the page is torn down and thrown away, and replaced by the DOM created by reading the HTML of the new page. So changes you make to the old DOM don’t persist. If you want the “btnActive” class to be on the link when the page is loaded, you’ll need to modify the HTML of the
home.php,apps.php, andsupport.phppages accordingly.E.g., for
home.php:…but for
apps.php:Alternately, you could use JavaScript on page load to add the class based on the
location.href, but really it’s better to modify the HTML. But just for completeness, since you use the same value for theidof the link and the name of the page, you could do this:That isolates the name of the page from the URL (ignoring any path leading up to it, and stripping off the
.phpat the end), then uses it as anidand adds the class. Again, I don’t recommend it, but with the URLs you quoted, it should work.The following original answer was from before I realized (thanks to Rory) that you probably really do need to follow the link.
Original Answer:
Because you never tell the browser not to follow the link, so the page gets reloaded.
You can fix it by either doing
return false;out of your event handler:…or accepting the
eventargument and callingpreventDefaulton it:return falsein a jQuery event handler does two things:Prevents the default action (in this case, following the link).
Stops the event propagating to ancestor elements.
preventDefaultjust does the first one.