MAR
MAR

Reputation: 613

Applying CSS using jQuery on specific body class only

WordPress top navigation menu is pushed by the logo element a little too much to the right. What I wanted to do was to get the logo width on page-load, and add a negative left margin to the menu set at half the width of the logo. I did so successfully by applying the following:

jQuery(document).ready(function($){
    var logoWidth = $('img#logo').width();
    var logoWidthMargin = logoWidth / 2;
        $('nav#top-menu-nav').css("margin-left", - logoWidthMargin);

});

Here's the HTML:

<body class="some-class1 some-class2 some-class3">
   <div id="page-container">
      <header id="main-header">
         <div class="container">
            <div class="logo_container">
               <img src="logo.png" id="logo"/>
            </div>
            <div id="top-navigation">
               <nav id="top-menu-nav">
                  <ul id="top-menu" class="nav">
                     <li id="menu-item">Menu Item</li>
                     <li id="menu-item">Menu Item</li>
                     <li id="menu-item">Menu Item</li>
                  </ul>
               </nav>
            </div>
         </div>
      </header>
   </div>
</body>

Now the thing is, I want to be able to disable this on specific pages. The body tag has multiple classes, and I'd like to somehow make it so that on a page in which the body tag has a certain class, this script will not run.

For instance - I want the script to keep running on all pages as it does now - but once there is a page in which the body tag has "some-class2" (in addition to the other classes), the script won't run. How can I do so?

Also - bonus question - I'm quite new to js and jquery, and wrote that code above by trial and error till it worked, but is there a more efficient way to achieve the same? I mean, the whole defining a variable to get the width of the logo and then defining another variable to get half of that width seemed to be a bit excessive, I'm sure there's a shorter way which I couldn't figure out...?

Upvotes: 0

Views: 54

Answers (1)

T.J. Crowder
T.J. Crowder

Reputation: 1074248

Now the thing is, I want to be able to disable this on specific pages. The body tag has multiple classes, and I'd like to somehow make it so that on a page in which the body tag has a certain class, this script will not run.

Check for the class:

if (!$("body").hasClass("the-class")) {
    // run the script
}

In situ:

jQuery(document).ready(function($){
    if (!$("body").hasClass("the-class")) {
        var logoWidth = $('img#logo').width();
        var logoWidthMargin = logoWidth / 2;
        $('nav#top-menu-nav').css("margin-left", - logoWidthMargin);
    }
});

If the logo has a known width (and it probably does, if you look at the CSS for it), you can also do this just with CSS:

body:not(.the-class) #top-menu-nav {
    margin-left: -32px; /* Assuming the logo is 64px wide */
}

Upvotes: 3

Related Questions