5

OK so I know this question has been asked separetly but I'm trying to use javascript to replace a broken image with another image with DIFFERENT dimensions by changing th src attribute. Here's a part of my code:

MARKUP:

...
<img id="error-img" class="img-header" onerror="imgError(this);" alt="Header" src="images/header.png">
...

STYLES:

...
.img-header { width: 54px; height: 64px; }
...

JAVASCRIPT:

...
function imgError(image) {
image.onerror = "";
image.src = "/images/broken.png";
return true;
}
...

So what I need is to include a piece of code in this function so that when the image gets replaced the new image has it's dimensions set correctly but not 54x64px.

EDIT:

Thank you for the answers guys but I've forgot to mention the size of the broken.png image: Width: 276px Height: 45px.

2
  • So replace the values in below answer with those values and it will work... Commented Feb 27, 2014 at 18:50
  • Yeah I know I just wanted to help future visitors understand the question better. Commented Feb 27, 2014 at 18:59

3 Answers 3

3

For that you can use image.style to set a width or height, or image.className to assign it a class.

...
function imgError(image) {
image.onerror = "";
image.src = "/images/broken.png";
// set width/height
image.style.width = "50px";
image.style.height = "50px";
// or add class name
image.className = "img-error";
return true;
}
...

CSS

...
.img-header { width: 54px; height: 64px; }
.img-error  { width: 40px; height: 40px; }
...
Sign up to request clarification or add additional context in comments.

Comments

1

If you want replacement image to have it's own width/height and not inherited from .image-header class, you have couple options:

1). clear className:

image.className = '';

http://jsfiddle.net/gGP5D/

2). add new class name:

function imgError(image) {
    image.onerror = "";
    image.src = "/images/broken.png";
    image.className += ' replacement-image';
}

http://jsfiddle.net/gGP5D/1/

This new class name could define new dimensions if they are known, or reset width and height to auto values.

2 Comments

Just out of curiosity, as I already added the answer to change class name much earlier than you, why did you add one more answer targeting the same property/solution?
Oh, I didn't see it, just saw that you propose changing style.width.
0

You can do the following to reset the image's CSS properties to whatever size your error image is:

function imgError(image) {
  image.onerror = "";
  image.src = "/images/broken.png";
  elem.style.width = "100px"; //use whatever size the new image is here
  elem.style.height= "100px"; //use whatever size the new image is here
  return true;
}

1 Comment

You can use elem.style - you need to change to image.style

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.