Background-Image fade jquery - javascript

I have a div and I want to fade in and out of 5 different background images at random.
I have downloaded a jquery plugin for this, but unfortunately it alternates - I'll explain.
You must set a default background image (for this case lets say "image1") and then load an array of images (say image2, image3, image4, and image5). What the plugin does is duplicate the div and place it directly over the original one, then fades in and then out one of the array of images. The undesirable effect that I'm getting from this is:
1,2,1,3,1,4,1,5
as opposed to:
1,2,3,4,5
Because the fade out simple reveals the default image once again.
Without re-inventing the wheel is there a way to modify the code to that when the fade-in animation is complete (the default is completely concealed) I swap out the image on the background div so that when the fade out begins there's a new image below? I'm relatively new to JQuery and so this is not my strength.
Heres the action part of the plugin:
var tempImage = new Image();
jQuery(tempImage).load( function(){
var newImage = ( helperElement.css('display') == 'block' ) ? jQuery(this) : jQuery(helperElement);
newImage.css('backgroundImage', 'url('+tempImage.src+')');
helperElement.animate( settings.effect, settings.duration, settings.easing, settings.callback );
});
tempImage.src = src;
And in my HTML:
<script>
document.getElementById('content_container_home').style.backgroundImage = "url('img/buttons.jpg')";
$( function(){
var bgImages = [ 'barker.jpg', 'boards.jpg', 'feet.jpg', 'glasses.jpg' ];
var currImage = 'buttons.jpg';
setInterval( function(){
do{
var randImage = bgImages[Math.ceil(Math.random()*(bgImages.length-1))];
}while( randImage == currImage )
currImage = randImage;
$('#content_container_home').BgImageTransition( 'img/'+currImage );
}, 5000)
});
</script>

Check out my answer to another question
This should do the trick:
HTML:
<div id="testers">
<div class="tester">
<img src="http://regmedia.co.uk/2008/03/18/google_adwords_machine.png" alt="" />
</div>
</div>
<div id="morework">
<div class="holderdiv">
<div class="tester">
<img src="http://www.swwebs.co.uk/images/google-pagerank.jpg" alt="" />
</div>
</div>
<div class="holderdiv">
<div class="tester">
<img src="http://jsfiddle.net/favicon.gif" alt="" />
</div>
</div>
</div>
CSS:
#morework{display:none;}
jQuery:
$(document).ready(function(){
function runIt(){
$('#morework').find('.holderdiv').each(function(i, elem) {
$("#testers").delay(5000).fadeOut(1000, function() {
$(this).html($(elem).html());
}).fadeIn(1000, runIt);
});
};
runIt()
});
Check it out in action here - http://jsfiddle.net/sfsPx/

Related

Fadein() effect to a function: how to?

