Using jquery to add / remove class based on body id

I am not a javascript master, but I need to create a script that will do the following.

If body id = "index" add the class "current-selected" for tag binding, where href = index.php If body id = "services" add class = "current-selected" for tag binding, where href = services.php and other

It makes sense? Can anyone help?

Thanks if you can!

Web Design Abbotsford

+4
source share
4 answers

Based on Using Jquery to add / remove a class based on body id :

var bodyID = $('body').attr('id'); $("a[href$='" + bodyID + ".php']").toggleClass('current-selected'); //add/remove 

OR

 $("a[href$='" + bodyID + ".php']").addClass('current-selected'); //add 

Instead of "=" we use the syntax "$ =" (referring to the syntax "href $ ="), which will correspond to the end of the line, so both "index.php" and "/index.php" will correspond to "index.php".

To implement it on your site, you need to run the above code inside the jQuery ready function, so all the HTML code under the script block is loaded before Javascript performs the actions on it:

EDIT: this works for all the main / top navigation links for your site (the href matching string is the last segment of the URL path):

 <script type="text/javascript"> $(document).ready(function(){ page = window.location.pathname.substring(1).replace(/\//g,''); $("a[href*='" + page + "']").addClass('current-selected'); }); </script> 
+2
source

Something like this should do the trick. This will dynamically determine your body element id and change all anchor tags that reference the php file with the same name.

 var bodyID = $("body").attr("id"); $("a[href='" + bodyID + ".php']").addClass("current-selected"); 


As noted in another comment, use the .removeClass("current-selected") function to do the opposite.

Also, if your URL ends with "index.php", that is, the href attribute is set to /something/index.php, use " a[href$='" + bodyID + ".php'] " as your selector. This will match the href values ​​that end with the file name.

+4
source

Assuming that your body id will not always perfectly match the file name of the corresponding link, you can do it this way.

 $("body#index a[href='index.php']").addClass("current-selected"); $("body#service a[href='service.php']").addClass("current-selected"); 

If your identifier for your body will always match your corresponding href link value, you can first extract the body identifier and use it as a variable in the jQuery selector:

 var body_id = $("body").attr("id"); $("a[href='"+body_id+".php']").addClass("current-selected"); 
+1
source
 $('body#index a[href="index.php"]').addClass("current-selected"); $('body#services a[href="services.php"]').addClass("current-selected"); 
0
source

All Articles