jQuery Image Swap Not Showing Immediately - javascript

I'm using the jQuery code below to replace part of the image src. Basically it converts example.com/200x200/sample.jpg into example.com/500x500/sample.jpg.
It works fine only problem is it renders the old image first before showing the new one. Is it possible to load the swapped image first to improve user experience?
$(document).ready(function() {
$(".gallery img").each(function() {
$(this).attr("src", function(a, b) {
return b.replace("200x200", "500x500")
})
})
});
JSFiddle Demo
(Click "Run" multiple times)

Put the image in fixed position div that has overflow hidden and height and width of 0. This will cause the image to load but not display. Here is a fiddle showing the basic idea: https://jsfiddle.net/0tm3kb6e/. This image displays after 10 seconds. Use chrome to throttle the network and you will see that it is loaded by the time it is displayed. Here is the code I used. You just need the html and css
html
<div id="image-hider">
<img src="https://www.google.com/images/srpr/logo11w.png"/>
</div>
css
#image-hider {
height:0;
width: 0;
overflow: hidden;
position: fixed;
}
javascript
$(document).ready(function() {
setTimeout(function() {
$('#image-hider').css('height','500px');
$('#image-hider').css('width','500px');
}, 10000);
});

Try using a overlay div
<div class="gallery">
<img src="//lorempixel.com/200/200" />
<div class="overlaydiv"> </div>
</div>
Hide it after a second(giving some time for image to load)
$(".gallery img").each(function () {
$(this).attr("src",$(this).attr("src").replace("200/200", "400/400"));
setTimeout(function(){
$(".overlaydiv").hide();
},1000);
});
Check out this fiddle

Related

jQuery Fade In a New Image from a New URL on Hover without Getting White "Blink"

I am working within Squarespace so some of my options are limited (I can't add a separate image div and use that as a replacement, or if I can I'm not sure how). I am trying to slowly fade in a new image on hover but WITHOUT a full Fade Out -> Fade in Effect that results in a white "blink" in between.
Other solutions on StackOverflow all seemed to contain the full Fade Out/Fade In and did not work.
HTML:
<div id='#block-2091ad01016e0c16fbf5'>
<img class="thumb-image"
src="https://static1.squarespace.com/static/5cae826d21d24e00012dc02b/t/5e0a26c2afc7590ba0a3b443/1603914016365/Jason-5941.jpg">
</div>
JS:
<script>
(function($) {
$(document).ready(function() {
$('#block-76b0ced63f31cd9e2342').mouseover(function() {
$( "#block-76b0ced63f31cd9e2342 .thumb-image" ).attr("src","https://static1.squarespace.com/static/5cae826d21d24e00012dc02b/t/5fc2881b9ee0f32b87a52a14/1606584347864/Jason_Art.jpg");
});
$('#block-76b0ced63f31cd9e2342').mouseout(function() {
$( "#block-76b0ced63f31cd9e2342 .thumb-image" ).attr("src","https://static1.squarespace.com/static/5cae826d21d24e00012dc02b/t/5e0a26c2afc7590ba0a3b443/1603914016365/Jason-5941.jpg");
})
})
})(jQuery);
</script>
I think you're much better off creating a second from JS and get this crossfade effect from css. See fiddle for example:
https://jsfiddle.net/x0ye6r5L/
$(function() {
var jsonArt = '<img id="bottom-art-jason" src="https://static1.squarespace.com/static/5cae826d21d24e00012dc02b/t/5fc2881b9ee0f32b87a52a14/1606584347864/Jason_Art.jpg" class="thumb-image" />';
$('#myDiv').prepend(jsonArt);
});

How to make an element appear then disappear on click

