1

Hello there i'm new to javascript. I am trying to change the color of all Divs in a container every time that I click.

Example: On the first click i want all divs to appear red. On the second click I want all divs to appear 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>
Funk Forty Niner
  • 74,450
  • 15
  • 68
  • 141
willy
  • 249
  • 3
  • 12

6 Answers6

0

Try:

$(".container").on("click",function(){
     if($(this).css("color") == "red"){
           $(this).css("color","green");
     }else{
           $(this).css("color","red");
     }
}
Illya
  • 1,268
  • 1
  • 5
  • 16
0

first of all you need a color mapping:

var color = {
    "1": "red",
    "2": "green"
};

Next we add an event listener and initialize the click count:

var clickCount = 0;
var container = document.getElementById("container");
container.addEventListener("click", function (e)
{
    clickCount++;
    container.querySelectorAll("div[id^=\"div\"]").forEach(function (element)
    {
        element.style.color = color[clickCount];
    });
});

Best regards.

Bär Ger
  • 62
  • 5
0

This should answer your question.

As a beginner, you may find this resource useful. https://vanillajstoolkit.com/helpers/

(function () {
    var clickHandler = function (event) {
        // Choose your target, in this instance all divs
        var target = document.querySelectorAll('div');

        // Loop through the targets
        for (var i = 0; i < target.length; i++) {

            // If the color is not red, make it red
            if (target[i].style.backgroundColor != 'red') {
                target[i].style.backgroundColor = 'red';
            } else {
                // If the color is red, it must be defacto green
                target[i].style.backgroundColor = 'green';
            }

        }
    };
    // Every time a click happens on screen, clickHandler will fire
    document.addEventListener('click', clickHandler, false);

}());
0

Like a hybrid of the previous answers...

<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>

Unless you have specific need of the ID attributes for the child divs it is OK to remove them, though you MUST ensure that the start and end tags match - so <div>...</p> is not correct!!

Professor Abronsius
  • 33,063
  • 5
  • 32
  • 46
0

Make list of colors then loop through them. Example:

$("#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>

Edit!!!

If you want to change text color you can remove "background" 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 you don't want to deal with RGB, instead HEX, here is good answer how to convert this two https://stackoverflow.com/a/1740716/8812168

Noob
  • 1
  • 3
0

You have a lot of errors in your HTML, you open "< div>" and you close them with "< /p>". And in your JS you make an unconditional loop in which you pass to your elements a "red" style then a "green" style, in this case the result will always be green. Here is the HTML and JS corrected.

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" onclick="myFunction();"> -->
  <div id="container">
    <!-- <div id="div1">This is div 1</p> -->
    <div class="color">
      <p>This is div 1</p>
    </div>
    <!-- <div id="div2">This is div 2</p> -->
    <div class="color">
      <p>This is div 2</p>
    </div>
    <!-- <div id="div3">This is div 3</p> -->
    <div class="color">
      <p>This is div 3</p>
    </div>
  </div>
  <script src="index.js">
  </script>
</body>
Cyril Wallis-Davy
  • 292
  • 1
  • 5
  • 9