Replacing image based on screen size with Jquery - javascript

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.

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!

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

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");
});
});
});

Related

Updating the HTML on real time using jQuery

On the desktop sizes, my navbar brand includes only one larger image. But on the mobile sizes I want that larger image to be replaced with two smaller images. For that, I have used jQuery and when I check it on the mobile it looks just how I wanted to. But the problem is that as I change my browser's size the image is not being replaced in real time. Is there a way I could achieve this?
$(document).ready(function() {
if ($(window).width() < 575.98) {
$('.navbar-brand').children().remove();
$('.navbar-brand').append('<img src="assets/images/Llogo AIP.png"><img src="assets/images/CoA RKS.png">');
}
});
<a class="navbar-brand" href="index.html"><img src="assets/images/logo.png"></a>
To get the code to be executed on resizing the window you should use .resize():
The resize event is sent to the window element when the size of the browser window changes.
$(window).resize(function() {....
Demo:
$(document).ready(function() {
if ($(window).width() < 575.98) {
$('.navbar-brand').children().remove();
$('.navbar-brand').append('<img src="https://homepages.cae.wisc.edu/~ece533/images/pool.png"><img src="https://homepages.cae.wisc.edu/~ece533/images/fruits.png">');
}
$(window).resize(function() {
if ($(window).width() < 575.98) {
$('.navbar-brand').children().remove();
$('.navbar-brand').append('<img src="https://homepages.cae.wisc.edu/~ece533/images/pool.png"/><img src="https://homepages.cae.wisc.edu/~ece533/images/fruits.png"/>');
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<a class="navbar-brand" href="index.html"><img src="assets/images/logo.png"></a>
This behavior is because the image is only replaced at document ready, aka when the document has finished loading.
If you want to change the images on window resize you need the resize event handler, as Mamun pointed out.
In that case you probably also want to switch back to the original image when you make the screen larger. I would make a separate function to handle setting the correct images and call it on window resize and on document ready. For example:
$(document).ready(function() {
setNavImages();)
});
$(window).resize(function(){
setNavImages()
});
function setNavImages(){
if ($(window).width() < 575.98) {
$('.navbar-brand').children().remove();
$('.navbar-brand').append('<img src="assets/images/Llogo AIP.png"><img src="assets/images/CoA RKS.png">');
}else{
$('.navbar-brand').children().remove();
$('.navbar-brand').append('<img src="[your original image here]">');
}
}
Like #Mamun said and call it on document ready
or better use bootstrap hidden-xs visible-md classes
$(document).ready(function() {
$(window).resize(function() {
if ($(window).width() < 575.98) {
$('.navbar-brand').children().remove();
$('.navbar-brand').append('<img src="assets/images/Llogo AIP.png"><img src="assets/images/CoA RKS.png">');
}
});
$(window).resize(); // call it here after define it
});
<a class="navbar-brand" href="index.html"><img src="assets/images/logo.png"></a>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
With this code the navbar will change like you want, on every resize, for example.
$(document).ready(function() {
navbarBrandContent = $('.navbar-brand').html();
changeNavbarBrand();
});
$(window).resize(function() {
changeNavbarBrand();
});
function changeNavbarBrand() {
if ($(window).width() < 575.98) {
$('.navbar-brand').children().remove();
$('.navbar-brand').append('<img src="assets/images/Llogo AIP.png"><img src="assets/images/CoA RKS.png">');
} else {
$('.navbar-brand').html(navbarBrandContent);
}
}

Why does this jQuery code works only once?

I have this short jQuery code to make the picture disappear when the window is resized. For some reason, after it disappears, it doesn't appear again.
Here is the code:
$(document).ready(function(){
$(window).resize(function(){
if($(window).width() < 700) {
$("#side-pic").css("display","none");
} else if($(window).width() >= 700){
$("#side-pic").css("display","show");
}
});
});
Also if by any chance you know if there is a way to make picture move under a certain div in my code, I'll be glad to hear it! Thank you guys in advance!
There is no display property such as display: show. Try using $("#side-pic").css("display","block"); instead.
Another Alternative would be hide/show:
$(document).ready(function(){
$(window).resize(function(){
if($(window).width() < 700) {
$("#side-pic").hide();
}
else if($(window).width() >= 700) {
$("#side-pic").show();
}
});
});
That's because the "show" is not a valid display value. https://developer.mozilla.org/en-US/docs/Web/CSS/display
Also, why the else if, isn't an else good enough?
Or rather a reusable CSS class and jQuery's toggleClass() Method:
jQuery( $ => {
$(window).on('resize', function() {
$("#side-pic").toggleClass("is-hidden", $(this).width() < 700);
});
});
.is-hidden {display: none;}
<div id="side-pic">SIDE PIC</div>
<script src="//code.jquery.com/jquery-3.1.0.js"></script>
You can also write a code Like following
$(document).ready(function(){
$(window).resize(function(){
if($(window).width() < 700) {
$("#side-pic").hide();
} else if($(window).width() >= 700){
$("#side-pic").show();
}
});
});

How do I use multiple functions in jQuery?

I've added jQuery function that shows and hides navbar when scrolled. I also want to hide a div when the button 'start' is clicked. After i add new function none of them works longer. I have tried to add it to various places, but I still get no result at all. So how do I add multiple functions and make them to work?
Heres my code:
<script>
// function that hides text on click
(function($) {
$('#start').click(function() {
$('.lead').hide());
});
});
// my original function that stopped working after i added new one
(function($) {
$(document).ready(function() {
$(".masthead").css("background-color", "inherit");
// fade in .navbar
$(function() {
$(window).scroll(function() {
// set distance user needs to scroll before we fadeIn navbar
if($(this).scrollTop() > 600) {
$('.masthead').fadeIn();
$(".masthead").css("background-color", "black");
} else if($(this).scrollTop() === 0) {
$('.masthead').fadeIn();
$(".masthead").css("background-color", "inherit");
} else {
$('.masthead').fadeOut();
}
});
});
});
}(jQuery));
</script>
I think the problem is in the closing tag of the function you're adding.
Try like this:
(function ($){
$('#start').click(function(){
$('.lead').hide();
});
}(jQuery));
// my original function that stopped working after i added new one
(function ($) {
$(document).ready(function(){
$(".masthead").css("background-color","inherit");
// fade in .navbar
$(function () {
$(window).scroll(function () {
// set distance user needs to scroll before we fadeIn navbar
if ($(this).scrollTop() > 600) {
$('.masthead').fadeIn();
$(".masthead").css("background-color","black");
} else if($(this).scrollTop() === 0){
$('.masthead').fadeIn();
$(".masthead").css("background-color","inherit");
} else {
$('.masthead').fadeOut();
}
});
});
});
}(jQuery));
At least, closing bracket is wrong here. $('.lead').hide());
Tip: always check developer console first. Have fun coding.
Edit : Note that you have an extra closing bracket in the first function $('.lead').hide());.
You can use the following. Both functions can be combined in to a single block. And you can use $(document).ready() directly. If there is a problem with name conflict for $ use jQuery.noConflict();
<script>
$(document).ready(function() {
$(".masthead").css("background-color", "inherit");
// fade in .navbar
$('#start').click(function() {
$('.lead').hide();
});
$(window).scroll(function() {
// set distance user needs to scroll before we fadeIn navbar
if ($(this).scrollTop() > 600) {
$('.masthead').fadeIn();
$(".masthead").css("background-color", "black");
} else if ($(this).scrollTop() === 0) {
$('.masthead').fadeIn();
$(".masthead").css("background-color", "inherit");
} else {
$('.masthead').fadeOut();
}
});
});
</script>

Scroll function activates before scrolling

So i have this code on my page
jQuery
$(window).scroll(function(){
if ($(this).scrollTop() > 785) {
$('#navbar').addClass('fixed');
} else {
$('#navbar').removeClass('fixed');
}
});
css
.fixed {position:fixed; top:0; left:0;}
My problem
When i load the page #navbar seems to have .addClass('fixed'); before scrolling. If i scroll just 1px after loading the page then .removeClass('fixed') activates and is activated until i dont get below 785px.
How do i fix so fixed doesnt activate when i load the page?
Why not just remove it on load?
$(function() { $('#navbar').removeClass('fixed'); }); // this should remove it on load
$(window).scroll(function() {
if ($(this).scrollTop() > 785) {
$('#navbar').addClass('fixed');
} else {
$('#navbar').removeClass('fixed');
}
});
try 'resetting' the state once DOM loads, as follows:
function _setClass() {
if ($(window).scrollTop() > 785) {
$('#navbar').addClass('fixed');
} else {
$('#navbar').removeClass('fixed');
}
}
_setClass();
$(window).scroll(function(){
_setClass();
});
$(function(){ _setClass() });
hope that helped.

jQuery Scroll function after 100px

Using this script:
<script>
$(function() {
$(window).scroll(function(){
$('#Your element id').slideUp('slow');
});
});
</script>
Is it possible only to perform the action after the user has scrolled 100px or more?
You do need scrollTop as said. It would be wise to include an 'else' function as well, so that when you scroll back to the top the toggled element gets hidden again. As such:
$(document).ready(function() {
$('#scrollDiv').hide();
$(window).scroll(function() {
if ($(document).scrollTop() > 100) {
$('#scrollDiv').fadeIn('slow');
}
else {
$('#scrollDiv').fadeOut('slow');
}
});
});​
Here is a quick jsfiddle
You can use .scrollTop() to get how far the page has been scrolled
<script>
$(function() {
$(window).scroll(function(){
if($(this).scrollTop() > 100) {
$('#Your element id').slideUp('slow');
}
});
});
</script>

Categories

Resources