Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Prevent alt text of an img tag from being rotated when the image is not found

Tags:

html

css

I have applied transform: rotate(90deg); CSS on my image, but it is also rotating ALT text, which is causing this text to appear over other image whenever image is not found.

Is there any why in which I can prevent ALT text from getting rotated?

<div>
<img style="transform: rotate(90deg);" alt="User Name" src="http://ImageURL">
</div>

ALT text

div { margin-top:50px; }
<div>
    <img style="transform: rotate(90deg);" alt="User Name" src="http://ImageURL">
    </div>

EDIT

I am having a lot of images on the page.

like image 574
nbi Avatar asked May 11 '18 05:05

nbi


3 Answers

You can use the onerror handler to remove the styles from your image:

function onImageNotFound() {
  document.getElementById('imgTest').style.transform = 'none';
}
div { margin-top:50px; }
<div>
    <img id="imgTest" style="transform: rotate(90deg);" alt="User Name" src="http://ImageURL" onerror="onImageNotFound();">
</div>

And here is an inline version:

div { margin-top:50px; }
<div>
    <img style="transform: rotate(90deg);" alt="User Name" src="http://ImageURL" onerror="this.style.transform = 'none';">
</div>
like image 98
klugjo Avatar answered Oct 22 '22 03:10

klugjo


The best solution is probably to apply the transformation only on loaded images:

for (let img of document.querySelectorAll("img")) {
  img.addEventListener("load", function(){
    this.classList.add("rotated");
  });
}
div { margin-top:50px; }
.rotated { transform: rotate(90deg); }
<div>
    <img alt="User Name" src="http://ImageURL">
</div>
<div>
    <img alt="User Name" src="https://dystroy.org/spacebullet-48.png">
</div>
like image 25
Denys Séguret Avatar answered Oct 22 '22 03:10

Denys Séguret


If you are only applying the effect to one (small) image you could do something like this with CSS.

Place a non-rotated copy of the image behind the rotated image. If the image loads, the rotated version will show. If it fails, the alt text of the non-rotated version will show.

div {
  margin-bottom: 50px;
  border: 1px solid red;
  position: relative;
  /* hide the broken image icon */
  overflow: hidden;
}

img {
  display: inline-block;
  vertical-align: bottom;
}

.img-rotate {
  transform: rotate(90deg);
  /* hide the alt text */
  color: transparent;
}

.img-copy {
  position: absolute;
  left: 0;
  z-index: -1;
}
<p>Broken image link</p>
<div>
  <img class="img-rotate" alt="User Name" src="http://ImageURL">
  <img class="img-copy" alt="User Name" src="http://ImageURL">
</div>

<p>Working image link</p>
<div>

  <img class="img-rotate" alt="User Name" src="https://unsplash.it/200">
  <img class="img-copy" alt="User Name" src="https://unsplash.it/200">
</div>
like image 29
sol Avatar answered Oct 22 '22 04:10

sol