Reputation:
I'm trying to make a div toggle the opacity of multiple other divs on click. If anyone could point me in the right direction as to where I'm going wrong here, that would be great :)
function toggle_opacity(className) {
var x = document.getElementsByClassName(className);
if(x.style.opacity == '0')
x.style.opacity = '1';
else
x.style.opacity = '0';
}
Upvotes: 0
Views: 380
Reputation: 1849
may be you want this I done with jquery
html--
<div id="div_1" class="ope">
</div>
<div id="div_2" class="ope">
</div>
<div id="div_3" class="ope">
</div>
css---
.ope{
width:200px;
height:100px;
background-color:pink;
margin-bottom:4px;
cursor:pointer;
}
jquery--
$(document).ready(function(){
$(".ope").click(function(){
var thisdiv = $(this).attr('id');
//alert(thisdiv);
$(".ope").css('opacity','1');
$("#"+thisdiv).css('opacity','0.5');
})
})
Upvotes: 0
Reputation: 2763
Have updated the Fiddle with the changes:
I have changed the function to match your requirement.
e1[0].style.opacity = '1';
e1[1].style.opacity = '0';
Added these 2 lines.
Upvotes: 0
Reputation: 20806
Your JSFiddle has 3 problems.
1) document.getElementsByClassName(className)
returns an array, so you need to select the first element:
var x = document.getElementsByClassName(className)[0];
2) Your if
needs to check if the opacity is 0
, not '0'
.
3) Your JS needs to be in <head>
, not onLoad
.
Here's an updated JSFiddle.
Upvotes: 0
Reputation: 2992
getElementsByClassName
will return an array, so wrap your code in a loop:
function toggle_opacity(className) {
var x = document.getElementsByClassName(className);
for(i = 0; i < x.length; i++){
if(x[i].style.opacity == '0')
x[i].style.opacity = '1';
else
x[i].style.opacity = '0';
}
}
Upvotes: 1