jQuery switch image with fade - javascript

I have a script which changes some images on hover. Works really well, however I would like to add a little fade between the two images. Here is the script. Really new to jQuery so I'm a little confused where to add it. Any help would be appreciated
jQuery(document).ready(function ($) {
var img_src = "";
var new_src = "";
$(".rollover").hover(function () {
img_src = $(this).attr('src');
new_src = $(this).attr('rel');
$(this).attr('src', new_src);
$(this).attr('rel', img_src);
}, function () {
$(this).attr('src', img_src);
$(this).attr('rel', new_src);
});
//preload images
var cache = new Array();
//cycle through all rollover elements and add rollover img src to cache array
$(".rollover").each(function () {
var cacheImage = document.createElement('img');
cacheImage.src = $(this).attr('rel');
cache.push(cacheImage);
});

function imageSwitch(img) {
var src = img.attr('src');
var rel = img.attr('rel');
img.fadeOut('fast', function() {
img.attr('src', rel);
img.attr('rel', src);
img.fadeIn('fast');
});
}
$(".rollover").on('mouseenter', function() {
imageSwitch($(this));
});

a small search give me that : http://www.simonbattersby.com/demos/crossfade_demo_basic.htm i think it's kinda what you're looking for.
or else you with thread that do something also :
jQuery Change Image src with Fade Effect

it would be better to use .mouseenter for this.
and you could do .animate() opacity to 0 and in the call back you would change the image src, so that the src change after the animation ended.
$('.rollover').mouseenter(function () {
var me = $(this),
new_src = me.attr('rel'),
anmiation_duration = 300; // 300ms
me.animate({
opacity: 0
}, anmiation_duration, function () {
me.attr('src', new_src).css({'opacity':'1'});
})
});
After the src is changed you can do another .animate() to set the opacity back to 1.
I would however suggest to have the other image already displayed behind the first image, (images placed over each other using position:absolut). That way the opacity change would create sort of morf effect.

Briefly tested, thanks to #Oksid for the mouseenter comment.
EDITED
The HTML:
<img class="front rollover" src="http://placehold.it/350x150/006699" rel="http://placehold.it/350x150/000000" />
The CSS:
.image_holder {
position: relative;
}
.image_holder img {
position: absolute;
top: 0;
left: 0;
z-index: 1;
}
.image_holder img.front {
z-index: 2 !important;
}
The jQuery:
function init_rollovers() {
$(".rollover").each(function() {
var w = $(this).width()+'px';
var h = $(this).height()+'px';
var src = $(this).attr('src');
var rel = $(this).attr('rel');
$(this).addClass('shown');
if (!$(this).parents('.image_holder').length) {
$(this).wrap('<div class="image_holder" style="width:'+w+';height:'+h+';"></div>');
$(this).parents('.image_holder').append('<img src="'+rel+'" />');
}
});
}
init_rollovers();
function doImageSwitch(el, speed=425) {
var front = el.find(".front");
if (front.hasClass('shown')) {
front.fadeTo(speed, 0, function() {
$(this).removeClass('shown');
});
}
else {
front.animate({
opacity: 1
}, speed, function() {
$(this).addClass('shown');
});
}
}
$(document).on('mouseenter', '.image_holder', function() {
doImageSwitch($(this));
});

Related

Detect dynamically appended images load event pure javascript [duplicate]

Say, user opens a page, clicks on a button, and popup with images appears. How do I detect when all of the images have been loaded? I can't use window.onload here, since the page had already been loaded with all the assets. To make it clear, I want to find out final extents of the popup.
Popup is added to DOM like so:
var popup = document.createElement('div');
popup.innerHTML = '...';
document.body.appendChild(popup);
Simply:
var image = document.getElementById('image');
image.onload = function () {
alert ("The image has loaded!");
};
setTimeout(function(){
image.src = "http://lorempixel.com/500/500";
}, 5000);
<img id="image" src="">
See https://developer.mozilla.org/en-US/docs/Web/API/GlobalEventHandlers/onload and Javascript callback for knowing when an image is loaded for more.
Based on this answer. Hopefully that is enough.
var cons = document.querySelector('#console');
var popup = document.createElement('div');
popup.className = 'popup';
popup.innerHTML = _.range(10).map(function(i) {
return '<img src="http://via.placeholder.com/50/50">';
}).join('');
document.body.insertBefore(popup, cons);
waitForImages(popup).then(function() {
d('loaded');
})
function d(s) {
var text = document.createTextNode(s);
cons.appendChild(text);
var br = document.createElement('br');
cons.appendChild(br);
}
function waitForImages(el) {
var images = document.querySelectorAll('img');
return Promise.all(_.compact(_.map(images, function(img) {
if (img.complete) {
d('img.complete');
return;
} else
return new Promise(function(resolve, reject) {
img.addEventListener('load', function() {
d('onload event');
resolve();
});
});
})));
}
.popup {
overflow: hidden;
}
img {
float: left;
margin: 0 5px 5px 0;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/bluebird/3.5.0/bluebird.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>
<div id="console">
</div>

Detect when images added to DOM have been loaded

Say, user opens a page, clicks on a button, and popup with images appears. How do I detect when all of the images have been loaded? I can't use window.onload here, since the page had already been loaded with all the assets. To make it clear, I want to find out final extents of the popup.
Popup is added to DOM like so:
var popup = document.createElement('div');
popup.innerHTML = '...';
document.body.appendChild(popup);
Simply:
var image = document.getElementById('image');
image.onload = function () {
alert ("The image has loaded!");
};
setTimeout(function(){
image.src = "http://lorempixel.com/500/500";
}, 5000);
<img id="image" src="">
See https://developer.mozilla.org/en-US/docs/Web/API/GlobalEventHandlers/onload and Javascript callback for knowing when an image is loaded for more.
Based on this answer. Hopefully that is enough.
var cons = document.querySelector('#console');
var popup = document.createElement('div');
popup.className = 'popup';
popup.innerHTML = _.range(10).map(function(i) {
return '<img src="http://via.placeholder.com/50/50">';
}).join('');
document.body.insertBefore(popup, cons);
waitForImages(popup).then(function() {
d('loaded');
})
function d(s) {
var text = document.createTextNode(s);
cons.appendChild(text);
var br = document.createElement('br');
cons.appendChild(br);
}
function waitForImages(el) {
var images = document.querySelectorAll('img');
return Promise.all(_.compact(_.map(images, function(img) {
if (img.complete) {
d('img.complete');
return;
} else
return new Promise(function(resolve, reject) {
img.addEventListener('load', function() {
d('onload event');
resolve();
});
});
})));
}
.popup {
overflow: hidden;
}
img {
float: left;
margin: 0 5px 5px 0;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/bluebird/3.5.0/bluebird.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>
<div id="console">
</div>

How to animate with delay TweenMax.to?

I created an animation with TweenMax, that animate a div from 100% width of it's parent to zero. I have three divs next to each other, that are overlapping the image below. Now I would like that each preload div class will start some seconds after the previous one was triggered.
I try something like setTimeout, but I couldn't get it work.
How can I achieve above?
CodePen: https://codepen.io/anon/pen/aWVZXL
I have changed the script. Please refactor if you want.
$(document).ready(function() {
var toBeAnimated;
var currentAnimat = 0;
$('.link').click(function() {
toBeAnimated = $(".preloader");
console.log('lets start animation');
preload(toBeAnimated[currentAnimat]);
});
function preload(elem) {
var elem = $(elem);
var width = elem.outerWidth();
// Tween out preload div
TweenMax.to(elem, 1.4, {
width: 0,
right: 0,
onComplete: function() {
elem.remove();
currentAnimat++;
if(currentAnimat >= toBeAnimated.length) {
console.log('Animation done');
} else {
preload(toBeAnimated[currentAnimat]);
}
}
});
}
});

How to toggle multiple images in jquery?

HTML
<div class="image_rollover">
<img id="image_one" src=image_one.png">
<img id="image_two" src="image_two.png">
<img id="image_three" src="image_three.png">
<img id="image_four" src="image_four.png">
<img id="image_five" src="image_five.png">
<img id="image_six" src="image_six.png">
</div>
CSS
.image_rollover{
border:1px solid #000000;
width:130px;
height:80px;
overflow:hidden;
}
Script
$(document).ready(function(){
$("#image_two, #image_three, #image_four, #image_five, #image_six").hide();
$(".image_rollover").hover(function(){
$(this).find("#image_one, #image_two, #image_three, #image_four, #image_five, #image_six").toggle();
});
});
When I hover mouse over the div, first image changes to second image and then nothing happens. When I hover mouse over the div, I want to change the image one by one from "image_one" to "image_six".
Does any one know how to do this???
http://jsfiddle.net/p7dsm1h7/
$(document).ready(function () {
$("#image_two, #image_three, #image_four, #image_five, #image_six").hide();
$(".image_rollover").hover(function () {
animation()
});
});
function animation() {
var $curr=$(".image_rollover img:visible");
var $next=$curr.next();
if($next.size()==0) $next=$(".image_rollover img:first");
$next.show();
$curr.hide();
}
or maybe something like this
UPDATE
http://jsfiddle.net/9v8ykfjs/2/
var hover=false;
var interval;
$(document).ready(function () {
$("#image_two, #image_three, #image_four, #image_five, #image_six").hide();
$(".image_rollover").hover(function () {
hover=true;
animation()
},function(){
hover=false;
clearTimeout(interval);
$(".image_rollover img:visible").hide();
$(".image_rollover img:first").show();
});
});
function animation() {
if(hover==false) return;
var $curr=$(".image_rollover img:visible");
var $next=$curr.next();
if($next.size()==0) $next=$(".image_rollover img:first");
$next.show();
$curr.hide();
interval=setTimeout(function(){ animation(); }, 1000);
}
$(document).ready(function(){
$('.image_rollover img').hide();
var index = 0;
var $imageRollover = $('.image_rollover');
var maxIndex = $imageRollover.find('img').length;
$imageRollover.on('mouseenter', function(){
$('.image_rollover img').hide();
console.log(index);
$imageRollover.find('img').eq(index).show();
index++;
if (index >= maxIndex) {
index = 0;
}
});
});
You can also see http://jsfiddle.net/2q2ycbdz/2/
Note that will be better if you hide your images by css and if you simplify the selector to get all images inside the div (or group those images with a class).
Check out this:
JS
$(document).ready(function(){
$(".image_rollover").hover(function(){
$(this).find("img").toggle();
});
});
CSS
.image_rollover{
border:1px solid #000000;
width:130px;
height:80px;
overflow: hidden;
}
.image_rollover img{
display: none;
}
HTML
<div class="image_rollover">
<img id="image_one" src=image_one.png">
<img id="image_two" src="image_two.png">
<img id="image_three" src="image_three.png">
<img id="image_four" src="image_four.png">
<img id="image_five" src="image_five.png">
<img id="image_six" src="image_six.png">
</div>
Check out this codepen.
JS
jQuery(document).ready(function(){
var current_image = 1;
jQuery('.image_rollover').hover(function(){
jQuery('.image_rollover img').hide();
jQuery('.image_rollover img:nth-child('+current_image+')').show();
current_image = current_image + 1;
if (current_image == 7)
current_image = 1;
},function(){});
});
jsFiddle demo
$('.image_rollover').hover(function(){
$("img:first", this).appendTo(this);
});
If you are looking with some animation. Try this.
$(document).ready(function () {
var $siblings = $("#image_one").siblings();
$siblings.hide();
$("#image_one").on("mouseenter", function () {
var timer = 100;
var showTime = 0;
$siblings.each(function () {
showTime += timer;
$(this).fadeIn(showTime).show()
})
});
});
Or If you wants a chain kind of animation try this:
So if you hover on first image, then second will appear, then if on second then third and so on.. is it what you are looking for??
$(document).ready(function () {
var $siblings = $("#image_one").siblings();
$siblings.hide();
var timer = 500;
var showTime = 0;
function init_chain(ev){
showTime += timer;
var $next_element = $(ev.target).next()
$next_element.fadeIn(showTime).show();
$next_element.bind("mouseenter",init_chain);
};
$("#image_one").on("mouseenter", function (event) {
init_chain(event);
});
});
Let us know.
Thanks!

JS if there is a slider show it

I'm no JS expert but I'm trying to alter this so that if there is a royalslider display it… if there isn't display the static image and the title and description. Any ideas as to why this isn't working? my head is currently spinning… I've left some space around the section I'm trying to add to the code under //royal slider fix and currently its just showing the title and description from the if statement. But, the markup is showing the slider div and outputting the code.
Any help would be very appreciated! You can preview this code and what I'm trying to do here... http://bvh.delineamultimedia.com/?page_id=2
;(function($) {
$.fn.SuperBox = function(options) {
var superbox = $('<div class="superbox-show"></div>');
var superboximg = $('<img src="" class="superbox-current-img">');
var superboxclose = $('<div class="superbox-close"></div>');
superbox.append(superboximg).append(superboxclose);
return this.each(function() {
$('.superbox').on('click', '.superbox-list', function() {
//allows for superbox to work inside of quicksand
$('ul.filterable-grid').css({overflow: 'visible'});
var currentimg = $(this).find('.superbox-img');
superbox.find('.title').remove();
superbox.find('.description').remove();
var imgData = currentimg.data();
superboximg.attr('src', imgData.img);
if (imgData.title) { superbox.append('<h3 class="title">'+imgData.title+'</h3>'); }
if (imgData.description) { superbox.append('<div class="description">' + imgData.description + '</div>'); }
//royal slider fix
superbox.find('.royalSlider').remove(); // remove the slider from previous events
var imgData = currentimg.data();
var sliderData = currentimg.next('.royalSlider'); // grab the slider html that we want to insert
superboximg.attr('src', imgData.img);
if (sliderData) { // show the slider if there is one
superbox.clone().append(sliderData); // clone the element so we don't loose it for the next time the user clicks
} else { // if there is no slider proceed as before
if (imgData.img) {
superbox.append(imgData.img);
}
if (imgData.title) {
superbox.append('<h3 class="title">' + imgData.title + '</h3>');
}
if (imgData.description) {
superbox.append('<div class="description">' + imgData.description + '</div>');
}
}
if($('.superbox-current-img').css('opacity') == 0) {
$('.superbox-current-img').animate({opacity: 1});
}
if ($(this).next().hasClass('superbox-show')) {
superbox.toggle();
} else {
superbox.insertAfter(this).css('display', 'block');
}
$('html, body').animate({
scrollTop:superbox.position().top - currentimg.width()
}, 'medium');
});
$('.superbox').on('hover', '.superbox-list', function(e) {
$(this).find('.overlay').stop()[(e.type == 'mouseenter') ? 'fadeIn' : 'fadeOut']('slow');
});
$('.superbox').on('click', '.superbox-close', function() {
$('.superbox-current-img').animate({opacity: 100}, 200, function() {
$('.superbox-show').slideUp();
});
});
});
};
})(jQuery);
This is only intended to be hints, not an attempt to solve the entire problem.
Try this:
var superbox = $('<div class="superbox-show"/>');
var superboximg = $('<img src="" class="superbox-current-img"/>');
var superboxclose = $('<div class="superbox-close"/>');
if (sliderData.length > 0)
Where is imgData.img getting its value?

Categories

Resources