James J
James J

Reputation: 25

Change a background image of a div on click

Okay, I think my head is being dense. But I cant seem to get this to work. I'm doing a website for a photographer, and he wants to be able to let a user change the frame that they would like from a choice of 3. Easiest way I thought to do this was to create a div, and then have it change class based on a button click. So it would change the background image. However I cant get it to do this. Any ideas would be well received, as I'm guessing theres probably a javascript version that does it quicker and easier.

<html>
<head>
<title>Untitled</title>
<style>
#pictureframe {
width:200px;
height:200px;
}

.wooden {
background-image:url(frame.png);
}

.plain {
background-image:url(clear.png);
}

.black {
background-image:url(black.png);
}

</style>
</head>
<body>

<div id="pictureframe">
</div>

<div style="height:20px;border:1px solid #617779;width:90px;text-align:center;background-color:white;" onclick = "pictureframe.style.className = 'wooden'">Make it wood</div>
<br>
<div style="height:20px;border:1px solid #617779;width:90px;text-align:center;background-color:white;" onclick = "pictureframe.style.className = 'clear'">Make it Frameless</div>
<br>
<div style="height:20px;border:1px solid #617779;width:90px;text-align:center;background-color:white;" onclick = "pictureframe.style.className = 'wooden'">Make it Black Bezel</div>
</body>

Upvotes: 1

Views: 2811

Answers (4)

Felix
Felix

Reputation: 852

If you want to use some other class for style, than you probably need to go with something like this:

function replaceClass(className) {
    $('#pictureframe').removeClass('plain black wooden');
    return $('#pictureframe').addClass(className);
}​

This way you can keep class with styles http://jsfiddle.net/NjTea/5/

Upvotes: 0

Sushanth --
Sushanth --

Reputation: 55740

Try this:

onclick ="pictureframe.className = 'wooden'"

Upvotes: 0

Zoltan Toth
Zoltan Toth

Reputation: 47657

It's not

pictureframe.style.className = ...

but

pictureframe.className = ...

DEMO

Upvotes: 2

Nick Rolando
Nick Rolando

Reputation: 26157

className is not part of the style object in the DOM element, but a direct property:

document.getElementById("pictureframe").className = 'wooden';

Upvotes: 4

Related Questions