pol
pol

Reputation: 109

Change color of current element and remove background from previous click

So I have a list of elements that originally have white backgrounds and my goal is when I click one of it it changes color to blue, but only one element can by chosen and have color - if another element was clicked earlier it background return to white

I was trying with this code but it doesn't work

var prevDiv=null
        function change_color_to_blue_click(){ 
            if(prevDiv) {
                prevDiv.style.backgroundColor = "white";        
            }
            var target = event.currentTarget
            target.style.backgroundColor="blue" 
            selected = true                               
            prevDiv = target;
        }

Upvotes: 0

Views: 991

Answers (4)

cpt.madi
cpt.madi

Reputation: 1

var prevDiv = null;
function changeColor() {
  var target = event.currentTarget;
  if (prevDiv) {
    prevDiv.style.backgroundColor = "white";
    target.style.backgroundColor = "blue";
    prevDiv = target;
  } else {
    target.style.backgroundColor = "blue";
    prevDiv = target;
  }
}

Upvotes: 0

Amr Eraky
Amr Eraky

Reputation: 1781

var prevDiv=null
function changeColor(){ 
  if(prevDiv) {
    prevDiv.style.backgroundColor = "white";        
  }
  var target = event.currentTarget
  target.style.backgroundColor="blue" 
  selected = true                               
  prevDiv = target;
}
.box {
  width: 50px;
  height: 50px;
  border: solid black 2px;
  margin: 20px;
  display: inline-block;
}
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
</head>
<body>
    <div id="click">
        <div onclick="changeColor()" class="box"></div>
        <div onclick="changeColor()" class="box"></div>
        <div onclick="changeColor()" class="box"></div>
        <div onclick="changeColor()" class="box"></div>
    </div>
</body>
</html>

Upvotes: 0

PHP Guru
PHP Guru

Reputation: 1556

Was there a reason why you didn't accept an event argument in your function? (Maybe because Internet explorer used to use a global event object.)

This worked for me:

function change_color_to_blue_click(event){
    if(prevDiv) {
        prevDiv.style.backgroundColor = "white";        
    }
    var target = event.currentTarget
    target.style.backgroundColor="blue" 
    selected = true
    prevDiv = target;
}

Upvotes: 0

Matthew Perlman
Matthew Perlman

Reputation: 103

The only thing I can think of is that you didn't pass event into the function.

Upvotes: 1

Related Questions