javascript - Alternate text colors several times within specified color ranges

Seeking assistance with changing the text color multiple times from #627CA9 to #FFFFFF and vice versa.

Here's what I've tried:

function changeColor(id) {
  var x = document.getElementById(id);
  if (document.getElementById(id).style.color = "#627CA9")
    document.getElementById(id).style.color = "#FFFFFF"
  else {
    document.getElementById(id).style.color = "#627CA9"; // forecolor
  }

}
<div style="cursor: pointer;" onclick="changeColor('myid1'); return false;" id="myid1" class="centered">CHVRCHES</div>
<div style="cursor: pointer;" onclick="changeColor('myid2'); return false;" id="myid2" class="centered">PVRIS</div>

The color change script only executes once.

(Apologies for any language barriers)

Thank you.

Answer №1

One thing to note is that the color is being assigned using "=" instead of being checked with "==", and it is being set in RGB format. However, checking against this RGB format seems to be effective. Here is the updated code:

function changeColor(id) {
  var x = document.getElementById(id);
  
  if (x.style.color != "rgb(255, 255, 255)")
    x.style.color = "#FFFFFF";
  else {
    x.style.color = "#627CA9"; // forecolor
  }

}
<div style="cursor: pointer;" onclick="changeColor('myid1'); return false;" id="myid1" class="centered">CHVRCHES</div>
<div style="cursor: pointer;" onclick="changeColor('myid2'); return false;" id="myid2" class="centered">PVRIS</div>

Answer №2

The issue lies in the code

document.getElementById(id).style.color = "#627CA9"
should be corrected to
document.getElementById(id).style.color == "#627CA9"
, Also, it is recommended to use classes and update the class name

function changeColor(id) {
  var x = document.getElementById(id);
  if (x.className === "white") x.className = "";
  else x.className = "white";
}
div {
  color: #627CA9;
}

.white {
  color: #FFFFFF;
}
<div style="cursor: pointer;" onclick="changeColor('myid1'); return false;" id="myid1" class="centered">CHVRCHES</div>
<div style="cursor: pointer;" onclick="changeColor('myid2'); return false;" id="myid2" class="centered">PVRIS</div>

The same effect can be achieved automatically using CSS

@keyframes color-change {
  0% {
    color: #627CA9;
  }
  50% {
    color: #FFFFFF;
  }
  100% {
    color: #627CA9;
  }
}

.change-color {
  animation-name: color-change;
  animation-duration: 0.5s;
  animation-iteration-count: infinite;
  animation-timing-function: ease-in-out;
}
<div class="change-color">CHVRCHES</div>

Answer №3

It is important to compare values rather than simply assign them. When checking conditions, use two equal signs.

if (document.getElementById(id).style.color == "#627CA9")

UPDATE: Typically, when applying colors using JavaScript, they are converted to RGB format, making further comparison with HEX values not feasible. Therefore, comparing and setting values in RGB format is not recommended. The preferred approach would be to create an additional class and style it using CSS. This way, you can easily check for the presence of a class on an element and add or remove it accordingly.

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

Is it possible to deactivate a button using jQuery without changing its visibility to transparent?

In my current project, I am utilizing jQuery and exploring its unique methods. I have a scenario where I need to disable two buttons based on a specific condition: if (...condition...) { $('button#submit, #hint').prop("disabled", true); } Ho ...

Can someone provide a method to automatically align bootstrap 5 footers within a set of cards?

Trying out this HTML code in Bootstrap 5, I noticed that the third column appears longer than the first two columns: <!-- bootstrap scripts --> <script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_ ...

The functionality of Selection.modify is unfortunately limited when it comes to input and textarea elements in Firefox

