Change the CSS element if the current URL is not example.com/page1 or example.com/page2

When I apply the following JS code snippets, my output is incorrect or does not display at all. Below are the codes in question:

if (location.href != "website.com/page1" || "website.com/page2")
   {
     element.style.backgroundColor='none';
   }

Alternatively with != and !==

if (location.href != "website.com/page1" || location.href != "website.com/page2")
   {
     element.style.backgroundColor='none';
   }

This is how I am integrating it with other code (simplified)

<script>
var element = document.getElementbyId('idElement');

if (location.href != "website.com/page1")
   {
     element.style.backgroundColor='blue';
   }
if (location.href != "website.com/page2")
   {
     element.style.backgroundColor='green';
   }
 //THIS IS WHERE I INSERT THE CODE
if (location.href != "website.com/page1" || "website.com/page2")
   {
     element.style.backgroundColor='none';
   }
 </script>

Nothing changes or the element malfunctions on different pages. What could be the issue?

Additional Information: I am designing a Tumblr theme where certain posts will have different characteristics when viewed on various pages. The code needs to be placed at the top.

A Suggested Solution That Worked:

<script>
window.onload = function ()

 var element = document.getElementbyId('idElement');

 if (location.href != "website.com/page1" && location.href != "website.com/page2") 
    {
       element.style.backgroundColor='none'; 
    } 
  if (location.href == "website.com/page1") 
    {
       element.style.backgroundColor='blue'; 
    }
  if (location.href == "website.com/page2") 
        { 
       element.style.backgroundColor='green'; 
    }

</script> 

Answer №1

Aside from the obvious syntax error (such as forgetting to close a quotation mark after website.com/page2), there are some steps you can take to refine this further.

One suggestion is to store location.href in a variable and convert it to lowercase to ensure accurate comparison:

var currentLocation = location.href.toLowerCase();

The logic in your code is somewhat convoluted... first checking for page1, then page2, and finally defaulting to no color if neither match. This final step may be causing the issue along with the syntax errors. Keep in mind that when evaluating the line:

