Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery add class based on page URL

I have what I think is a simple question but I can't get it to work for the life of me.

All I want to do is add some javascript to the page that adds a class to the main page container based on the URL.

Let's say I have a site at root.com and the following html structure (loosely speaking):

<html>
  <head>
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
  </head>
  <body>
    <div id="main" class="wrapper">
      Blah, blah, blah
  </body>
</html>

What I want to do is a script that, if the page = (for example) root.com/technology, it adds a class to the main div. So the div would now look like:

     <div id="main" class="wrapper tech">

I've loaded jquery, so I'd like to do it that way.

like image 880
Matt Martin Avatar asked Apr 02 '12 20:04

Matt Martin


People also ask

How do I add active class to UL Li?

on('click','li',function(){ $(this). addClass("active"); // adding active class }); The above code will add the active class to the li tag whenever the user clicks on the Li element.


2 Answers

You can use window.location to get the current URL, and then switch based on that:

$(function() {
  var loc = window.location.href; // returns the full URL
  if(/technology/.test(loc)) {
    $('#main').addClass('tech');
  }
});

This uses a regular expression to see if the URL contains a particular phrase (notably: technology), and if so, adds a class to the #main element.

like image 72
Alex Vidal Avatar answered Sep 23 '22 16:09

Alex Vidal


would something like below help? based on other answer, just by doing

console.log(window.location)

, you can wealth wealth of information related to your location object

     if(window.location.href=== "root.com/technology") {
         $("#main").addClass("tech");
     }
like image 37
DG3 Avatar answered Sep 21 '22 16:09

DG3