I am a novice JavaScript programmer. Can someone make me understand how this works?
What is the difference between mouseover & onmouseover in JavaScript? Can we interchange its use? If not, how do we know which one to use where?
mouseover example:
function showAlert() {}
button.addEventListener('mouseover', showAlert);
onmouseover example:
function changeColor() {}
titleHeader.onmouseover = changeColor;
Basically both of them is same according to what they do , but the differences arises when we talk about what the do. you can use anyone out of them as per your wish but the addEventListener() method is not supported in Internet Explorer 8 and earlier versions which is required when you want to use mouseover. Syntax of addEventListener() which is dom element is addEventListener(event, function)
event(required)-> A String that specifies the name of the event. Note : Do not use the "on" prefix. For example, use "mouseover" instead of "mouseover". function(required)->Specifies the function to run when the event occurs. eg:
<html>
<body>
<p>This example uses the addEventListener() method to attach a "mouseover" and "mouseout" event to a h1 element.</p>
<h1 id="demo">Mouse over me</h1>
<script>
document.getElementById("demo").addEventListener("mouseover", mouseOver);
function mouseOver() {
document.getElementById("demo").style.color = "red";
}
</script>
</body>
</html>
**Dom Event onmouseover**
<body>
<h1 id="demo">Mouse over me</h1>
<script>
document.getElementById("demo").onmouseover = function(){mouseOver()};
function mouseOver() {
document.getElementById("demo").style.color = "red";
}
</script>
</body>
At last I will like to add that you can use addEventListener inside script only you cant use it inside your html body howerver in case of Dom event you can use it inside html also using syntax like Eg:
<html>
<body>
<p>This example demonstrates how to assign an "onmouseover" and "onmouseout"
event to a h1 element.</p>
<h1 id="demo" onmouseover="mouseOver()" >Mouse over me</h1>
<script>
function mouseOver() {
document.getElementById("demo").style.color = "red";
}
</script>