I have this function that works well for lazy loading.
panel.find('img[data-src]').each(function(){
element = $(this);
element.attr('src', element.data('src'));
element.removeAttr('data-src');
How can I give a fadeIn() effect to that removeAttr function?
I tried:
element.removeAttr('data-src').fadeIn();
but it doesn't work. The img code looks like this and I simply want the dot.png to fadeOut and the original.jpg to fade in.
<img src="dot.png" data-src="original.jpg">
http://jsfiddle.net/7s1yb1un/6/
Thanks in advance
You cannot fade a src change on an img element. To acheive this you'll need two img elements. The second one will have a the src "original.jpg" and will have a higher z-index and start with display: none for a style. Then you can fade it in and it will fade in over the dot.
EDIT Given your new question, you could do the following:
Add an onload listener for the image
Just before changing the "src", fade the image out
Then change the "src" to "original.jpg"
In your onload function, do a fadeIn
Here is what I have done.
Added a fadeOut(5000), the img with original src will fadeout after 5 sec.
Called a function with timeout of 6sec, which changes the src with data-src and fadeIn(5000) in 5 sec, I hope this solves your problem.
JS code is below
var myVar;
function myFunction() {
myVar = setTimeout(function(){
var src = $("img.hide").attr("data-src");
$("img.hide").attr("src",src);
$("img.hide").fadeIn(5000);
}, 6000);
}
function myStopFunction() {
clearTimeout(myVar);
}
$(document).ready(function() {
$(".hide").fadeOut(5000);
myFunction();
});
The following code would fade out, change the src, then fade in.
JSFiddle
HTML
<div id="fullpage">
<div class="section">
<img class="fadeable" src="http://1.gravatar.com/avatar/767fc9c115a1b989744c755db47feb60?size=800" data-src="http://2.gravatar.com/userimage/5/ff5263e8c30557b57e64423ee8496e41?size=800" width=100 height=100 alt="smile"></div>
</div>
JS
$(function() {
$('img[data-src]').each(function(i, e) {
// cache element
original_img = $(e);
original_img
.fadeOut(function(){
original_img.attr('src', original_img.attr('data-src'))
})
.fadeIn();
})
});
Thanks guys. I found this script working (somehow), the images just blink sometimes. I don't know if semantically correct.
$(function() {
$('img').one("load", function() {
var e = $(this);
e.data('src', e.attr('data-src'));
e.animate({"opacity": 0}, 400);
e.data('src');
e.animate({"opacity": 1}, 400);
})
});
The following code would clone the images that have the data-src attribute, then hide the clone, update the clone src, position it over the original image, and fade in. Would this work for you?
JSFiddle
HTML
<div id="fullpage">
<div class="section">
<img class="fadeable" src="http://1.gravatar.com/avatar/767fc9c115a1b989744c755db47feb60?size=800" data-src="http://2.gravatar.com/userimage/5/ff5263e8c30557b57e64423ee8496e41?size=800" width=100 height=100 alt="smile"></div>
</div>
JS
$(function() {
$('img[data-src]').each(function(i, e) {
// cache element
original_img = $(e);
// get position of original image
offset_left = original_img.offset().left;
offset_top = original_img.offset().top;
// get data-src of
data_src = original_img.attr('data-src');
// clone original image
original_img.clone()
.hide()
// put it directly in the body, so it can be positioned
.appendTo('body')
// set the new src
.attr('src', data_src)
// place it over the original image
.css({
"left": offset_left,
"top": offset_top,
"position": "absolute"
})
.fadeIn(function(){
original_img.attr('src', data_src);
$(this).remove();
});
})
});

Get the Height of an Image

This should be easy but it's not. I just need the height of an image:
<div id="map">
<img src="myimage.jpg">
</div>
$("#map img").height(); // returns 0
Use .clientHeight (pure JavaScript):
https://jsfiddle.net/ryanpcmcquen/v6yz8t3u/
console.log(document.querySelector('img').clientHeight);
<img src="//makelin.us/100/100" />
Read up on it here: https://developer.mozilla.org/en-US/docs/Web/API/Element/clientHeight
Note that this will give you the height as the image appears on the page, it could be affected by CSS.
Note: To get the actual height of the image, use .naturalHeight.
Great article here: https://davidwalsh.name/get-image-dimensions
To make sure this runs after the image has loaded, do:
window.addEventListener('load', function () {
console.log(document.querySelector('img').clientHeight);
});
The problem is that the height or width are not calculated yet, listen to the loading of the image with .on( "load", handler )
$("#map img").on("load", function(){
var height = $(this).height();
$('#output').html('height=' + height);
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.1/jquery.min.js"></script>
<div id="map">
<img src="https://via.placeholder.com/400x40">
</div>
<div id="output"></div>
You can refer following example to get height of image-
<div id="map">
<img id="img_id" src="http://www.clickerzoneuk.co.uk/cz/wp-content/uploads/2010/10/PuppySmall.jpg" >
</div>
write following code in js file
var height = document.getElementById("img_id").clientHeight;
alert(height);
check example using following link-
http://jsfiddle.net/v60mut3L/1/
This worked for me:
$(window).load(function () {
var artLists = [];
$("ul.articles").each(function (index) {
var imageHts = [];
$("li img", $(this)).each(function () {
imageHts.push($(this)[0].height);
})
artLists.push(imageHts);
})
});

Jquery toggle img attribute

I am trying to toggle images from the thumbnail to the feature image when the thumb nail is clicked. Currently when its clicked the images will swap but I cant get them to swap back with the thumb nail is clicked on again. I've tried using toggle but when the thumb nail is clicked on it would remove the image completely and I couldnt get any image to return. Currently this will switch the images but not switch or toggle them back on click.
$(".browseTable").on('click', 'td', function () {
var thumbNail = $(this).parent('tr').find('img').attr('src');
var feature = $('#featureImg img').attr('src');
$('#featureImg img').fadeOut(400, function () {
$(this).fadeIn(400)[0].src = thumbNail;
});
});
You can use data for store source string and toggling images
preview on : https://jsfiddle.net/5kxf65Lx/
<img src="source1.jpg" data-srcfirst="source1.jpg" data-srcsecond="source2.jpg" />
<script type="text/javascript">
$('img').click(function(){
var loaded = $(this).attr('src')
var first = $(this).data('srcfirst')
var second = $(this).data('srcsecond')
if(loaded == first){
$(this).attr('src' , second)
} else {
$(this).attr('src' , first)
}
})
Try this. When the parent is clicked we toggle both children. The large version starts off hidden.
<div class="toggle js-toggle">
<img src="http://www.placehold.it/100x100" alt="" class="toggle__thumb js-toggle-image"/>
<img src="http://www.placehold.it/500x500" alt="" class="toggle__active js-toggle-image" style="display: none" />
</div>
The jQuery
$('.js-toggle').on('click', function() {
$(this).find('.js-toggle-image').toggle();
});
https://jsfiddle.net/uoLv2nkh/1/
Or an only CSS way if you only care about when the user is clicking.
https://jsfiddle.net/uoLv2nkh/
You can achieve your target via setting src of image in css.
.imageOne{
content:url(YOUR SOURCE);
}
.imageTwo{
content:url(YOUR SOURCE);
}
add class to your image element in start
check if element exist by either class if exist toggle() to another, this will change the image back to another.
And use toggle() like following example
$(".browseTable").on('click', 'td', function () {
//var thumbNail = $(this).parent('tr').find('img').attr('src');
//var feature = $('#featureImg img').attr('src');
//$('#featureImg img').fadeOut(400, function () {
// $(this).fadeIn(400)[0].src = thumbNail;
//});
$('#featureImg img').find('.imageOne, .imageTwo').toggle();
});
I am able to use toggle simply to change one element to another. etc. hope it will help you.
Is it possible to set the equivalent of a src attribute of an img tag in CSS?

Reclick image to shrink

I have a series of images that expand when click but I would like for them to return back to their original size on re-click. I gave the images an initial class (.images) and then added a class "selected".
HTML:
<div class='images'>
<img src="file:///F|/Desktop/testing new site/sdfs/img/work/Yama/yama1.jpg" width="200" height="150" />
<img src="file:///F|/Desktop/testing new site/sdfs/img/work/Yama/yama2.jpg" width="200" height="150" />
<img src="file:///F|/Desktop/testing new site/sdfs/img/work/Yama/yama3.jpg" width="200" height="150" />
</div>
Javascript:
$(".images img").click(function () {
$(".images img").removeClass('images')
$(this).addClass('selected');
$(this).animate({
width: '50%',
height: '50%'
}, 50).css('z-index', 999);
});
So right now the images will expand correctly. I was thinking to just remove the added selected class so that it goes back to the default .images images with
$(".images img").removeClass('active');
but it doesn't seem to work. I'm still very new to this so hopefully this explanation is detailed enough. Thanks!
2 options:
keep a flag or check the current class to know the image is grown or shrunk. then run your animation accordingly.
Use a class which would change the size. then toggleClass on click to grow or shrink on alternate clicks.
To show animation, you could define a transition css property. So, whenever your class is toggled, the width property will not change abruptly but show an animation effect.
javascript for the 2nd option.
$("img").on("click", function(){
$(this).toggleClass("selected");
});
See this sample.
if you can do css transitions, than all you need is just
.click(function() {
$(this).toggleClass('active)
})
if you want to stick with jquery to animate
$(img).click(function(){
if ( $(this).hasClass('active') {
// shrink it
// remove clas
} else {
// expand it
// add class
}
})
how about that. use animation method and event delegation
// n
$(".images").on('click','img',function() {
var $self = $(this);
$self.toggleClass('selected');
var width = ($self.hasClass('selected')) ? $self.width() * 2 : $self.width() /2 ;
var height = ($self.hasClass('selected')) ? $self.height() * 2 : $self.height() /2 ;
$self.animate ({
width : width+'px' ,
height : height+'px'
}, 50 );
});
other

ListView item animations - Windows store app

I create simple grid application using basic grid example in visual studio and this tutorial. I expected this animation will work on all item's, but it seems that it works only on first one. My question is, how can I animate this on all item's? And if it is possible to animate randomly(not all at once! Example: windows 8 start menu).
Item template:
<div class="itemtemplate" data-win-control="WinJS.Binding.Template">
<div class="item">
<img class="item-image" src="#" data-win-bind="src: backgroundImage; alt: title" />
<img class="item-image-new" src="#" data-win-bind="src: backgroundImage; alt: title" />
<div class="item-overlay">
<h4 class="item-title" data-win-bind="textContent: title"></h4>
<h6 class="item-subtitle win-type-ellipsis" data-win-bind="textContent: subtitle"></h6>
</div>
</div>
</div>
Js animation:
var darkGray = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsQAAA7EAZUrDhsAAAANSURBVBhXY3B0cPoPAANMAcOba1BlAAAAAElFTkSuQmCC";
var lightGray = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsQAAA7EAZUrDhsAAAANSURBVBhXY7h4+cp/AAhpA3h+ANDKAAAAAElFTkSuQmCC";
var mediumGray = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsQAAA7EAZUrDhsAAAANSURBVBhXY5g8dcZ/AAY/AsAlWFQ+AAAAAElFTkSuQmCC";
// Play the Peek animation
function peekTile(tile1, tile2) {
// Create peek animation
var peekAnimation = WinJS.UI.Animation.createPeekAnimation([tile1, tile2]);
// Reposition tiles to their desired post-animation position
tile1.style.top = "-250px";
tile2.style.top = "0px";
// Execute animation
peekAnimation.execute();
}
function changeImage() {
// Get the two image elements
var images = document.querySelector(".item-image");
var imagesNew = document.querySelector(".item-image-new");
// Swap out the old image source and choose the new image source
images.src = imagesNew.src;
if (images.src == lightGray)
imagesNew.src = mediumGray;
else if (images.src == mediumGray)
imagesNew.src = darkGray;
else
imagesNew.src = lightGray;
// Reset the elements for the pre-animation position and trigger the animation
images.style.top = "0px";
imagesNew.style.top = "250px";
peekTile(images, imagesNew);
};
And interval, that changes images(it is written inside ready function):
setInterval(function () { changeImage() }, 4000);
When you call document.querySelector it will only return the first matching element, which in your case will be the first list item. If you want to animate any random item, just call document.querySelectorAll(".item"), pick a random item from the result list and then call querySelector('.item-image') on it, proceeding as you currently do.

Categories