Limit jQuery script to operate exclusively on a single page

Despite the abundance of answers to similar questions, my lack of JS skills hinders me from implementing them in my specific case. On my WordPress site, I have a script that changes the navigation bar's color when scrolling down to the #startchange CSS ID.

jQuery(document).ready(function( $ ) {      
   var scroll_start = 0;
   var startchange = $('#startchange');
   var offset = startchange.offset();
   $(document).scroll(function() { 
      scroll_start = $(this).scrollTop();
      if(scroll_start > offset.top) {
          $('#main-header').css('background-color', 'rgba(28, 48, 64, 0.4)');
       } else {
          $('#main-header').css('background-color', 'transparent');
       }
   });
});

While this setup works flawlessly on the landing page, it poses an issue on blog post pages where the background is white, rendering the navbar invisible. How can I modify this script to only work on the landing page or apply a certain CSS class to blog post pages?

Answer №1

To implement this, consider adding the script directly to a specific page (there may be a suitable plugin for this task, such as Elementor which allows you to insert a javascript block).

Alternatively, you can enclose it in an if statement that verifies the presence of the required page-id-## class:

jQuery(document).ready(function( $ ) {    
  // replace the XX with your page id
  if (document.body.classList.contains('page-id-XX')) { /
    var scroll_start = 0;
    var startchange = $('#startchange');
    var offset = startchange.offset();
    $(document).scroll(function() { 
       scroll_start = $(this).scrollTop();
       if(scroll_start > offset.top) {
           $('#main-header').css('background-color', 'rgba(28, 48, 64, 0.4)');
        } else {
           $('#main-header').css('background-color', 'transparent');
        }
    });
  }
});

Answer №2

To check the page path in an if statement, you can do the following:

if (window.location.pathname === '/example/path')
{

}

Answer №3

To achieve a similar effect without using Wordpress, you can simply implement the JS code on the specific page where you want it to be displayed.

jQuery(document).ready(function( $ ) {    
   var pageName = location.pathname.substring(location.pathname.lastIndexOf("/") + 1);
   if(pageName != null && pageName.toLowerCase() == "somepagename.php") {
       var scroll_start = 0;
       var startchange = $('#startchange');
       var offset = startchange.offset();
       $(document).scroll(function() { 
          scroll_start = $(this).scrollTop();
          if(scroll_start > offset.top) {
              $('#main-header').css('background-color', 'rgba(28, 48, 64, 0.4)');
           } else {
              $('#main-header').css('background-color', 'transparent');
           }
       });
   }
});

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the best way to add JSON data received from an AJAX response to multiple classes?

Currently, I am honing my skills in jquery and have hit a bump in the road. I am receiving JSON data from a fantasy football API and am trying to map over the data to assign each team owner and name to their own div. My main query revolves around how I can ...

What is the best way to create pages that showcase 10 posts each?

Currently, I am facing a challenge with displaying 100 posts using the Fetch API on one single page. I am looking for a way to create separate pages where each page would showcase only 10 posts. Below is my existing JavaScript code: fetch('htt ...

Having trouble displaying SVG elements in Material UI

Currently, I am faced with an issue while trying to display a .svg file in the header of a drawer using Material-UI and create-react-app. Instead of the expected .svg image, all I see is a broken image rendering. Any assistance on resolving this problem ...

Angular's jQuery timepicker allows users to easily select a

Transitioning from jQuery to Angular, we previously utilized the for selecting times due to Firefox not supporting HTML5 input time. While searching for a similar timepicker plugin for Angular to maintain consistency with our past data and styles, I came ...

How to link a CSS file from a JavaScript file

I have a form for users with fields for first name, last name, password, and confirm password. I've implemented validation to check if the password and confirm password fields match using JavaScript: $(document).ready(function() { $("#addUser").cl ...

Creating an arrow icon alongside a pseudo:hover::before element

This is my custom code snippet: .privacycheck1 { position: relative; top: 265px; background-color: #CF0000; width: 24px; height: 24px; left: 843px; border-radius: 50px; border: 5px #E60000; } .privacycheck1::before { position: relative ...

Getting the badge value of a button in Angular JS is a simple process that involves accessing

How can I retrieve the badge value of a Button? This badge represents data-text-as-pseudo-element and I am new to Angular. Can someone guide me on how to achieve this? <style type="text/css">[data-text-as-pseudo-element]::before { content: ...

Issue with Jquery event not triggering correctly following ajax data retrieval

This script uses jQuery and Ajax to populate a navigation bar with categories and subcategories dynamically. The first unordered list is static, while the second one is populated after receiving data via Ajax. There are some jQuery events that need to be i ...

Generating the data section of $.ajax on the fly

I am trying to dynamically construct the data string, but I'm encountering an issue where it's treating the param variable as a plain string instead. var parameters = "{foo: 'test'}"; $.ajax({ url: 'test.php', ...

What is the best way to maintain a div centered when the browser window shrinks smaller than the div's dimensions?

Is there a way to keep a div centered and create white space around it when the browser window is resized? I want this effect to happen whether the browser window gets larger or smaller. Currently, when the window size decreases, the left side of the div l ...

Forwarding to a specific webpage

`<!DOCTYPE html> <html class="no-js"> ... </body> </html> I'm in the process of developing a website where users can enroll in programs by clicking on an ...

Create an animated hamburger menu using Tailwind CSS and Angular framework

Within my Angular project, I have successfully integrated Tailwind UI to handle the opening and closing of the hamburger menu by utilizing the code below: <header> <div class="-mr-2 -my-2 md:hidden"> <button type="button ...

Is there a method in ASP MVC to generate an object dynamically within the view that corresponds to the model and can be mapped to input fields for sending via Ajax?

Details of the Model: public class MyDerived: Base { public string FirstName { get; set; } public string LastName { get; set; } } Description of Controller's Action Method: [HttpPost] public ActionResult Add(MyDerived obj) { if (ModelSt ...

Display user input within a modal dialogue box

I have a subscription form that requires users to enter their name and email address. After clicking on "Compete Now," a pop-up appears asking for workshop information and postal code. The form is functioning correctly as intended. However, I want the em ...

The contact form is encroaching on the footer

The issue arises when the contact form overlaps with the footer. When testing the code on Codepen, the styles are correctly linked and working for everything except the contact form. I have attempted adjusting the padding, bottom position, etc., but nothin ...

CSS Flexibility

Greetings everyone, it's been a while since I dabbled in web development. I recently worked on my site with the intention of making it responsive using flexbox. This is my first time posting here, so please guide me on how to seek help more effective ...

I have noticed that the brand section of the navigation bar changes to black when I hover over it, but I have been unable to locate any

I'm currently working on a Rails application that has a navbar-top with a brand element. However, I've encountered an issue where the background of the brand element turns black when I hover over it. Despite inspecting the browser console, I coul ...

Having trouble with Jquery .ajax not properly sending data in an asp.net mvc website? Formcollection showing up empty?

Here's the jquery code I'm using to submit my form (with id "#myForm"): $(document).ready(function() { $("#my_form").submit(function(event) { $.ajax( { type: "POST", url: $("#my ...

Refresh the counter on WordPress database using an AJAX request

I am in the process of tallying votes on my website. When a user submits the form, I would like to make an ajax call that updates the total number of votes displayed at the bottom of the page. To achieve this, I am counting the number of rows in a table wi ...

Leveraging jQuery.css for retrieving values in Internet Explorer

I need to assign a variable to the value of the border-color property of my div errorChartColorError = $('.col__item.error').css('border-color'); Although this code works fine in Chrome, Internet Explorer 11 returns it as undefined W ...