sway
sway

Reputation: 373

Change text using onmouseover on an image?

I'd like the text to change depending on which image the user is hovering over. I thought I had the right idea, but the code doesn't work.

http://jsfiddle.net/6V2TL/

HTML

<p id="test">
some text 1
</p>
<div id="image1" onmouseover="change1()">
    <img src="http://www.helpinghomelesscats.com/images/cat1.jpg">
</div>
<div id="image2" onmouseover="change2()">
    <img src="http://cvcl.mit.edu/hybrid/cat2.jpg">
</div>

JS

function change1() {
     document.getElementById("test").innerHTML = "this is a cute cat";   
}
function change2() {
     document.getElementById("test").innerHTML = "this is a cuter cat";   
}    ​

Thanks

Upvotes: 0

Views: 3362

Answers (4)

A.M.K
A.M.K

Reputation: 16785

Your code is inside and onLoad handler, it can't be run from the page. The first dropdown on the left changes this, please select "no wrap (head)" from the list.

Demo: http://jsfiddle.net/SO_AMK/35s4C/

function change1() {
  document.getElementById("test").innerHTML = "this is a cute cat";
}

function change2() {
  document.getElementById("test").innerHTML = "this is an angry cat";
}
<p id="test">
  some text 1
</p>

<div id="image1" onmouseover="change1()">

  <img src="http://lorempixel.com/output/cats-q-c-640-480-1.jpg">

</div>

<div id="image2" onmouseover="change2()">
  <img src="http://lorempixel.com/output/cats-q-c-640-480-2.jpg">
</div>

Upvotes: 3

dev4life
dev4life

Reputation: 892

There is something wrong with the JSfiddle site it looks. I moved the js to the HTML window and it worked. But your code works.

http://jsfiddle.net/6V2TL/9/

Upvotes: 0

kannanrbk
kannanrbk

Reputation: 7134

Your javascript methods onchange1,onchange2 is not calling on onmouseover event. You can try this link

http://jsfiddle.net/6V2TL/5/ .

Upvotes: 0

TheZ
TheZ

Reputation: 3732

If you look in the console you'll see yours throws Errors about not finding the functions when you hover.

JFiddle by default loads the code in the Javascript box after the page has loaded with a special handler, you want to change it to put the code in a non-wrapped form so when the body hovers happen the functions actually exist globally so they can be accessed: http://jsfiddle.net/6V2TL/3/

It is in the options on the left in the toolbar.

Upvotes: 1

Related Questions