Script to get tags with specific class and trigger onload

1

I need a JavaScript code that looks for all img tags with class load and enter the onload="loader(this)" function on them.

The idea here is that all images with class load are given the function of onload that will change the value of src to the value of the image.

It would work as a lazy load plugin, but without APIs.

If there is already something like this, let me know the link because I could not find something like this.

    
asked by anonymous 25.04.2014 / 00:51

2 answers

3

I think instead of injecting javascript inside the 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)
    });
}

Example online

Or, with another style of writing:

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)
}
    
25.04.2014 / 03:21
0

A solution using Jquery would be:

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

Demo

    
25.04.2014 / 02:01