3

I have a div with ID "box". its initial background color is set to #ff7700. I want to create a function "function1()" to do following:

  • first click: change the background color to #ff0077
  • Second click: change the background color back to #ff7700
  • third click: change the background color to #ff0077
  • fourth click: change the background color back to #ff7700 and so on.

Code:

<style>
    #box{
    background-color: #ff7700;
    cursor: pointer;
}    
</style>

<div id="box" onClick="function1()" > Inner HTML</div>

I tried to write a function but it is not working.

<script>
    function function1(){
        var check = document.getElementById("box").style;
        check2=check.backgroundColor;
        if (check2 != "#ff0077"){
            check2="#ff7700";
            } else {
               check2="#ff0077";
            }
       }
</script>

please advise any other approach. I want to stick to core JS instead of using Jquery.

ibrahim mahrir
  • 31,174
  • 5
  • 48
  • 73
creativated
  • 211
  • 3
  • 16

6 Answers6

4

It's better to use a boolean as toggle:

var div = document.getElementById("box"),
    toggle = false;
    
div.onclick = function() {
  toggle = !toggle;                                     // invert toggle
  div.style.background = toggle? "#ff0077": "#ff7700";  // change background color depending on the value of toggle
}

div.style.background = "#ff7700";                       // give the div an initial background
<div id="box">Inner HTML</div>
ibrahim mahrir
  • 31,174
  • 5
  • 48
  • 73
2

I did a simple example using jQuery. I hope I have helped.

Basically I get an element with class ".myDiv" and add a click event to it. Always the element is clicked the "toggleClass ()" method toggles the class.

$(document).ready(function(){
  $(".myDiv").bind("click", function(){
    $(this).toggleClass("myClass");
  });
});
.myDiv{
  padding: 1em;
  font-family: "Helvetica", sans-serif;
  line-height: 1.5em;
  background: #cccccc;
}

.myClass{
  background: red;
  color: white;
}
<div class="myDiv">
    <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Assumenda facere, cumque aliquam quis aut, velit quidem, repellendus quo maiores saepe unde sed reprehenderit laborum? Eum laborum possimus quidem, ea non.</p>
</div>

<!--jQuery Libary-->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
1
  1. Remove background-color: #ff7700; from css selector #box
  2. Create 2 css class, say A and B and put background colors there accordingly
  3. Get the dom element var domEl = document.getElementById("box"); After that if domEl.className==="A" then assign "B" to it, otherwise assign "A"
Koushik Chatterjee
  • 4,106
  • 3
  • 18
  • 32
1

.style property does not return a hexidecimal color code. You can use window.getComputedStyle() to get the computed CSS property, set the color to an rgb() value

<style>
  #box {
    background-color: #ff7700;
    cursor: pointer;
  }
</style>
<script>
  function function1() {
    if ( window.getComputedStyle(box).backgroundColor === "rgb(255, 119, 0)") {
      box.style.backgroundColor = "rgb(255, 0, 119)";
    } else {
      box.style.backgroundColor = "rgb(255, 119, 0)";
    }
  }
  onload = function() {
    const box = document.getElementById("box");
  }
</script>
<div id="box" onClick="function1()"> Inner HTML</div>

See also Is it possible to change the background color and back to the original in plain javascript every time i click a button?

guest271314
  • 1
  • 15
  • 104
  • 177
1

You'll get the color of your element using getComputedStyle() which will return your color to rgb() format. If you need to change your rgb() to hex learn more on this post.

Here's an example

function function1(){
    var check = document.getElementById("box");
    var color = window.getComputedStyle(check, null).getPropertyValue('background-color');  
    if (color != "rgb(255, 119, 0)"){
      check.style.backgroundColor = "rgb(255, 119, 0)";
    } else {
      check.style.backgroundColor = "rgb(255, 255, 255)";
    }
}
#box{
    background-color: #ff7700;
    cursor: pointer;
}    
<div id="box" onclick="function1()">Inner HTML</div>
Horai Nuri
  • 5,358
  • 16
  • 75
  • 127
1

Using inline js code I'd suggest to pass the this variable: current element. In this way you don't need to select the element.

Using window.getComputedStyle and converting the value to an hexadecimal value your code is:

function function1(ele) {
    var background = window.getComputedStyle(ele).backgroundColor;
    var hexColor = rgb2hex(background);
    if (hexColor != "#ff0077") {
        ele.style.backgroundColor = "#ff0077";
    } else {
        ele.style.backgroundColor = "#ff7700";
    }
}



function rgb2hex(rgb) {
    rgb = rgb.match(/^rgba?[\s+]?\([\s+]?(\d+)[\s+]?,[\s+]?(\d+)[\s+]?,[\s+]?(\d+)[\s+]?/i);
    return (rgb && rgb.length === 4) ? "#" +
    ("0" + parseInt(rgb[1], 10).toString(16)).slice(-2) +
    ("0" + parseInt(rgb[2], 10).toString(16)).slice(-2) +
    ("0" + parseInt(rgb[3], 10).toString(16)).slice(-2) : '';
}
#box {
    background-color: #ff7700;
    cursor: pointer;
}
<div id="box" onClick="function1(this)"> Inner HTML</div>
gaetanoM
  • 41,594
  • 6
  • 42
  • 61