Check your HTML output to make sure that Cake is generating your link and image correctly. I'm not sure what the ready
part is for, but insert as needed. You should have Cake code like this:
echo $this->Html->link(
'#', // specify a target
$this->Html->image(
'button_on',
array(
// height and width attributes are deprecated
// use CSS styles in style attribute instead
'style' => 'height: 40px; width: 70px;',
'id' => 'changeimg',
'onclick' => 'changeImage()'
)
),
array('escape' => false) // this goes in the link part, not the image
);
Then your Javascript should look like this:
<script>
function changeImage() {
if (document.getElementById("changeimg").src === "button_on") {
document.getElementById("changeimg").src = "button_off";
} else {
document.getElementById("changeimg").src = "button_on";
}
return false; // prevent the link's default behaviour
}
</script>
Note: ===
is a strict comparison operator, so when you assign the src
attribute to something else, you use the assignment operator =
instead.