Programming Tips - jQuery: do something when an image is loaded

Date: 2022sep16 Library: jQuery Language: javaScript Keywords: onload Q. jQuery: do something when an image is loaded A. For jQuery >= 3
$(document).ready(function() { $('#myimg').one('load', function() { const naturalWidth = this.naturalWidth; const naturalHeight = this.naturalHeight; console.log('natural=' + naturalWidth + ' x ' + naturalHeight); const width = $(this).width(); const height = $(this).height(); console.log('My image is loaded, size=' + width + ' x ' + height); }) .one('error', function() { console.log('load failed'); }) .each(function() { if (this.complete) { $(this).trigger('load'); } else if (this.error) { $(this).trigger('error'); } }); });
Not to be confused with the load() function.