Script to pick tags with specific class and trigger onload

Asked

Viewed 297 times

1

I need a Javascript code that searches all tags img with class load and insert the function onload="loader(this)".

The idea in this is that all images with the class load receive the function of onload that will change the value of src by the image value.

Would work as a plugin Lazy load, but without Apis.

If there is already something of the type here indicate me the link because I could not find something of the type.

  • In pure javascript, or using some library, such as jQuery?

  • 1

    But the onload won’t run only when the image is already loaded? How can this be a Lazy load? (And if you’re thinking about remove the src, then the onload will never perform - as the "image loaded" event will not fire until it is actually loaded...)

  • Jose, the way to mark a question as "solved" is to choose an answer and mark it as correct. Or publish your own solution, citing the answers that helped, and mark this as correct.

2 answers

3


I believe that instead of injecting javascript into html it is better to tie Event handlers to the desired images...

If you want to use pure javascript you can use it like this in two +/- similar versions:

var imagens = document.getElementsByTagName('img');
for (var i = 0; i < imagens.length; i++) {
    imagens[i].addEventListener('load', function (e) {
        loader(this)
    });
}

Online example

Or, with another writing style:

function loader(event) {
    var estaImagem = event.target; // e usar "estaImagem" em vez de "this" como sugere
}
var imagens = document.getElementsByTagName('img');
for (var i = 0; i < imagens.length; i++) {
    imagens[i].addEventListener('load', loader)
}

0

A solution using Jquery would be:

$(function(){
    $('img.load').attr('onload','loader(this)');
});

Demo

Browser other questions tagged

You are not signed in. Login or sign up in order to post.