Alter the colors of all Divs inside a container with each click

Hey everyone, I'm just starting to learn JavaScript. I'm working on a project where I want to change the color of all the divs in a container every time they are clicked.

For example, on the first click, I want all the divs to turn red. Then, on the second click, I want them to turn green!

<!doctype html>
 <html lang="en">
  <head>
  <!-- Required meta tags -->
   <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
     <!-- Bootstrap CSS -->
      <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta/css/bootstrap.min.css" integrity="sha384-/Y6pD6FV/Vv2HJnA6t+vslU6fwYXjCFtcEpHbNJ0lyAFsXTsjBbfaDjzALeQsN6M" crossorigin="anonymous">
       <link href="//maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" type="text/css" rel="stylesheet">
        <!--jquery easing plugin-->
         <script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
         <!--custom css---->
         <link href="css/phcoding.css" type="text/css" rel="stylesheet">
          <title>cliciks</title>
          <style>
          </style>
           </head>
           <body>
<div id="container" onclick="myFunction();">
<div id="div1">This is div 1</p>
<div id="div2">This is div 2</p>
<div id="div3">This is div 3</p>
</div>
<script>
function  myFunction(){
    let x = document.getElementById("container");
    y=x.children;
    for(let i = 0; i< y.length;i++){
        y[i].style.color="red";
        y[i].style.color="green";
    }
}
myFunction();
</script>
          </body>
         </html>

Answer №1

Give it a shot:

