NoName84 NoName84 - 3 months ago 25
jQuery Question

jQuery Image Swap Issue

I am trying to create a simple swap img src when the browser is resized to a smaller screen but for some reason my code is not working. Hope someone can help with this issue. I have the 2d image in the same folder as the first one.

Thanks

HTML Code:

<div class="body-bg">
<img src="img-01.jpg" class="img-01">
<h1>Example</h1>
<h2>Example</h2>
</div>


jQuery Code:

$(function(){

var $window = $(window);

function resize() {
if ($window.width() < 750) {
$('.img-01').attr('src','img-01.jpg');
}
else if ($window.width() > 750) {
$('.img-01').attr('src','img-02.jpg');
}
}

});

Answer

You're not actually running the resize function. Try replacing your javascript with this:

$(function(){
    var $window = $(window);

    function resize() {
        if ($window.width() < 750) {
            $('.img-01').attr('src','img-01.jpg');
        }
        else if ($window.width() > 750) {
            $('.img-01').attr('src','img-02.jpg');
        }
    }

    $window.on('resize', resize);
});

$window.on('resize', resize); runs the function on the window resize event.

Comments