Check out this demonstration (jsfiddle link): const input = document.querySelector('#input'); const textarea = document.querySelector('#textarea'); const div = document.querySelector('div'); const x = (e) => { if (e.ke ...

What steps can be taken to prevent a wrapper's CSS from affecting its enclosed elements?

My container div includes some opacity and auto height that I don't want to affect all elements within it. Is there a way to preserve the container's styles without impacting its contents? ...

PHP failing to insert data

I'm facing an issue where my PHP code is not inserting any data. I have a form that displays values, but the update code doesn't seem to be working. Can someone please help me with this problem? Here is the PHP code snippet: if (isset($_POST[&ap ...

Creating CSS-in-JS Components in React JS without External Stylesheet interference

import React, { Component } from "react"; import './navbar.css' class NavBar extends Component { render() { return ( <div> navbar content </div> ); } } export default NavBar; If I were to ...

The event listener fails to function properly in asynchronous JavaScript

The reason for the error is due to the asynchronous nature of the code, where the button is not loaded yet. Is there a solution to this issue? It's difficult to explain in words but essentially, when the window is loaded, the button is not present as ...

AJAX/PHP causing delays due to lag problems

I've been trying to implement an asynchronous call in my PHP script, but I keep running into the same issue: "Maximum call stack size exceeded." This is causing severe lag on my site and I suspect there might be a loop somewhere in my code that I just ...

What is the best way to style an image with CSS when it is not contained within a disabled parent element?

Struggling to find a way to add a hover effect to an image that is not inside a disabled element? Although it seems like the css selector below should do the trick, it doesn't quite work as expected. In this scenario, I only want the hover effect on e ...

Prevent the div from moving beyond the boundaries of its container while anim

After experimenting with a javascript image panner that I put together from various code snippets, I have decided to switch to a simpler approach. However, I need some guidance on a few things. Below is the code for the left and right buttons: <div id ...

Retrieve the data stored in an array of objects

code props.thumbnails.forEach(value=>{ console.log(value.photo.thumbnail_url); }) error TypeError: Cannot read property 'thumbnail_url' of undefined Trying to loop through props.thumbnails array and access the thumbnail_url pro ...

What steps can be taken to prevent the "unable to convert undefined to an object" error from occurring?

There seems to be an issue with some of the documents not containing the planDetails and planId properties, resulting in the error "can't convert undefined to an object." However, I need to fetch that document whether these properties exist or not. Ho ...

When incorporating "<" or ">" into a parameter value in Angular Translate and then showcasing it in a textarea with ng-model

In my Angular Translate string, I am using a parameter that can be in the form of <test>. However, when this translate is displayed in a textarea, it shows up as &lt;test&gt; instead of <test>. Is there a way to ensure it appears correc ...

Is your Ajax jQuery live search not functioning properly with JSON data?

My programming code is not functioning properly. Here is the file I am working on. When it does work, it does not display the list and gives an error in the Json file. I am unsure of the reason behind this issue. You will be able to view the error in the C ...

Validating dynamic textboxes in Angular with custom rules

Creating dynamic textboxes with *ngFor in Angular <tr *ngFor="let computer in _Computers; let i = index;"> <td>{{computer.Name}}</td><td>{{computer.Optional}}</td> <td> <input matInput [formControl] = " ...

Utilize Google Autofill to easily populate address fields in a form

I've come across several autofill address codes, but I'm looking to integrate a Post function that would allow me to post the obtained data to a PHP page. Is there anyone who can assist with the javascript or HTML code to achieve this? HTML Cod ...

React's componentDidUpdate being triggered before prop change occurs

I am working with the CryptoHistoricGraph component in my app.js file. I have passed this.state.coinPrices as a prop for this element. import React from 'react'; import axios from 'axios'; import CryptoSelect from './components/cry ...

When the route is changed, the system must execute a function to verify the authenticity of the token

When routing changes in Angular, I have a requirement to execute a function based on whether a valid token is set or not. Is there anyone who can assist me in achieving this task? In Angular 1, I used to accomplish this using $on. ...

Learn how to obtain a response for a specific query using the `useQueries` function

Can we identify the response obtained from using useQueries? For instance, const ids = ['dg1', 'pt3', 'bn5']; const data = useQueries( ids.map(id => ( { queryKey: ['friends', id], queryFn: () =&g ...

The Event of XMLHttpRequest State Transition Error

Can anyone provide assistance in troubleshooting why the code below is not functioning as expected, displaying "something negative happened" instead of the desired PHP echo alert? The JavaScript code I am using is: window.onload = function(){ var re ...