dezman
dezman

Reputation: 19358

Still having simple javascript trouble

if (document.getElementById) {

function alterImg() {
    document.body.getElementById('sendimg').src="url('images/tridown.png')";
}

}

and then the html:

<div id="sendbutton">
<img id="sendimg" src="images/tri.png" onclick="alterImg()" />
</div>

i tried using a this keyword reference too, to no avail.

Upvotes: -2

Views: 73

Answers (4)

Bergi
Bergi

Reputation: 664395

Three problems with your code:

  • Your using document .body .getElementById. "getElementById" is a method of the document, not the body element.
  • You're mixing css with html. In html, you assign a url to the src attribute of an image. In css, you use url(...) to reference an image, e.g. for backgrounds.
  • You're using a function declaration in an if statement. Please note that this does declare the function in the current scope (I assume global), regardless whether the if-block gets executed or not. If you want to define the function only when document.getElementById is available, you will need to use
if (document.getElementById) {
    var alterImg = function () {
        document.getElementById('sendimg').src="images/tridown.png";
    }
} 

Upvotes: 1

Mattias Buelens
Mattias Buelens

Reputation: 20159

The getElementById method is only defined on the document object, not on document.body. Also, the src property is not a CSS property, so you can't use url(...) as value. You should simply write:

document.getElementById('sendimg').src = images/tridown.png";

For a more complete description of the HTMLImageElement, check out the Mozilla Developer Network.

Upvotes: 0

Peter
Peter

Reputation: 89

remove the url('') statement from .src="url('images/tridown.png')"

The below worked for me:

<div id="sendbutton">
<img id="sendimg" src="http://placehold.it/64x64" onclick="alterImg()" />
</div>


<script type="text/javascript">
    if (document.getElementById) {

function alterImg() {
    document.body.getElementById('sendimg').src="http://placehold.it/128x128";
}

}

</script>
​

Upvotes: -1

shingokko
shingokko

Reputation: 412

A couple of problems here:

  1. the src attribute does not need to be wrapped around url()
  2. Use document.getElementById instead of document.body.getElementById

    function alterImg() { document.getElementById('sendimg').src = "images/tridown.png"; }

Upvotes: -1

Related Questions