Reputation: 531
(function() {
var divs = document.getElementsByClassName('data');
var myFunction = function()
{
alert("hello");
var el = this;
var st = window.getComputedStyle(el, null);
var tr = st.getPropertyValue("transform") ||
st.getPropertyValue("-moz-transform") ||
st.getPropertyValue("-ms-transform") ||
st.getPropertyValue("-o-transform") ||
st.getPropertyValue("transform") ||
"Either no transform set, or browser doesn't do getComputedStyle";
console.log(tr);
}
for (var i = 0; i < divs.length; i++) {
divs[i].addEventListener('mouseover', myFunction, true);
}
})();
<div class="data">data1</div>
<div class="data">data2</div>
<div class="data">data3</div>
<div class="data">data4</div>
I am using pure javascript to add event listener to the div .
The add event listener not working
Some guys said to me to add the event listener at window.load but i am getting my dom objects here in this javascript. Any help?
Upvotes: 0
Views: 3919
Reputation: 2994
There is no error in your code. you just need to put your code below the DOM.
Best place to add your script is before the end of body tag. Use external script files instead of internal of script.
For example only I am using script inside html. You should use script as external file which is best practice.
Working Code -
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
</head>
<body>
<div class="data">data1</div>
<div class="data">data2</div>
<div class="data">data3</div>
<div class="data">data4</div>
<script>
document.addEventListener("DOMContentLoaded", function() {
(function() {
var divs = document.getElementsByClassName('data');
var myFunction = function()
{
alert("hello");
var el = this;
var st = window.getComputedStyle(el, null);
var tr = st.getPropertyValue("transform") ||
st.getPropertyValue("-moz-transform") ||
st.getPropertyValue("-ms-transform") ||
st.getPropertyValue("-o-transform") ||
st.getPropertyValue("transform") ||
"Either no transform set, or browser doesn't do getComputedStyle";
console.log(tr);
};
for (var i = 0; i < divs.length; i++) {
divs[i].addEventListener('mouseover', myFunction, true);
}
})();
});
</script>
</body>
</html>
DOMContentLoaded event will execute your code after DOM is loaded and parsed. so it will not give error.
Upvotes: 1
Reputation: 485
Your code works. You must run your script after DOM is loaded, or you must write
DOMContentLoaded
eventListener:
document.addEventListener("DOMContentLoaded", function(event) {
(function() {
var divs = document.getElementsByClassName('data');
var myFunction = function()
{
//.... Your code
}
for (var i = 0; i < divs.length; i++) {
divs[i].addEventListener('mouseover', myFunction, true);
}
})();
});
Upvotes: 1