Modify the background of a DIV upon clicking it

Is there a way to achieve the following scenario:

I have multiple DIVS

<div style="background-color: black;">text1</div>
<div style="background-color: black;">text2</div>
<div style="background-color: black;">text3</div>
<div style="background-color: black;">text4</div>
<div style="background-color: black;">text5</div>
<div style="background-color: black;">text6</div>

Upon clicking on the DIV containing "text5," the background color should change to RED. If the same person clicks on the DIV with "text3," the background color of text5 should revert to black and text3 should turn red. This process should continue for other DIVS as well.

In summary, the background color should switch when another DIV is clicked.

Can this be accomplished using basic JavaScript?

Answer №1

To enable interaction with div elements in Javascript, ensure that each div has appropriate classes assigned and implement an `onclick` event to detect when a div is clicked. Pass the current div as a parameter using `this` to a Javascript function called from the `onclick` event.

In the `changeColour` function triggered by the `onclick`, begin by resetting all divs to their default color using `document.getElementsByClassName` to get all divs, then iterate through them to reset the color back to default.

Once the divs have been reset and control returns to `changeColour`, proceed to change the background color of the clicked-on div (passed as a parameter).

function changeColour(item)
{
    resetColour();
    item.style.backgroundColor = 'red';
}

function resetColour()
{
    var divsToReset = document.getElementsByClassName("colouredDivs");
    for(var i=0; i < divsToReset.length; i++) 
    {
         var div = divsToReset[i];
         div.style.backgroundColor = 'black';
    }
}
<div class="colouredDivs" style="background-color: black;" onClick="changeColour(this);">text1</div>
<div class="colouredDivs"  style="background-color: black;" onClick="changeColour(this);">text2</div>
<div class="colouredDivs"  style="background-color: black;" onClick="changeColour(this);">text3</div>
<div class="colouredDivs"  style="background-color: black;" onClick="changeColour(this);">text4</div>
<div class="colouredDivs"  style="background-color: black;" onClick="changeColour(this);">text5</div>
<div class="colouredDivs"  style="background-color: black;" onClick="changeColour(this);">text6</div>

Answer №2

Check out this solution that utilizes forEach() along with a traditional for loop.

Avoiding the need to include inline JavaScript events within the HTML markup.

let div = document.querySelectorAll('div');

div.forEach(function(div_current) {
  div_current.addEventListener('click', function() {
    for (var i = 0; i < div.length; i++) {
      div[i].style.backgroundColor = 'black';
    }
    this.style.backgroundColor = 'red';
  });
});
<div style="background-color: black;">text1</div>
<div style="background-color: black;">text2</div>
<div style="background-color: black;">text3</div>
<div style="background-color: black;">text4</div>
<div style="background-color: black;">text5</div>
<div style="background-color: black;">text6</div>

Answer №3

It's important to assign proper classes to your tags. This way, you can easily implement events on these elements to customize their behavior.

let tags = document.getElementsByClassName('color-tag');
for (let item of document.getElementsByClassName('color-tag')) {
    item.addEventListener('click', function () {
        for (let i = 0; i < tags.length; i++) {
            tags[i].style.backgroundColor = 'black';
        }
        this.style.backgroundColor = 'red';
    });
}
<div class="color-tag" style="background-color: black;">text1</div>
<div class="color-tag" style="background-color: black;">text2</div>
<div class="color-tag" style="background-color: black;">text3</div>
<div class="color-tag" style="background-color: black;">text4</div>
<div class="color-tag" style="background-color: black;">text5</div>
<div class="color-tag" style="background-color: black;">text6</div>

Answer №4

Utilizing a parent element would simplify the process and enable you to separate the components effectively.

document.querySelectorAll('.wrapper').forEach(wrap => {
  wrap.addEventListener('click', e => {
    e.target.parentNode.querySelectorAll('div').forEach(div => {
      div.classList.remove('selected');
    });

    e.target.classList.add('selected');
  });
});
body {
  color: #FFF;
}

.selected {
  background: red !important;
}
<div class="wrapper">
  <div style="background-color: black;">text1</div>
  <div style="background-color: black;">text2</div>
  <div style="background-color: black;">text3</div>
  <div style="background-color: black;">text4</div>
  <div style="background-color: black;">text5</div>
  <div style="background-color: black;">text6</div>
</div>

<hr>

<div class="wrapper">
  <div style="background-color: black;">text1</div>
  <div style="background-color: black;">text2</div>
  <div style="background-color: black;">text3</div>
  <div style="background-color: black;">text4</div>
  <div style="background-color: black;">text5</div>
  <div style="background-color: black;">text6</div>
</div>

An alternate method, without the use of JavaScript, could involve using tabIndex along with the :focus pseudo-class selector.

body {
  color: #FFF;
}

.wrapper div:focus {
  background: red !important;
}
<div class="wrapper">
  <div style="background-color: black;" tabIndex="1">text1</div>
  <div style="background-color: black;" tabIndex="1">text2</div>
  <div style="background-color: black;" tabIndex="1">text3</div>
  <div style="background-color: black;" tabIndex="1">text4</div>
  <div style="background-color: black;" tabIndex="1">text5</div>
  <div style="background-color: black;" tabIndex="1">text6</div>
</div>

<hr>

<div class="wrapper">
  <div style="background-color: black;" tabIndex="1">text1</div>
  <div style="background-color: black;" tabIndex="1">text2</div>
  <div style="background-color: black;" tabIndex="1">text3</div>
  <div style="background-color: black;" tabIndex="1">text4</div>
  <div style="background-color: black;" tabIndex="1">text5</div>
  <div style="background-color: black;" tabIndex="1">text6</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

