Use jQuery to dynamically alter color based on conditional statements

What could be causing the background color not to change to green?

var id;
id = setInterval(changeColor, 1000);

function changeColor(){
  var elem= $("#target");         

  var color = elem.css('background-color');
  if (color == 'rgb(255,0,0)')
    elem.css('background-color','green');
  else
    elem.css('background-color', 'red');
}

Answer №1

Give this a shot:

let timerId;
timerId = setInterval(alterBackground, 1000);

function alterBackground(){
  let targetElement= $("#target");         

  let backgroundColor = targetElement.css('background-color');
  if (backgroundColor == 'rgb(255, 0, 0)')
    targetElement.css('background-color','green');
  else
    targetElement.css('background-color', 'red');
}

The if statement was checking the wrong condition: 'rgb(255,0,0)' instead of 'rgb(255, 0, 0)'

Answer №2

Consider using rgba instead of rgb for better color transparency.

<html>

<head>
    <title>Adjust Color</title>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>

    <script>
       function adjustColor(){
            var target= $("#box");         
        
            var backgroundColor = target.css('background-color');
            
            if (backgroundColor == 'rgba(0, 0, 0, 0)')
                target.css('background-color','lightblue');
            else
                target.css('background-color', 'orange');
           
        }

        $(document).ready(function () {
            var intervalID;
            intervalID = setInterval(adjustColor, 1000);
        });
    </script>
</head>

<body>
   <div id="box">Welcome to Frontend Development!!!</div>
    <!--.row-div -->


</body>

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

A guide on how to reset Orbit Controls once the target has been defined

After clicking the mouse, I successfully set a new target for my THREE.OrbitControls and it works perfectly. However, once the camera pans to the new location, I lose all mouse interaction. I suspect that I may have broken the controls when I made the came ...

The Chrome extension is unable to add text to the existing window

Lately, I've been attempting to develop an extension that will automatically add a div to the beginning of the current page. I've been following the guide provided on this https://developer.chrome.com/extensions/activeTab page. The code from the ...

incorrect calculation of date difference using momentjs

Currently utilizing countdown.js for a project where I need to add 60 days to a date fetched from the database. Successfully implemented this in the targetDay variable and it's functioning properly. However, when attempting to calculate this date fro ...

Tips for dynamically inserting a tabbed element into a list using AngularJS

I am trying to dynamically add elements with tabs in the list, but I encounter a problem where the device info gets overridden from the last user. You can see the issue here: This is how my Tabs item looks like in HTML: <div class="sample tabsdemoDyn ...

CSS: Adjusting alignment differences between local host and server

I've been working on a webpage with rotating background images, and everything looked perfect on my localhost. But once I uploaded it to the server and viewed it in different browsers, some of the people in the images were not positioned as intended, ...

Building a contact form in Angular and sending emails with Nodemailer

Currently, I am in the process of setting up a contact form for my website. Since I am utilizing a MEAN stack, it made sense to incorporate the nodemailer module for sending emails. In order to handle this functionality, I have established an endpoint &ap ...

Switch from using `widthWidth` to `useWidth` in MUI v5 ReactJS

Currently, I am in the process of updating a project that utilizes MUI as the UI Library for my React application. I have started migrating to version 5 today, and one issue I've encountered is related to all functional components wrapped by withWidth ...

Ensure the first column is fixed and all other columns have the same height

I have encountered an issue where the first column of my table has varying heights compared to the other columns, resulting in inconsistent row heights. Below is the code I am using: <div class="outer"> <div class="inner"> <table> ...

What is the proper way to safely escape a JSON string for an object that contains user-generated content?

How can I correctly use the variable s for the value-field of an option-element while escaping user input used for key and value? var key='highway'; var value='track'; var s = JSON.stringfy({ [key]:value }, undefined,''); s ...

creating a fresh instance of a class while in a subscribe method

Although this code is functional, it briefly displays incorrect data because a blank token is instantiated before being populated in the subscribe function. Is there a way to move the instantiation into the subscribe function or provide all necessary par ...

Could you provide instructions on how to change mjs files into js format?

Is there a method to change .mjs files to .js files? Some hosting services do not yet support mjs files, so I am interested in converting them to js files. Context: Mozilla's PDFjs has incorporated JavaScript modules (mjs) into their code, but since ...

Executing a function immediately upon the start of a new month in JavaScript (Node.js) without relying on any external libraries?

Is it possible to automate the process of creating a document in MongoDB using Mongoose every 1st of a new month, ideally as soon as the date changes without relying on third-party libraries like needle or cronjob? Can this be achieved solely with setInter ...

Trouble with CSS positioning

Styling with CSS: .one { width: 13%; } .two { width: 30%; } .three { width: 30%; } Formatting in HTML: <table> <tr> <th class= "one">Quantity</th> <th class= "two">Info</th> ...

HTML forms are larger in size on web pages than in Internet Explorer

https://i.stack.imgur.com/bUPtm.png I have posted the issue, and it is predominantly visual in nature. When viewed on a web browser within a C++ interface, the HTML appears significantly distorted. ...

What is the best method for generating a vertical tab using JavaScript in a paragraph format?

Struggling to create a menu similar to this using bootstrap 4. Despite my efforts, I keep encountering various issues. Is there someone who can help me solve this problem? Remember, I am using bootstrap 4. Here is a demo: <!doctype html> <html ...

What could be causing my completed torrents to sometimes not be saved to my disk?

Currently, I am working on developing a small torrent client using electron and webtorrent. Although everything appears to be functioning correctly initially, there is an issue where sometimes the resulting files from a finished download are not being save ...

The performance of HTTP requests is significantly decreased in Internet Explorer compared to expected speeds

I am currently developing an Angular site where I need to send a significant amount of data (approximately 1 MB) in an API call. In the Chrome and Firefox browsers, everything works smoothly and quickly, with a response time under one second. However, whe ...

What is the process for creating a login page that redirects automatically?

For instance: Whenever I enter gmail.com, it automatically takes me to this link: https://accounts.google.com/signin/v2/identifier?service=mail&passive=true&rm=false&continue=https%3A%2F%2Fmail.google.com%2Fmail%2F&ss=1&scc=1&ltmp ...

Using jQuery to select the child element of the parent that came before

Recently, I've been experimenting with creating animations using CSS and jQuery. While it has been successful so far, I'm now looking to take it a step further. Specifically, I want information to appear on top of an image when the user clicks on ...

Starting http-server in the background using an npm script

Is there a way to run http-server in the background using an npm script, allowing another npm script, like a Mocha test with jsdom, to make HTTP requests to http-server? To install the http-server package, use: npm install http-server --save-dev In your ...