Suppose there is a hypothetical code:
$(window).on('load resize', function() { var img = document.createElement('img'); img.src = 'img/bg.jpg'; var imgAspectRatio = img.naturalWidth/img.naturalHeight; var $bg = $('.bg'), bgAspectRatio = $bg.outerWidth() / $bg.outerHeight(); if (bgAspectRatio > imgAspectRatio) { $bg.css('backgroundSize', 'cover'); } else { $bg.css('backgroundSize', 'auto ' 500px'); } });
How you can make the variable Declaration imgAspectRatio out with the condition that it remains in local scope and can be used by other functions? Particularly interested in the answer to the question, what are common practices (best practices) for dealing with such situations, what are the patterns used? I apologize in advance, if not correctly formulated a question, in js I'm new.