Reputation: 73
I'm attempting to change an image src based on the screen size.
$(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"));
});
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="crew-content">
<img id="crewimage" src="resources/images/thecrew.png" alt="Header Image"></img>
</div>
My logic seems solid. I'm not sure why its not functional.
Thanks for the help in advance.
Upvotes: 0
Views: 4051
Reputation: 1360
Use window resize
$(window).resize(function(){
$(function() {
if($(window).width() < 568) {
$(".crewimage").each(function() {
$(this).attr("src","resources/images/thecrewmobile.png");
});
});
} else if ($(window).width() >= 568) {
$(".crewimage").each(function() {
$(this).attr("src","resources/images/thecrew.png");
});
});
});
Upvotes: 0
Reputation: 15647
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!
Upvotes: 2
Reputation: 32354
Don't use replace:
<img class="crewimage" src="resources/images/thecrew.png" alt="Header Image"></img>
$(function() {
if($(window).width() < 568) {
$(".crewimage").each(function() {
$(this).attr("src","resources/images/thecrewmobile.png");
});
} else if ($(window).width() >= 568) {
$(".crewimage").each(function() {
$(this).attr("src","resources/images/thecrew.png");
});
}
});
note: the images will change only if you refresh the page after the window resize, if you want to change automatically on resize use the resize event
second change the ids to classes if you have multiple divs, if you have just one div remove the each loop
Upvotes: 0