Matt Coady
Matt Coady

Reputation: 3856

onMouseOver change background image position

I'm trying to reposition the background image of a div using javascript. Here's what I have but it doesn't seem to work. What am I missing?

<a href="#" onMouseOver="document.getElementById('rubbish_image').style.backgroundPosition="0px 150px"">link one</a>
<a href="#" onMouseOver="document.getElementById('rubbish_image').style.backgroundPosition="0px 350px"">link two</a>

<div id="rubbish_image"></a>

Upvotes: 0

Views: 4731

Answers (2)

David Thomas
David Thomas

Reputation: 253308

I'm not entirely sure, but there's two obvious problems I can see with your JavaScript:

  1. You've got two " just before the closing > of the a tags, as a result of
  2. Your use of " inside of the string, which isn't allowed (you can use ' inside a string delimited with ", or vice versa, but " inside of a string delimited by " terminates the string).

I'd suggest, therefore, amending the code to:

<a href="#" onMouseOver="document.getElementById('rubbish_image').style.backgroundPosition='0px 150px';">link one</a>
<a href="#" onMouseOver="document.getElementById('rubbish_image').style.backgroundPosition='0px 350px';">link two</a>

I don't believe it's a huge problem, but you also didn't terminate your JavaScript within the onmouseover attribute, so I also added the ; to the end of each.

Upvotes: 2

thirtydot
thirtydot

Reputation: 228142

You're nesting double quotes, which won't work.

A simple fix is to only use single quotes inside the onmouseover attributes:

<a href="#" onMouseOver="document.getElementById('rubbish_image').style.backgroundPosition='0px 150px'">link one</a>
<a href="#" onMouseOver="document.getElementById('rubbish_image').style.backgroundPosition='0px 350px'">link two</a>

<div id="rubbish_image"></a>

You're already doing this inside getElementById.

Upvotes: 1

Related Questions