tags:

views:

227

answers:

1

I have a simple web page with a simple puzzle. There are some images that user is supposed to drag to their designated drop zones. I use solution in JavaScript generated by DreamWeaver.

I want to add a JavaScript function that will show a correct.png or wrong.png image next to the image a user just dropped. The straightforward way to do it is to just have correct and wrong div elements for each of the draggable images. But is there a more elegant way?

Another way to put it would be:
Write a JavaScript functions Show(commonImageId, nextToImageId) and Hide(commonImageId, nextToImageId) that would be used like Show('correct', 'draggable1');.

+2  A: 

Instead of having multiple divs that you show and hide, you can try this solution as well.

Create two styles, each with a different background image set. Whenever you trap the event that a given image should be marked as correct or wrong, simply swap the style of the div, which will have the affect of switching the background image.

Very quick (and in need of some cleanup) sample code below, you've got the right idea with setting the type with a function...

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd"&gt;
<html>
<head>
<title>Image Swap</title>
<script language="javascript">
function setImage(id, value){
document.getElementById(id).className=value;
}
</script>
<style>
.blank{
    width:80px;
    height:80px;
    float:left;
}
.correct{
    background-image:url('correct.gif');
    background-repeat:no-repeat;
    width:80px;
    height:80px;
    float:left;
}
.wrong{
    background-image:url('wrong.gif');
    background-repeat:no-repeat;
    width:80px;
    height:80px;
    float:left;
}
.item{
    float:left;
    height:80px;
}
.clear{
    clear:both;
}
</style>
</head>
<body>
<div id="correct1" class"blank"></div><div id="item1" class="item">Item 1</div><div class="clear"></div>
<div id="correct2" class="blank"></div><div id="item2" class="item">Item 2</div><div class="clear"></div>
<script language="javascript">
setImage('correct1','correct');
</script>
</body>
</html>
tschaible