Is there a way to dynamically alter the background style of a div by clicking on it multiple times using Javascript?

I am attempting to create a calendar where each day changes its background color between blue and green when clicked, using JavaScript and CSS. It should function similar to a toggle feature. The default color is blue, and I have successfully made the days turn green when clicked. However, I am struggling to figure out how to change them back to blue.

Here is my current approach:

const days = document.getElementsByClassName('day')

for (let i = 0; i < days.length; i++) {
  days[i].addEventListener('click', function(e) {
    if (e.target.style.background != 'linear-gradient(#7ce8b6, #00ff2a)') {
      e.target.style.background = 'linear-gradient(#7ce8b6, #00ff2a)'
    } else if (e.target.background != 'linear-gradient(#7CB9E8, #00FFFF)') {
      e.target.background = 'linear-gradient(#7CB9E8, #00FFFF)'
    }
  });
}
.day {
  height: 10em;
  width: 100px;
  padding: 1em;
  border: 5px solid rgb(29, 29, 116);
  border-radius: 1em;
  background: linear-gradient(#7CB9E8, #00FFFF);
}
<div class="day">1</div>
<div class="day">2</div>
<div class="day">3</div>
<div class="day">4</div>
<div class="day">5</div>
<div class="day">6</div>
<div class="day">7</div>
<div class="day">8</div>
<div class="day">9</div>
<div class="day">10</div>

Answer №1

Implement a CSS class that defines a green background color, and then use JavaScript to toggle this class on each div element.

const days = document.getElementsByClassName('day');

for (let i = 0; i < days.length; i++) {
  days[i].addEventListener('click', function(e) {
    days[i].classList.toggle("green");
  });
}
.day {
  height: 30px;
  width: 30px;
  padding: 1em;
  border: 5px solid rgb(29, 29, 116);
  border-radius: 1em;
  background: linear-gradient(#7CB9E8, #00FFFF);
}

.green {
  background: linear-gradient(#7ce8b6, #00ff2a);
}
<div class="day">1</div>
<div class="day">2</div>

Answer №2

} else if (e.target.style.background != 'linear-gradient(#7CB9E8, #00FFFF)') {
  e.target.style.background = 'linear-gradient(#7CB9E8, #00FFFF)'
}

It may need to be updated to:

} else if (e.target.style.background != 'linear-gradient(#7CB9E8, #00FFFF)') {
  e.target.style.background = 'linear-gradient(#7CB9E8, #00FFFF)'
}

This will ensure that it aligns with the first if statement. I have not yet tested this code, but upon a logical reading, I noticed a potential typo.

EDIT:

<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
</head>
<body>
<style>
.day {
  height: 10em;
  width: 100px;
  padding: 1em;
  border: 5px solid rgb(29, 29, 116);
  border-radius: 1em;
  background: linear-gradient(#7CB9E8, #00FFFF);
}
</style>

<div class="day">1</div>
<div class="day">2</div>
<div class="day">3</div>
<div class="day">4</div>
<div class="day">5</div>
<div class="day">6</div>
<div class="day">7</div>
<div class="day">8</div>
<div class="day">9</div>
<div class="day">10</div>

<script>
const days = document.getElementsByClassName('day')

for (let i = 0; i < days.length; i++) {
  days[i].addEventListener('click', function(e) {
  alert(e.target.style.background);
    if (e.target.style.background != 'linear-gradient(rgb(124, 232, 182), rgb(0, 255, 42))') {
      e.target.style.background = 'linear-gradient(#7CE8B6, #00FF2A)';
    } else {
      e.target.style.background = 'linear-gradient(#7CB9E8, #00FFFF)';
    }
  });
}
</script>

</body>
</html>

During my testing, my browser detected the colors as RGB values. By converting the hexadecimal values into their respective RGB ranges, the issue was resolved.

Answer №3

When you select a div element, the browser displays its color in RGB format like this:

To update your code accordingly:

 const days = document.getElementsByClassName('day')

 for (let i = 0; i < days.length; i++) {
  days[i].addEventListener('click', function(e) {
  if (e.target.style.background != 'linear-gradient(rgb(124, 232, 182), rgb(0, 255, 42))') {
    e.target.style.background = 'linear-gradient(#7CE8B6, #00FF2A)';
   } else {
  e.target.style.background = 'linear-gradient(#7CB9E8, #00FFFF)';
   }
  });

Answer №4

There are a few issues with your CSS code that need to be addressed:

  1. The value of the background property should be checked through backgroundImage in JavaScript when using a linear-gradient.
  2. To check for the active background image property set via a class, you should utilize getComputedStyle().
  3. In the else if statement, you are missing the style setting part. It should be
    e.background = 'linear-gradient(#7CB9E8, #00FFFF)
    instead of
    e.target.background = 'linear-gradient(#7CB9E8, #00FFFF)
    .
  4. Keep in mind that browsers may render colors in formats other than hex like RGBA in Firefox.

Below is the corrected snippet that addresses the mentioned issues and functions as expected:

const days = document.getElementsByClassName('day')
console.clear();
for (let i = 0; i < days.length; i++) {
  days[i].addEventListener('click', function(e) {
    const style = getComputedStyle(e.target).backgroundImage;
    console.log(style);
    if (style != 'linear-gradient(rgb(124, 232, 182), rgb(0, 255, 42))') {
      console.log('green');
      e.target.style.backgroundImage = 'linear-gradient(rgb(124, 232, 182), rgb(0, 255, 42))'
    } else if (style != 'linear-gradient(rgb(124, 185, 232), rgb(0, 255, 255))') {
      console.log('blue');
      e.target.style.backgroundImage = 'linear-gradient(rgb(124, 185, 232), rgb(0, 255, 255))'
    }
  });
}
.day {
  height: 10em;
  width: 100px;
  padding: 1em;
  border: 5px solid rgb(29, 29, 116);
  border-radius: 1em;
  background: linear-gradient(rgb(124, 185, 232), rgb(0, 255, 255));
}
<div class="day">1</div>
<div class="day">2</div>
<div class="day">3</div>
<div class="day">4</div>
<div class="day">5</div>
<div class="day">6</div>
<div class="day">7</div>
<div class="day">8</div>
<div class="day">9</div>
<div class="day">10</div>

Answer №5

Utilize event delegation along with CSS.

document.querySelector('.days').addEventListener('click', ev => {
  if (ev.target.matches('.day')) {
    ev.target.classList.toggle('other')
  }
})
.day {
  height: 4rem;
  border: 1px solid blue;
  margin: 0.5rem;
  border: 5px solid rgb(29, 29, 116);
  border-radius: 1em;
  background: linear-gradient(#7CB9E8, #00FFFF);
}

.day.other {
  background: linear-gradient(#7ce8b6, #00ff2a);
}
<div class="days">
  <div class="day">1</div>
  <div class="day">2</div>
  <div class="day">3</div>
  <div class="day">4</div>
  <div class="day">5</div>
  <div class="day">6</div>
  <div class="day">7</div>
</div>

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

Problem with React Native Camera: Camera display is not functioning correctly - React-Native-Vision-Camera Error

Hey there! I could really use some help with a tricky situation I'm facing in my React Native app, specifically regarding camera integration. Here's the scoop: The Issue: I'm working on a video recording application using React Native that ...

Is Amazon altering the names of their CSS selectors and HTML elements on the fly?

For my Amazon.es web scraper built with Selenium, I am using a CSS selector to determine the total number of pages it will iterate through. However, the selector name seems to change dynamically and I must update it daily. As someone not well-versed in H ...

Extract the element when the mouse is clicked

I'm currently working on developing a Chrome extension with a specific goal in mind: My aim is to capture the username when a user Ctrl-clicks on a username while browsing Reddit, and then transfer that username from the content script page to the ba ...

A thrilling twist on the classic game of Tic Tac Toe, where X and

I am having trouble with switching between the cross and circle symbols in my Tic Tac Toe game. The code seems to be set up correctly, but it's not functioning as expected. Any suggestions on how to fix this? Here is the JavaScript code: varcode va ...

retrieving identifiers from a separate table for an array of values

As a newcomer to node and noSQL databases, I am facing challenges in grasping the concept of passing an array of IDs and retrieving the corresponding values from another table. I have 'users' and 'products' tables in my database. The st ...

Refine your search with a JSON object description in expressJS and UnderscoreJS

[ { "id": 1, "description": "Empty the garbage bin", "completed": false }, { "id": 2, "description": "Dine out for dinner", "completed": false }, { "id": 3, "description": "Exercise at the fitness center", "com ...

Guide to leveraging clsx within nested components in React

I am currently using clsx within a React application and encountering an issue with how to utilize it when dealing with mappings and nested components. For instance: return ( <div> <button onClick={doSomething}>{isOpened ? <Component ...

Smoothly transition the box shadow using CSS3's ease-in and ease-out effect

Struggling to achieve a smooth easing effect for a box shadow transition using CSS3. This is the current CSS code in use: #how-to-content-wrap-first:hover { -moz-box-shadow: 0px 0px 5px #1e1e1e; -webkit-box-shadow: 0px 0px 5px #1e1e1e; box-s ...

Custom Native Scrollbar

Currently, there are jQuery plugins available that can transform a system's default scroll bar to resemble the iOS scroll bar. Examples of such plugins include . However, the example code for these plugins typically requires a fixed height in order to ...

How do I incorporate a standalone checkbox in a React Material-UI table without affecting row selection upon clicking?

I would like to have a distinction between clicking on a checkbox and clicking on a row. Specifically, I want the following behavior: when I click on the checkbox, only the checkbox should be checked; and when I click on the row, only the row should be se ...

Increment the text counter following the uploading of an image file with html format

I have a form in which I am checking the character limit that a user can input into a text field using the 'onkeyup' attribute to update it in real time. Now, I want to achieve a similar function for image uploading. When a user selects an image ...

Exploring the function of variables in VueJS

I'm facing a tricky issue with VueJS as I am still getting acquainted with it. My objective is to access and modify variables within the data function, but so far, I haven't been successful. The problematic line: console.log('item: ' ...

Best practices for coding in HTML and CSS

Creating my first website for an internship has been quite a learning experience. Throughout my training, I was always advised to avoid embedding styles directly into the HTML code. However, now that I am actually developing a site, I can't help but f ...

I have encountered a node.js error related to the 'Require Stack'

Encountering an error in my node.js application when trying to open a .js file { code: 'MODULE_NOT_FOUND', requireStack: } Unable to determine the root cause of this issue I have tried re-installing Node.js and its packages, removed and added b ...

Using jQuery, set a restriction on the total number of options in three dropdown menus to

I am currently facing a challenge with 3 dropdowns, each containing 8 options. My aim is to restrict the total selection across all three dropdowns to 8. For instance, if I choose 7 in the first dropdown, I should only be able to pick 1 in the next two. Si ...

I am currently working with a for loop within an object in JavaScript, but there seems to be a problem with one

Here is a function called validator: import validator from "validator"; import isEmpty from "is-empty"; export default function validate(data) { const errors = {}; for (const property in data) { console.log(property); //< ...

How can I display SQL results in a Jade page using Node, Express, and MySQL?

My application built with Node.js and Express is connected to a MySQL database for monitoring purposes. The code structure is as follows: In the Node file: app.get('/banners', function(req,res){ connection.query("SELECT * FROM banner_store_ ...

Display additional javascript code for expanding a marquee

Currently, I am working on a stock ticker project using JavaScript. It's progressing well, and now I am focusing on adding a "show more" button to style the ticker. The button should be placed outside of the marquee. When clicked, it will expand the m ...

Having trouble with Vue component not showing updated data after axios POST request issue

Hi there, I'm facing an issue and could really use some guidance from a skilled Javascript Wizard. Here's the problem: I have a Laravel collection that I'm passing to a Vue component. Within the component, I am looping through the collecti ...

What is the most effective method for dimming or disabling a Material-UI div?

Within my application, there are instances where I need to dim and disable the mouse events for certain div elements based on the component's state - such as when it's loading. My initial approach involved creating a helper function that generate ...