Utilizing Mapbox-gl within a Vue.js single file component with Quasar-Framework integration

I'm attempting to incorporate a Mapbox-gl-js Map into a single file Vue component within the Quasar Framework, but I'm struggling to make it work. I've come across examples of Googlemaps with Vue and Mapbox with React, and I'm trying to ...

D3.js Sunbursts featuring Hierarchical Arcs that display values at each level, providing a comprehensive view beyond just the aggregate of the leaves

Hey there, Stackoverflow community! I've been working on creating a sunburst chart using the resources provided at: http://bl.ocks.org/kerryrodden/7090426. I've successfully replicated the artwork from the example, but now I'm trying to add ...

The most effective way to transmit data from an asynchronous call in Node.js while ensuring a reliable fallback routing structure

I have a request function that makes a call to an endpoint and retrieves data from it. When passing this data to an hbs template for rendering, the array is empty due to asynchronicity. Can someone guide me on the correct approach? Below is the code snippe ...

Hiding a row in AngularJS after changing its status can be achieved by utilizing the

I need help hiding a clicked row after changing its status using angularjs. Below is the code I have written, can someone guide me on how to achieve this? table.table tr(data-ng-repeat="application in job.applications", ng-hide="application.hideApplic ...

To prevent multiple requests to the server, limit the number of requests received if a user clicks on a list too quickly

I need some assistance. I have been working on tracking user clicks. The issue is that I have a list where users can click to fetch data from the server. However, when multiple users click simultaneously, it results in multiple requests being sent to the s ...

It is important for the CSS :active state to transition to an "inactive" state after a certain period of

For mobile, I utilized the :hover and :active pseudo-classes to create a transition effect when tapping on a tab that enlarges the elements for more information. However, I am seeking a way for the activated element to return to its original state after a ...

Manipulating the arrangement and alignment of div elements within a designated container

Here is the markup I am working with: <div class="container"> <div class="left-rect"></div> <div class="text">Lorem ispum</div> <div class="right-rect"></div> </div> .left-rect, .right-rect { ...

All I desire is to eliminate the term "class" from the text

Upon clicking the code, only the value 137 should display according to the image. However, the word "class" also appears. https://i.stack.imgur.com/HZhr4.png <a rel="facebox" href="portal.php?id='.$rowa["_id"].' class="icon-remove"></a ...

Encountering an issue with a React-slick slider test case - receiving an error related to the inability to access property 'querySelector

I am currently utilizing next.js for a React project and have incorporated the react-slick slider plugin successfully. However, I encountered an issue when attempting to run tests as it displayed a `TypeError: Cannot read property 'querySelectorAll&ap ...

Scouring the web with Cheerio to extract various information from Twitter

Just starting out with Web Scraping, using Axios to fetch the URL and Cheerio to access the data. Trying to scrape my Twitter account for the number of followers by inspecting the element holding that info, but not getting any results. Attempting to exec ...

The quickest regular expression match possible if it is already a subsection of another match

Is there a simple way to find the shortest match in a long text where strings are repeated? I'm having trouble because matches within already matched text aren't being found. Here's an example of the issue: Using code: "ababc".match(/a.+c ...

Activating the submit button only following confirmation that the image dimensions have been verified

I've written some code that checks whether selected pictures meet specific size and dimension constraints before enabling the submit button. However, there's an issue where the button might be enabled before verifying the last image due to delays ...

When decoding a JWT, it may return the value of "[object Object]"

Having some trouble decoding a JSON web token that's being sent to my REST API server. I can't seem to access the _id property within the web token. Below is the code I'm currently using: jwt.verify(token, process.env.TOKEN_SECRET, { comp ...

Concealing and revealing information with jQuery and AJAX

Need help hiding a Message and displaying an alert message after 5 seconds, but it's not working. What I want is for the Message to be hidden and show an alert message 5 seconds after clicking submit. <script> $(document).ready(function () { ...

Dissecting Distinct and Alphabetized Attributes in JSON/JavaScript

Below is a code snippet that retrieves and organizes a list of values from JSON data in alphanumeric order based on a specific key-value pair: var xmlhttp = new XMLHttpRequest(); xmlhttp.onreadystatechange = function() { if (this.readyState == 4 &a ...

My custom class is being ignored by Tailwind CSS within breakpoints

I'm attempting to incorporate some animation on the height property within the md breakpoint, but for some reason Tailwind CSS isn't applying my class. <div className={`h-12 bg-blue flex w-full text-white fixed mt-1 md:bg-white ${scrolling ? ...

Get the initial item from a Nested Array in JSON using NodeJS

I am attempting to extract the nested array named platforms, but I am specifically interested in only the first key within that array. So, for the Array it should look like [{platforms: [windows], [windows]]} instead of [{platforms: [windows, osx, linux, n ...

Activate Button upon Textbox/Combobox/RadDatePicker Modification through JavaScript

On my ASP.NET form, I have various input elements including textboxes, dropdowns, date pickers, and update buttons. My goal is to enable the update button whenever a user makes a change in any of these fields. To achieve this, I applied a specific CSS cla ...

Show a pop-up form when a user focuses on it using React

Hello, I have been looking for a way to create an overlay with a form that appears when a specific input field is clicked. I am trying to achieve this using React. Can someone please advise me on how to accomplish this? Here is my code import React, { Co ...

Creating Component Variants for Google Optimize A/B testing in Next.js

I've been attempting to create a component variant in Google Optimize beyond just text or color changes, but I haven't found a suitable method to do so yet. I'm looking for guidance on how to integrate/configure Optimize with my code in orde ...