user3550879 user3550879 - 19 days ago 12
PHP Question

targeting only the home page

I have the following code which targets my navigation (adding specific classes based on window position. Using Wordpress.

js

jQuery(document).ready(function($){
$(window).scroll(function() {
var scroll = $(window).scrollTop();
if (scroll >= 250) {
$("#s-nav").addClass('s-nav-w');
$(".main-nav li a").addClass('text-w');
} else{
$("#s-nav").removeClass('s-nav-w');
$(".main-nav li a").removeClass('text-w');
}
});
});


I want to use the same navigation on all my pages. However, I want the

$("#s-nav").addClass('s-nav-w');
$(".main-nav li a").addClass('text-w');


to remain addded on all interior pages (all pages except for the home page) I was hoping I could modify the code instead of creating a seperate header.php.

Answer

A typical way to do this is to detect some object that is only on the home page and use an if to execute your code conditionally based on the lack of presence of something that is only on the home page. You don't show us your actual HTML so I will demonstrate the concept:

Supposed you had this div that only appears on your homepage:

<div id="homepage">...</div>

Then, you could use this in your jQuery:

// execute some jQuery on all pages except the home page
if (!$("#homepage").length) {
    $("#s-nav").addClass('s-nav-w');
    $(".main-nav li a").addClass('text-w');
}

Of course, you could also detect all pages that are not the homepage and reverse the logic. Either will work just fine.

If you want help with how exactly to do the homepage detection, then we'd have to know a bunch more about your HTML for the homepage and how it is different than your other pages.

Since the content for the homepage is always unique compared to the other pages, there is nearly always something unique in that page that can be identified. Or, if you control the content for the homepage separately from the other pages, you can just add an empty div to serve as the sentinel for identifying the homepage.


You can also use the path of the page:

// execute some jQuery on all pages except the top level page
// if your home page is some other path than "/", then substitute the appropriate path
if (window.location.pathname !== "/") {
    $("#s-nav").addClass('s-nav-w');
    $(".main-nav li a").addClass('text-w');
}
Comments