$(".target").on("click",function(){
     if($(this).css("background-color") == "blue"){
           $(this).css("background-color","yellow");
     }else{
           $(this).css("background-color","blue");
     }
}

Answer №2

To begin, start by creating a color map:

var colors = {
    "1": "blue",
    "2": "yellow"
};

Then, set up an event listener and initialize the click counter:

var clickCounter = 0;
var box = document.getElementById("box");
box.addEventListener("click", function (event)
{
    clickCounter++;
    box.querySelectorAll("div[id^=\"section\"]").forEach(function (element)
    {
        element.style.color = colors[clickCounter];
    });
});

Warm regards.

Answer №3

Here is a helpful resource for beginners that may answer your question:

If you are just starting out, you might find this website useful:

(function () {
    var clickHandler = function (event) {
        // Selecting all div elements as targets
        var target = document.querySelectorAll('div');

        // Looping through each target
        for (var i = 0; i < target.length; i++) {

            // Changing background color to red if not already red, green if it's red
            if (target[i].style.backgroundColor != 'red') {
                target[i].style.backgroundColor = 'red';
            } else {
                target[i].style.backgroundColor = 'green';
            }

        }
    };
    // Attaching click event listener to the entire document
    document.addEventListener('click', clickHandler, false);

}());

Answer №4

Combining elements from previous responses...

<div id="container">
    <div>This is div 1</div>
    <div>This is div 2</div>
    <div>This is div 3</div>
</div>
<script>
    document.getElementById('container').addEventListener('click',function(e){
        Array.from( this.querySelectorAll('div') ).forEach( div=>{
            let colour;
            switch( div.style.color ){
                case '':colour='red';break; //default
                case 'red':colour='green';break;
                case 'green':colour='red';break;
            }
            div.style.color=colour;
        })
    });
</script>

If there is no specific need for ID attributes in the child divs, they can be removed. Ensure that start and end tags match correctly - <div>...</p> is not valid!!

Answer №5

Compile a list of different colors and then iterate through them.

$("#changeColor").click(function() {
        var currentColor = $(".con-child").css("background-color");
        var colorList = ["rgb(255, 0, 0)", "rgb(0, 255, 0)", "rgb(0, 0, 255)"];
          var next = colorList[($.inArray(currentColor, colorList) + 1) % colorList.length];
          $(".con-child").css("background-color", next);
        });
.con-child {
    display: block;
    height: 100px;
    width: 100px;
    background-color: red;
    margin-bottom: 30px;
  }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div class="containt" id="changeColor">
  <div class="con-child">
   
  </div>
  <div class="con-child">
    
  </div>
  <div class="con-child">
    
  </div>
</div>

Modify!!!

If you wish to change text color, simply remove the "background" property from JS:

$("#changeColor").click(function() {
        var currentColor = $(".con-child").css("color");
        var colorList = ["rgb(255, 0, 0)", "rgb(0, 255, 0)", "rgb(0, 0, 255)"];
          var next = colorList[($.inArray(currentColor, colorList) + 1) % colorList.length];
          $(".con-child").css("color", next);
    console.log(currentColor);
console.log(next);
        });

If dealing with RGB is not your preference and you prefer HEX values, check out this helpful guide on converting between the two:

Answer №6

Your HTML code contains numerous errors such as opening "< div>" tags and closing them with "< /p>". Additionally, your JavaScript includes a loop that applies a "red" style followed by a "green" style to elements, resulting in a constant display of green. Here is the corrected version of both the HTML and JS:

document.getElementById('container').addEventListener('click', myFunction)

function myFunction() {
  let divs = document.getElementsByClassName("color")

  if (divs[0].style.color === "green") {
    Array.prototype.map.call(divs, (div) => {
      div.style.color = "red"
    })
  } else {
    Array.prototype.map.call(divs, (div) => {
      div.style.color = "green"
    })
  }
}
<head>
  <!-- Required meta tags -->
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
  <!-- Bootstrap CSS -->
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta/css/bootstrap.min.css" integrity="sha384-/Y6pD6FV/Vv2HJnA6t+vslU6fwYXjCFtcEpHbNJ0lyAFsXTsjBbfaDjzALeQsN6M" crossorigin="anonymous">
  <link href="//maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" type="text/css" rel="stylesheet">
  <!--jquery easing plugin-->
  <script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
  <!--custom css---->
  <link href="css/phcoding.css" type="text/css" rel="stylesheet">
  <title>cliciks</title>
  <style>

  </style>
</head>

<body>
  <div id="container">
    <div class="color">
      <p>This is div 1</p>
    </div>
  
    <div class="color">
      <p>This is div 2</p>
    </div>
   
    <div class="color">
      <p>This is div 3</p>
    </div>
  </div>
  <script src="index.js">
  </script>
</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

Why is the value returned by getBoundingClientRect 190 when the y attribute is set to 200 in SVG?

When placing textBox1 at a y-position of 200, getBoundingClientRect is returning a value of 190. What could be causing this discrepancy? For more details and code snippets, please refer to the following link: https://codepen.io/anon/pen/REKayR?editors=101 ...

Using various designs on elements generated from ng-repeat

Is it possible to apply different styles to buttons created using ng-repeat by having b.color return a value from the btnValues object? Currently, it is not returning the value. If this is not possible, are there alternative methods to achieve this? < ...

JavaScript code to place variables into an array with included variables

Looking for a solution: const myArray = [] myArray.push( { "bob" : { "banana" : "yellow" } }) console.log(myArray) Output: { "bob": { "banana": "yellow" } } Attempting a modifi ...

Tips for Placing a Div in a Precise Location

I'm currently working with Bootstrap and I'm attempting to replicate a layout similar to the one used by Twitter, as shown in the screenshot below. The specific part I'm struggling with is where the profile picture is located. I want to add ...

Issue with Angular application failing to fetch data from JSON server

I've been attempting to retrieve data from a local server, but so far I'm not getting any results. The concept is to have a service handle the retrieval process and return an observable for any components in need of the data to subscribe to. dis ...

Adjust the text size of a label in material-ui

Hey everyone, I'm struggling with something here. I need to adjust the font size of the label that goes along with my textfield. So far, I've only been able to change the font size of the input itself and not the label. Here's the code for ...

Email confirmation section

I'm in the process of setting up a subscription newsletter page, and everything seems to be working correctly except for the part where I need users to enter their email address twice. The second email field is meant for confirmation purposes, but I&a ...

End the div element upon completion of the Vimeo video

I am in need of a website that includes an intro video displayed as a full-width div over the background content. To achieve this, I created a Div containing an iframe video from Vimeo along with a button to skip the intro (which closes the div upon clicki ...

How to use JavaScript and regex to control the state of a disabled submit button

I have a challenge where I need to activate or deactivate a submission button in a form called btn-vote using JavaScript. The button will only be activated if one of the 10 radio buttons is selected. Additionally, if the person-10 radio button is chosen, t ...

Adjust the position if the height exceeds 100 pixels

Can someone help with this code issue? $(document).ready(function () { if ($('.pi-img').height() > 100) { $(this).css('top' , '30%'); console.log('yeah'); } }); I am encountering difficu ...

The session feature in Express is malfunctioning

Incorporating express-session into my app, I attempted the following proof of concept (POC):. server.js app.use(session({ secret: 'pal!lap789', // create new redis store. store: new redisStore({ host: 'localhost ...

CSS - Problem with background image appearing stretched on Samsung mobile devices

Is the Samsung default "Internet Browser" based on another build? It seems to have trouble displaying stretched background images correctly, unlike desktop browsers or Chrome for mobile. Here is the CSS and HTML I am using: #bk_img { height:100%; ...

Troubleshooting Test Failures: The importance of passing $controller in the callback of 'it' function in Angular

As a newcomer to testing, I am attempting to write Jasmine/Karma tests for a controller. Given a sample test to use as a starting point, the issue arises when passing the $controller in the argument of the it block. The test passes successfully with this s ...

Checking the validity of a username through regex

I have implemented a Username field validation in Vue using regex. A key down event triggers the method below with each keystroke: userNameValidation(event) { if (!event.key.match(/^[a-zA-Z0-9._]+$/)) { event.preventDefault(); } ...

How can you turn off the full-page display of Javascript errors in Visual Studio?

Recently, I've been experimenting with React on Visual Studio using a React app and C#. However, I find it frustrating that JavaScript errors are displaying as full pages instead of in the console. Is there a way to turn this feature off? I've s ...

Deleting a hyperlink within a content-editable area

Presently, I am in the process of working on a straightforward project where users can format text using contenteditable. I have successfully implemented a feature that allows users to add hyperlinks to selected text by clicking on the "Create Link" button ...

Is it a guarantee that a function called in the head section of a JavaScript for-of loop will only be executed once?

In both Firefox and Chrome, I tested the code snippet below: function test() { console.log("***") return [1,2,3] } for (const t of test()) { console.log(t) } After running this code, I noticed that the test function was only called once. T ...

Adjust the panel size accordingly for smaller screens

My application is utilizing the Spotify API to retrieve names and images. These are then displayed on my webpage within cards/panels in the following format: <div class="col-md-4" v-if="type == 'tracks'" v-for="(track, index) in tracks"> ...

Tips for creating two columns within a Bootstrap row, one with a form and the other with an image, that are both the same height and responsive

I am facing an issue with my bootstrap columns. One column has a form, while the other contains an image. The image section is set to 100% width, making it responsive when the screen size changes. However, the form remains at a fixed height regardless of t ...

Implement a hover effect on a specific class targeting a nested element using JavaScript

Is there a method to apply a class that modifies rules for a child element using Javascript? I have successfully added it with CSS but am struggling to do the same with Javascript. Removing the class in JS is easy by referencing the classname before the ho ...