I have been trying to make a random image appear on click by adding a fadeOut effect and then removing the class. when I click it works fine, but I don't know how to remove the class after a few milliseconds and then being able to appear again on another click. so far I have just been able to make it fade out on click, I have tried a setInterval function so that the class gets removed after 1 millisecond but didn't work so I erased it, but even then, I don't know how to make the .on('click', function()) function fire on every click, instead of just working once. any help or tips would be really appreciated. Thanks!
<style>
body {
background-color: black;
}
img {
opacity: 0;
width: 40px;
z-index: 0;
position: relative;
top: 3em;
}
</style>
<img class="red"
src="http://www.clker.com/cliparts/0/f/1/f/130267960774173786paint-
splash(red)-md.png" alt="">
<img class="blue" src="http://www.clker.com/cliparts/Q/3/H/u/Z/K/dark-blue-
splash-ink-hi.png" alt="">
<img class="yellow" src="http://www.clker.com/cliparts/3/y/m/m/p/P/yellow-
splash-ink-md.png" alt="">
<script>
$(document).ready(function(){
var red = $(".red");
var blue = $(".blue");
var yellow = $(".yellow");
var images = [red, blue, yellow];
$(document).on('click', function(){
$(images[(Math.floor(Math.random()*3))]).addClass("animated fadeOut");
});
})
//i should be able to click anywhere on the screen and a random image should appear and then fadeout each time there is a click
</script>
Try something like this:
$(document).on("click", function() {
$("#element").show(0, function() {
$("#element").fadeOut();
});
});
$("#element").hide();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<span id="element">Element</span>
It looks like you are using jQuery so you simply need to:
1) Create a function that hides the class. Example:
function hideStuff(){
$(".myimg").hide();
}
2) Add a class to your image files so they have a common selector (like "myimg" below). You may also want to add an "alt" attribute (was missing in your code). Example:
<img class="yellow myimg" src="http://www.clker.com/stuff" alt="image-three">
3) Add the timeout as part of your function with the amount of delay you want. While it is not required, you should include a variable name so you can call it in the future. Example:
var myTimeout = setTimeout( hideStuff, 5000);
Hopefully these will get you going in the right direction.
Both .fadeOut() and .hide() set display: none, which could effect your layout. I think you're looking to animate opacity to 0, and then in the callback function you can change the image source. I'd recommend using a div and setting the background-image property since divs are a bit more layout friendly. Also, you could either use classes and set the background-image property in the <style> section or you can make an array of the image urls and randomly pick from that (which is what I did here).
let images = [
'http://www.clker.com/cliparts/0/f/1/f/130267960774173786paint-splash(red)-md.png',
'http://www.clker.com/cliparts/Q/3/H/u/Z/K/dark-blue-splash-ink-hi.png',
'http://www.clker.com/cliparts/3/y/m/m/p/P/yellow-splash-ink-md.png'
];
$(document).on('click', function() {
let $img = $('.img'); //so you don't have to make a new object everytime it's used
if ($img.css('opacity') === '1') {
$img.animate({ opacity: 0 }, function() {
$img.css('background-image', `url(${images[Math.floor(Math.random()*3)]})`);
});
} else {
$img.animate({ opacity: 1 });
}
}).click().click(); //two clicks to initialize image
https://jsfiddle.net/yc4e4nxb/3/
NOTE: JSfiddle doesn't seem to like wherever these images are hosted, so it's working kind of erratically. Hopefully you get the gist of what this code is doing though.
http://api.jquery.com/animate/
If I understood the question correct, In This Fiddle the button element disappears when you click anywhere in the screen and then re appears immediately. Hope this will work.
$(document).ready(function(){
$(document).on('click',function(){
$("#myElement").fadeOut().delay(100).fadeIn();
});
});

change background image in no time

