0

I want a logo image to responsively change between small and large. Here's my code:

v.checkIfMobile = function() {
    var newIsMobile = window.matchMedia("(max-width: 60em)").matches;
    var valueToReturn = (v.isMobile != newIsMobile);
    v.isMobile = newIsMobile;
    return valueToReturn;
}

v.responsiveAdjust = function() {
    console.log("will now check mobile status");
    if(v.checkIfMobile()) {
        console.log("mobile status changed");
        var src = "local/images/logo"
            + (v.isMobile ? "Mobile" : "Desktop") + ".png";
        $("#logo").attr("src", src);
        console.log("src should have changed");
    }
}

v.responsiveAdjust();
$(window).on("orientationchange", v.responsiveAdjust);
$(window).resize(v.responsiveAdjust);

Almost every time, the source simply doesn't change, but once or twice reloading the page did it. I've put a breakpoint right after the command and it made no difference. I've used both prop and attr, and I know the code is being processed because of the console messages.

Finally, when I enter the relevent code into the console after the page has loaded, it works as expected. Could there be a race condition? It's weird because the actual text of the src attribute doesn't change (until I do the console entry or unless I'm lucky) which doesn't sound like an effect of the time it takes to load the image.

What should I do?

  • Is there any reason that you're using JS to do this instead of CSS? Seems a far easier task to use CSS and background images. – sbeliv01 Dec 29 '15 at 16:49
  • Well, I want everything (for example, text next to the image) to move in accordance with the image size. I suppose I could also put the dimensions into the CSS, but that would be hard-coding something that could change. – Chris Morrow Dec 29 '15 at 17:05
  • 1
    Changing the `src` attribute won't reload the image like you think it should. [This answer](http://stackoverflow.com/a/30061734/2030565) links other similar questions. – Jasen Dec 29 '15 at 17:10
  • That seems like it should work. Unfortunately it still doesn't. That's actually not too surprising since the dev tools don't think the src is any different either (as if it's not just a failure of the image to load.) EDIT: Never mind! I had a typo, and didn't see the error because my console log was scrolled up. It seems to work now. Thank you! – Chris Morrow Dec 29 '15 at 17:14
  • The only way I've managed to change an image across various browsers was to completely replace the `` element then use a `src` that used a [cache-buster](http://stackoverflow.com/questions/118884/how-to-force-browser-to-reload-cached-css-js-files). I also use the image's load event to prevent screen flicker. The linked answer does exactly what I outlined, however, without a cache-busting url. – Jasen Dec 29 '15 at 17:29

0 Answers0