onTheInternet
onTheInternet

Reputation: 7253

jquery image replacement on screen size adjustment

I have some jquery that will replace an image when the screen size goes below 600 pixels.

<script type="text/javascript">
    jQuery(window).on("load resize", function (e) {
        jQuery(function () {
            if (jQuery(window).width() <= 600) {
                jQuery("img").each(function () {
                    jQuery(this).attr("src", jQuery(this).attr("src").replace("img/my_safe_net_hero_img_knight_2014_2.jpg", "img/my_safe_net_knight_mob_version_2014.png"));
                });
            }

        });
    });
</script>

This works, but if you want to enlarge the screen again, the smaller image remains. I thought I could fix it by adding an else statement, but it doesnt work. It seems to break the whole thing when I do that.

<!--Hero Image Replacement-->
<script type="text/javascript">
    jQuery(window).on("load resize", function (e) {
        jQuery(function () {
            if (jQuery(window).width() <= 600) {
                jQuery("img").each(function () {
                    jQuery(this).attr("src", jQuery(this).attr("src").replace("img/my_safe_net_hero_img_knight_2014_2.jpg", "img/my_safe_net_knight_mob_version_2014.png"));
                });
            }
            else {
                jQuery(this).attr("src", jQuery(this).attr("src").replace("img/my_safe_net_knight_mob_version_2014.png" , "img/my_safe_net_hero_img_knight_2014_2.jpg" ));
            };
        });
    });
</script>

What is wrong with the script above. Should I be using something different to achieve this?

Here is a Fiddle of my code

Upvotes: 1

Views: 130

Answers (1)

FrancescoMM
FrancescoMM

Reputation: 2960

Try this:

http://jsfiddle.net/kgnfqbxs/1/

    jQuery(window).on("load resize", function (e) {
             if (jQuery(window).width() <= 600) {
                jQuery("img").each(function () {
                    jQuery(this).attr("src", jQuery(this).attr("src").replace("http://placehold.it/350x150", "http://placehold.it/150x150"));
                });
             } else {
                jQuery("img").each(function () {
                    jQuery(this).attr("src", jQuery(this).attr("src").replace("http://placehold.it/150x150", "http://placehold.it/350x150"));
                });
             }

    });

Please consider that this will uselessly loop every image in your page, there are better ways, if you can, like giving your image an id="myimage" and then just:

jQuery("#myimage").attr("src","http://placehold.it/150x150");

jQuery("#myimage").attr("src","http://placehold.it/350x150");

Upvotes: 1

Related Questions