I am changing background image of a div on event basis,
There are two image
Image1
and
Image2
I have to use these two images on condition basis, it is working fine, but at first time when i change image, it takes time to load, how to load it instantly
div has image1 as default background image,
and I am changing it with below code
$("div").addClass('loadalternateImage');
alternate image is class with background-image with image2
but it take time to load Image2.
Please advise how to load it instantly
Thanks
You can preload both images in a div outside the viewport. So, when you click in order to change background, both images should have been loaded.
HTML:
<div class="img-container">
<img src="first/img" />
<img src="second/img" />
</div>
CSS:
.img-container {
position: fixed;
top: -100000px;
}
You can also bind the click event after page loads (not on document ready) in order for the images to get fully loaded:
$(window).load(function() {
$(document).on('click', '#your-div', function() {
// change background
});
});
Option 1
I suggest you to have a look at this post
Therefore, you could use the base64 encoding for your image and put it directly to your stylesheet:
loadalternateImage {
background: url(data:image/gif;base64,....) no-repeat left center;
}
Option 2
Alternatively, you could put this your into some invisible node, which would also trigger the preloading:
<img src="original.jpg">
<img src="secondary.jpg" style="display:none;">
Option 3
Use sprites - have a look at this post. It is the most difficult solution from the maintenance point of view
Ok retain the answer by #kapantzak but do this
Switch between
$("#imgBackground')[0].src = $("#firstImg")[0].src
and
$("#imgBackground')[0].src = $("#secondImg")[0].src
imgBackground is the id of IMG tag as your background.
//Code block from #kapantzak
$(window).load(function() {
$(document).on('click', '#your-div', function() {
// put the code above here..
});
});

Timed transition between image swaps with JQuery?

I have this code:
$('.pic_windows img').mouseenter(function () {
$(this).effect('shake', {
times : 4,
distance : 5
}, 15).attr('src', $(this).attr('src').replace(/.jpg/, '-1.jpg'))
});
$('.pic_windows img').mouseleave(function () {
$(this).attr('src', $(this).attr('src').replace(/-1.jpg/, '.jpg'))
});
where I'm using JQuery's .attr to swap the images, but I'd like the swapping to occur over the course of around 1 second. I've googled this and get all these complicated "CSS3 transitions with JQuery fallback" tutorials. Is there a way to 'animate' an .attr change?
I think I should do a fadeOut while the other fadeIn but I don't know how to write it, as I'm almost a complete JQuery newbie. I have a number of these transitions to do over the course of several pages. It'd be a cinch if I needed to write this for just one instance.
UPDATE On mouseenter, the image shakes and then should during this shake, fade from one picture to its swapped picture. On mouseleave, the image should just fade back to the original picture. Unfortunately I have also found that the shake effect is breaking on IE, all versions, as well as the image swap (it doesn't see image 2 at all)
No, you cannot animate an attribute change. What you can do is clone an element, change an attribute and transition between them.
var target = $(this).fadeOut();
var src = target.attr('src').replace(/-1.jpg/, '.jpg');
var copy = target.clone()
.attr('src', src)
.hide()
.insertAfter(target)
.fadeIn();
EDIT: Thank you for clarifying your intentions, I would advise not playing with the 'src', which will essentially require building a small stateful plugin. Instead, stick with the desired effect here, reveal an image on hover. jsFiddle
HTML
<div class="shaker">
<img src="http://lorempixel.com/output/nature-q-c-360-240-3.jpg" />
<img class="hover" src="http://lorempixel.com/output/technics-q-c-360-240-9.jpg" />
</div>​
CSS
.shaker {
position: relative;
}
.shaker img {
position: absolute;
}
.hover {
display: none;
}
JS
$('.shaker').hover(function () {
$(this).effect('shake', {
times: 4,
distance: 5
}, 15);
$(this).find('.hover').fadeIn();
}, function () {
$(this).find('.hover').stop().fadeOut();
});​
http://jsfiddle.net/eHQ3t/13/

Div is jumpy with fadeIn jQuery

When I roll over .comptext_rollover div it should hide the initial div on the page and show the minipage div. but it does but is sometimes really jumpy and also the minipage div sometimes shows below the initialpage div. any ideas? sorry i am new to coding! Thanks in advance.
$(document).ready(function() {
$('#mini_page').hide();
$('.comptext_rollover').hover(function() {
$('#initial_page').hide();
$('.register_button').hide();
$('#mini_page').fadeIn(100);
$('#container').css({
'margin-top': '-217px'
});
}, function() {
$('#mini_page').hide();
$('#initial_page').show();
$('.register_button').show();
$('#container').css({
'margin-top': '-150px'
});
});
});
I prepared a fiddle demo HERE
re-EDIT:
JSFIDDLE DEMO
(the demo may be incorrect while the main CSS is an external link)
I used:
<div id="container">
<div id="initial_page" class="page">
<div id="playvideo_hoverbutton"></div>
<div class="register_button"></div>
<div id="invisible_register2"></div>
<div id="termsandconditionsapplyshort"></div>
</div>
<div id="mini_page" class="page">
<div id="minicar_animated"></div>
<div id="worth25k"></div>
<div class="register_button"></div>
<div id="invisible_register"></div>
</div>
<!-- THE ROLLOVER IS OUT OF ALL 'PAGES'! -->
<div class="comptext_rollover">
<!--<div id="competition_text"></div>-->
</div>
</div>
$('#mini_page').hide();
$('.comptext_rollover').mouseenter(function() {
$('.page').fadeToggle(400);
});
$('.comptext_rollover').mouseleave(function() {
$('.page').fadeToggle(400);
});
In any case what you should do:
Position absolute the 2 screens you need to 'swap' into a container.
Than what you do:
Position the 'rollover' element outside the 'screens'.
Adjust the marginTop of the bigger image(car image) in the CSS (like I did) to fix the buggy 'jumps'.
IF POSSIBLE: ONLY ONE rollover ACTION ELEMENT!
Fix the margin-top of the car image. (give it a -Npx)
Doing so you don't need to do that stuff with positioning your container -Npx
There is also a simpler way to do the same effect:
you add to BOTH screens a class .swappable, making the second one (CSS)display:none; , and than you just use jQuery toggling just this class.
you've not set a great deal of time for the fade in. you're also just hiding some of the divs which makes the fade in move around depending on where you put them. maybe use slides instead. I have saved an example here: http://jsfiddle.net/kBEUH/
$(document).ready(function(){
$('#mini_page').hide();
$('.comptext_rollover').hover(function () {
$('#initial_page').fadeOut(1000);
$('.register_button').fadeOut(1000);
$('#mini_page').slideDown(1000);
}, function(){
$('#mini_page').slideUp(1000);
$('#initial_page').fadeIn(1000);
$('.register_button').fadeIn(1000);
});
});
if you put a console.log in your hover() function, you'll see hover is firing like crazy. This causes the animation to start over and over again, while moving your mouse.
You could take advantage of the jquery :animated selector:
$('.comptext_rollover').hover(function() {
//enable this line to see the hover event is firing every time your mouse moves
//console.log("hovering")
//if the div is in the middle of an animation, do nothing
if (!$("#mini_page").is(":animated")) {
$('#initial_page').hide();
$('.register_button').hide();
$('#mini_page').fadeIn(100);
$('#container').css({
'margin-top': '-217px'
});
}
}, function() {
//etc
});
EDIT:
Now I think of it, your probably want to use .mouseenter() and .mouseleave() instead of hover()
$('.comptext_rollover').mouseenter(function() {
//your code
}).mouseleave(function() {
//your code
});

Categories