Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
47
rated 0 times [  53] [ 6]  / answers: 1 / hits: 14929  / 9 Years ago, sat, august 8, 2015, 12:00:00

I have a set of dynamically generated div elements like:





<div on-click=selected>one</div>
<div on-click=selected>two</div>
<div on-click=selected>three</div>
<div on-click=selected>four</div>
<div on-click=selected>five</div>
<div on-click=selected>six</div>
<div on-click=selected>seven</div>





I want to change the background color of div on which it is clicked and lose it when another div is clicked.



I could achieve this using tabindex, but I want to retain it until I click it on the another div or clear it intentionally, which tabindex does not provide.



How can I acieve it using javascript?


More From » html

 Answers
17
<div class=radiodiv onclick=selected(this)>one</div>
<div class=radiodiv onclick=selected(this)>two</div>
<div class=radiodiv onclick=selected(this)>three</div>
<div class=radiodiv onclick=selected(this)>four</div>
<div class=radiodiv onclick=selected(this)>five</div>
<div class=radiodiv onclick=selected(this)>six</div>
<div class=radiodiv onclick=selected(this)>seven</div>

<script>
var divItems = document.getElementsByClassName(radiodiv);

function selected(item) {
this.clear();
item.style.backgroundColor = 'red';
}

function clear() {
for(var i=0; i < divItems.length; i++) {
var item = divItems[i];
item.style.backgroundColor = 'white';
}
}
</script>

[#35058] Friday, August 7, 2015, 9 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
pierceabnerc

Total Points: 430
Total Questions: 92
Total Answers: 102

Location: Faroe Islands
Member since Thu, Apr 8, 2021
3 Years ago
;