if (location.href != "website.com/page1" || "website.com/page2)

You are essentially saying "if location.href is not equal to page1 OR if 'website.com/page2' string exists."

To properly check both conditions, consider revising to:

if (location.href != "website.com/page1" && location.href != "website.com/page2")

Update your script with something like the following:

var element = document.getElementById('idElement');
var currentLocation = location.href.toLowerCase();

// Store color value in a variable
var backgroundColor = "none"; 

if (currentLocation != "website.com/page1") {
    backgroundColor = 'blue';
}
if (currentLocation != "website.com/page2") {
    backgroundColor = 'green';
}
// Update condition to include both pages
if (currentLocation != "website.com/page1" && currentLocation != "website.com/page2") {
    backgroundColor = 'none';
}

element.style.backgroundColor = backgroundColor;

Answer №2

Make sure to close your if statements properly.

Instead of writing it like this:

if (location.href != "website.com/page1" || "website.com/page2)

You should write it like this:

if (location.href != "website.com/page1" || "website.com/page2")

Also, instead of this:

if (location.href != "website.com/page1" || location.href != "website.com/page2)

It should be written like this:

if (location.href != "website.com/page1" || location.href != "website.com/page2")

If the issue persists, consider adding this at the beginning of your function.

alert(location.href);

Check what the value of location.href actually is.

Edit

Rather than this:

(location.href != "website.com/page1" || "website.com/page2")

Change it to look like this:

(location.href != "website.com/page1" || location.href != "website.com/page2")

We're making progress!

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

"Using Vue 3 to teleport content to a specific element and swap out existing

I've successfully implemented the use of Vue 3 teleport to display elements within a div. Although teleport adds items to the specified element, it doesn't replace existing elements in the div. Is there a way to configure teleport to replace th ...

What strategies can be used to avoid a single dangling word at the end of a line within an HTML element?

I am in the process of developing a straightforward webpage with marketing content. One aspect I find unfavorable is when a line of text stretches too long and breaks onto the next line, which is acceptable; however, it often splits in a manner where there ...

CSS code for vertical navigation arrows to remain on both the left and right sides of the webpage

I'm struggling a bit with the CSS. I want to recreate the same effect as seen on . The left and right navigation arrows stay fixed vertically even when scrolling up or down the page. Does anyone have any code examples for that? ...

The code functions properly on a standalone device, however, it encounters issues when

I am facing an issue with my JavaScript code. It works perfectly fine when I run it on my local machine, but once I upload it to the server, it only functions properly after I refresh the page. Below is the code in question. Please do not hesitate to rea ...

Refresh Material-Ui's Selection Options

Is there a way to properly re-render the <option> </option> inside a Material UI select component? My goal is to transfer data from one object array to another using the Material UI select feature. {transferData.map(data => ( <option ...

Oops! It looks like there was an error. Remember that AJAX events should be connected to the

I am completely new to the world of Ajax and unfortunately, I encountered an error message in my browser: "JQMIGRATE: AJAX events should be attached to document: ajaxComplete" After some research, it seems like I need to incorporate certain Ajax functi ...

Understanding the use of "el" in a function parameter in Vue Js

I am new to VueJS, so please be patient with me. I am trying to code a function that will scroll to an element with a specific ID when a "?" is used in the URL. I want it to have the same effect as demonstrated here. My assignment requires me to follow a ...

React Ant Design: Encountered a warning for 2 elements having non-unique properties

I have incorporated the Carousel component, with each one containing a different component. One contains a form, while the other includes an external library component called react-input-otp. https://codesandbox.io/s/pensive-einstein-uucvm?fontsize=14& ...

Web Page Content Scrambling/Character Exchange

I've encountered a perplexing issue that seems to strike randomly, yet I've managed to replicate the problem on three different desktops. Oddly enough, some other desktops never experience this issue and I'm at a loss as to what could be cau ...

Should the use of readFileSync() during the initialization of a Node.js web application be avoided?

I have a Node app that serves web pages with static HTML-snippet files included conditionally. I am considering implementing a cache map for these snippets by adding the following code to my Express's app.js file: var cache = Object.create(null); cac ...

The `appendTo` function in Ajax is used to swap out the current element

I have been working on sending form data to a Servlet using JQuery and then receiving the response from the same JQuery. Check out the code snippet below. <%-- Document : index Created on : Feb 23, 2015, 8:18:52 PM Author : Yohan --% ...

JavaScript error: You are trying to use Array.find() in Redux, but it

I am currently developing a react native application and I am using basic redux for managing the state, although I am a complete beginner to this. In a specific issue, I am facing an issue while fetching data from my redux store in the edit screen where th ...

issue encountered while attaching css file / css styles not rendering

Here is the css link I am using: <link rel="stylesheet" type="text/html" href="/public/assets/lib/css/style.css" /> Despite trying various solutions such as removing "rel="stylesheet"", changing to "text/html", checking paths, placing it in the pu ...

What is a more efficient approach to managing the response from an asynchronous call other than using setState?

Utilizing javascript async await, I have been making service calls to the server in componentDidMount or componentDidUpdate. However, when I need to pass the response data as props to other components, I find myself updating the component's state with ...

What is the relationship between JavaScript and the height of a window?

Consider the code snippet below: 24 <script type="text/javascript"> 25 26 function UpdateDisplay($isVisible){ 27 if($isVisible) 28 $('.relatedContent').stop().css({ 29 "transform": "tr ...

Arrow function returns itself, not the function

While working with React, I've been using utility functions for managing API calls. I noticed that when the arrow function is no longer anonymous, it successfully returns a pending promise – which is exactly what I want. However, if the arrow functi ...

Error: Invalid syntax detected: /blog

I am encountering an issue with jQuery while trying to add a blog section to my existing single-page site. The new blog will be located in a separate /blog directory, causing the menu item for it to differ from the other href="#" tags on the index.html pag ...

Tips for extracting values from a PHP array using JavaScript

Assuming we have a PHP array named $decoded: $decoded = array( 'method' => 'getFile', 'number' => '12345' ); The data from this array will be passed to a JavaScript function called get(params). funct ...

What is the method for incorporating a dotted line preceding the menu options?

I am currently working on an asp.net menu that looks like this: <div id="left"> <div id="menus" runat="server"> <div id="left_menu"> <div class="abc"> < ...

Mastering Excel Automation

Hello, I am looking to download an Excel sheet that contains a macro. However, I am using a PHP script to handle the download process. Is it feasible to download an Excel sheet with a macro in PHP? ...