Reputation: 79
I am currently trying to implement a "button" of sorts using javascript. When a user clicks on the div, the div background should change colors, and there should be a pop up listing the device number. I am planning on using the number to redirect the client later. But right now, I can't get the clicking event to register. I had the event working correctly for a bit, but the value was always the final value of 'i'. My webpage also has JQuery in it.
Here's a JSFiddle and my relevant code. http://jsfiddle.net/G3ADG/9/
HTML Structure:
<div class="device" id="device1" value="1">
<div class="device-name" id="deviceName1">Name1</div>
</div>
<div class="device" id="device2" value="2">
<div class="device-name" id="deviceName2">Name2</div>
</div>
<div class="device" id="device3" value="3">
<div class="device-name" id="deviceName3">Name3</div>
</div>
Javascript:
(function() {
var devices = document.getElementsByClassName("device");
for (var i = 0; i < devices.length; i++) {
devices[i].addEventListener("click", function () {
alert(i);
this.style.backgroundColor = "#000000";
})
}
})();
Any help or input is appreciated.
EDIT: Fixed the ClassName call. The alert returned is still wrong though.
Upvotes: 0
Views: 57
Reputation: 99640
Check this fiddle:
You just needed a closure to attach events
(function () {
var devices = document.getElementsByClassName("device");
for (var i = 0; i < devices.length; i++) {
(function (i) {
devices[i].addEventListener("click", function () {
alert(i);
this.style.backgroundColor = "#000000";
})
})(i);
}
})();
Upvotes: 2
Reputation: 6598
Instead of running a for
loop, just run $('.device').each()
. I also added an alert to get each div.device
's value. See here: http://jsfiddle.net/G3ADG/10/
Edit: I did it with bind
instead of an on click because that mirrored how he was doing it in plain JS. pXL's solution using on
works just as well if you are not dynamically adding div.device
.
Upvotes: 0
Reputation: 44740
If you are already using jQuery - What you are trying can be done with this -
$('.device').on('click',function(){
$(this).css('background-color','red');
})
Demo --->
http://jsfiddle.net/G3ADG/8/
Upvotes: 2