DanDaMan DanDaMan - 2 months ago 12
CSS Question

Replacing image based on screen size with Jquery

I'm attempting to change an image src based on the screen size.

This is my html:

<div id="crew-content">
<img id="crewimage" src="resources/images/thecrew.png" alt="Header Image"></img>
</div>


And this is my jquery:

$(document).ready(function() {
$(function() {
if($(window).width() < 568) {
$("#crewimage").each(function() {
$(this).attr("src", $(this).attr("src").replace("resources/images/thecrew.png", "resources/images/thecrewmobile.png"));
});
} else if ($(window).width() >= 568) {
$("#crewimage").each(function() {
$(this).attr("src", $(this).attr("src").replace("resources/images/thecrewmobile.png", "resources/images/thecrew.png"));
});
}
});
});


My logic seems solid. I'm not sure why its not functional.

Thanks for the help in advance.

Answer

You need to use jquery's resize function.

Working Fiddle : https://jsfiddle.net/f0ngoLkq/1/

HTML

<div id="crew-content">
    <img id="crewimage" src="http://completewebgraphics.com/wp-content/uploads/2015/11/Mobile-Apps-Development-in-India.jpg" alt="Header Image" />
</div>

jQuery Code

$(window).resize(function(e){
   if($(window).width() < 568) {
   console.log($(window).width());
    $("#crewimage").each(function() {
      $(this).attr("src", "http://s3.amazonaws.com/libapps/customers/1633/images/icon_52143.png");
                });
            } else if ($(window).width() >= 568) {
                $("#crewimage").each(function() {
                $(this).attr("src","https://ithemes.com/wp-content/uploads/2012/07/mobile300.png");
                });                        
    }         
});

Hope this helps!