Need to store some data in window.load and retrieve in document.ready:
<script>
$(window).load(function() { // Store here
$('img.storable').each(function() {
$(this).data("key", "value");
console.log($(this).data("key")); // Output: value
};
};
$(document).ready(function() { // Retrieve here
$('img.storable').each(function() {
console.log($(this).data("key")); // Output: undefined!
};
};
</script>
Output in document.ready is undefined. Am I missing something about DOM events?
$(document).ready()runs as soon as the DOM has loaded, but$(window).load()will not run until the DOM has loaded AND all dom resources have loaded (like images and CSS files and stuff). That means that$(document).ready()will run before you set the value.