TonyW
TonyW

Reputation: 18875

Javascript doesn't respond to mouseover a hyperlink

I know this question may be very basic, but I am learning Javascript. I wrote the following toy program and hope to see the text message "You clicked on me, stop it!" when I have mouse over the hyper link "Click Me".

my js code:

document.getElementsByClassName('clickme').onmouseover = function() { 
    var targetDiv = document.getElementById("foo").getElementsByClassName("bar")[0];

    targetDiv.innerHTML = "You clicked on me, stop it!";
    }

and my html code:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8" />
    <title>JavaScript Exercise1</title>
</head>
<body>
<a href='#' onmouseover="" class="clickme" />Click Me
<div id="foo">
    <div class="bar">
    <h4> hello world in h4 </h4>
    </div>
</div>

<script src="script.js"></script>
</body>
</html>

Upvotes: 1

Views: 76

Answers (1)

JohnFx
JohnFx

Reputation: 34909

Change this...

document.getElementsByClassName('clickme').onmouseover = ...

to this

document.getElementsByClassName('clickme')[0].onmouseover = ...

Here it is in action.

Upvotes: 1

Related Questions