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

Setting up a connection between an Express server and a Mongoose database in

As someone who is relatively new to the express framework and mongoose database, I have mainly worked with relational databases in the past. I am attempting to create a database using the script below. Currently, mongod.exe is running and listening on loca ...

What causes the picturesArray to remain consistently void?

const fetch = require("node-fetch"); let images = []; fetch('http://www.vorohome.com//images/assets/159314_887955.png') .then(response => response.buffer()) .then(buffer => { const data = "data:" + response.headers.get ...

What are the steps for implementing the Ionic 2 Pulling Refresher feature in my application?

Hey everyone, I'm currently working on developing a mobile app using AngularJS 2/Ionic2. I am facing an issue with implementing a pull-to-refresh feature in my app. We followed the steps outlined in this link, and while we were able to get the page to ...

What steps can I take to create a textbox that expands as more text is

Looking to create a unique textbook design that starts out with specific width and height dimensions, but expands downward as users type beyond the initial space. Wondering if CSS can help achieve this functionality? In a standard textbox, only a scroll ba ...

What are the steps to utilize vue.js for dynamically adjusting my sidebar based on a URL input?

Greetings to the amazing community of Vue.js enthusiasts, I am a novice looking to develop a single-page web application using vue.js. This application will consist of a fixed header and dynamic body content that changes based on user interactions. Here&a ...

Not all databases are retrieved in the search query

When I make an API call to get all the Database entries, I am encountering an issue. The response I receive only includes a few databases instead of all of them. async function checkDatabases(item){ if(item.object == 'database') ...

Tips for converting file byte code to file form data

From one folder I am retrieving a file and uploading it to another server. However, when I extract the file from the first folder, I receive a byte code representation of that file. The API for uploading the file to the second folder requires FormData as a ...

What is the process for setting up the Google Maps API within an Angular application without relying on any directives

Currently, I am attempting to integrate Google Maps into the application that I am developing. Utilizing the Places API for certain functionalities has been successful thus far. However, I have encountered an issue when trying to display a map on a specifi ...

Using a nested loop in Javascript to fetch JSON data

My goal is to display Categories and their corresponding subcategories in a specific order. However, my current method of using loops within loops is not producing the desired outcome: Category(Mobile) Category(Laptop) Subcategory(Iphone4) Subcategory(Iph ...

Identify Pressed Shift Key Direction - Leveraging JQuery

I am currently working on a web application that requires users to enter capital letters. However, I want to restrict them from using the right shift key for certain keys like a, s, d, f and the left shift key for h, j, k, l in order to detect whether they ...

Creating a CSS auto center for elements, with a unique twist

I have a design layout like this: Click here to view the image My auto-centered content is styled with the following CSS: width: 960px; margin: 0px auto; Within this auto-centered content, there is a DIV element that needs to span the full width of the ...

Encountering 404 errors when reloading routes on an Angular Azure static web app

After deploying my Angular app on Azure static web app, I encountered an error. Whenever I try to redirect to certain routes, it returns a 404 error. However, if I navigate from one route to another within the app, everything works fine. I have attempted t ...

What are the specifications for the opacity, width, and height of the background image in Bootstrap's

My current project has specific requirements that I need assistance with: I need the background image of the jumbotron to fit the width of the page and have its height scaled proportionally. The opacity of the jumbotron's background image should be ...

A tutorial on allowing a background element to capture the click event triggered by a foreground element

Within a container div, I have a background and foreground div. I want the click event on the foreground div to be passed through to the background div for handling the event. How can this be achieved in Angular 2+? Here is an example structure of my div ...

Refresh WebPage automatically after a Servlet successfully uploads and processes an image

I have a webpage that includes an image and a button. When the button is clicked, it uploads the image by submitting a form to a file upload servlet. However, after successfully uploading the image, the servlet does not display it in the img tag. Here is ...

The hidden Material UI Collapse component is still occupying space on the page

Currently, I am implementing Material UI Collapse in my React project and encountering an issue where it is causing unnecessary space on the interface when hidden <Collapse in={false}> //content here </Collapse> Even though I have not a ...

The issue with 'DemoCtrl' defined in Angular JS is that it does not correspond to a valid argument

signup.html <div ng-controller="UniqueCtrl" layout="column" ng-cloak="" class="md-inline-form inputdemoBasicUsage" ng-app="inputBasicDemo"> <md-content md-theme="docs-dark" layout-gt-sm="row" layout-padding=""> <div> <md- ...

Troubleshooting: Angular 6 Renderer2 Issue with Generating Dynamic DOM Elements for SELECT-Option

Currently, I am attempting to dynamically create a select option using Renderer2. Unfortunately, I am facing difficulties in creating the <Select></Select> element, but I can confirm that the <options> are being successfully created. Due ...

Creating an array of multiple divs based on numerical input

I am working on a project to show multiple divs based on the user's input number. For example, if the user selects 3, then 3 divs should be displayed. While I have successfully implemented this functionality, I need to dynamically assign IDs to each ...

Error is being returned by the JSONP callback

Looking to grasp JSONP. Based on my online research, I've gathered that it involves invoking a function with a callback. Other than that, is the way data is handled and the data format similar to JSON? I'm experimenting with JSONP as shown below ...