0

I have a jquery statement that replaces an image based on screen size

Fiddle

It only works on refresh though. I want it to automatically run when the user resizes their screen past my set of parameters.

I can't figure out how to do this.

JQUERY

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
    $(document).ready(function () {
        var screenWidth = $(window).width();
        if ((screenWidth) < 769) {
            $("#logoHolder img").attr("src" , "images/payday_ira_logo_stacked_web.png")
        } else {
            $("#logoHolder img").attr("src", "images/payday_logo_long_web.png")
        }
    });

html

<div class="d3-d4 m1" id="logoHolder">
    <img src="images/payday_logo_long_web.png" alt="Pay Day IRA" />
</div>
Mantosh
  • 11
  • 7
onTheInternet
  • 6,421
  • 10
  • 41
  • 74

2 Answers2

1

Try this:

window.onresize = function(event) {
    // your code goes here
};

Google "javascript screenresize event"

Mark Rijsmus
  • 627
  • 5
  • 16
0

As mentioned already, you want to bind a function to the window.onresize method. One big caveat, though: don't change the img SRC attribute every time resize is fired! One way to do this is by toggling a class on the image, not just its src. I've updated your Fiddle.

And here's how I updated your script:

$(document).ready(function () {
    imgSwap();
    $(window).on("resize", imgSwap);
});

function imgSwap() {
    var screenWidth = $(window).width(),
        $image = $("#logoHolder img");
    if (screenWidth < 769) {
        if ($image.hasClass("alt-img")) {
            $image.attr("src", "http://placehold.it/350x150").removeClass("alt-img");
        }
    } else {
        if (!$image.hasClass("alt-img")) {
            $image.attr("src", "http://placehold.it/150x50").addClass("alt-img");
        }
    }
}
Rodney G
  • 4,746
  • 1
  • 16
  • 15