jQuery image fade effect - javascript

I am using this code. When it changes the image, the image fades out and then the other image fades in, and in the meanwhile I can see the background color, which I don't want to see. Is there any simple way to fade images but at the same time fade in the next image, or another jQuery effect like slide the images? I just don't want to see the background color.
<script type="text/javascript">
$(document).ready(function(){
var imgArr = new Array( // relative paths of images
'css/images/main_img.jpg',
'css/images/main_img_2.jpg',
'css/images/main_img_3.jpg',
'css/images/main_img_4.jpg',
'css/images/main_img_5.jpg'
);
var preloadArr = new Array();
var i;
/* preload images */
for(i = 0; i < imgArr.length; i++){
preloadArr[i] = new Image();
preloadArr[i].src = imgArr[i];
}
var currImg = 1;
var intID = setInterval(changeImg, 6000);
//added this so that the first image is always the first from the array
$('#main_content').css('background','url(' + preloadArr[0].src +') top center no-repeat');
/* Main IMG */
function changeImg(){
$('#main_content').animate({opacity: 0}, 1000, function(){
$(this).css('background','url(' + preloadArr[currImg++%preloadArr.length].src +') top center no-repeat');
}).animate({opacity: 1}, 1000);
}
});
</script>

Since you are changing the css background you can't do this against a single element.
You could achieve this with another div which would hold the next background image (before your content fades out) and would be put under your #main_content element using none static css position states and z-index property.

You can't achieve this effect with one element only. You need a second element on top of the other and fade it in. Once its faded in, you can hide the back element but it's not even necessary.
See this tutotrial: http://bavotasan.com/2009/creating-a-jquery-mouseover-fade-effect/

Here I have written codes for creating simple JavaScript fade effect animation using Jquery, which may help you to create awesome image animations.
At first add the following script to import jquery.min.js or you can host this script yourself.
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js">
</script>
Here write CSS codes for
.fade and .fade img
.fade
{
box-shadow:1px 1px 5px 2px #6DC83C;
position:relative;
width:500px;
height: 300px;
border-radius:19px;
}
.fade img
{
border-radius:19px;
position:absolute;
left:0;
top:0;
}
And use the following Code.
<script> $(function(){ $('.fade img:gt(0)').hide(); setInterval(function(){$('.fade :first-child').fadeOut(3000).next('img').fadeIn(3000).end().appendTo('.fade');}, 4000); }); </script>
Then use the following code for images.
<div class="fade">
<img src="image_1.gif">
<img src="image_2.gif">
<img src="image_3.gif">
</div>

Related

Animate text using intervals (and timeouts?) Javascript, JQuery

I would like to make a Text run from left to right in a loop. Here is the fiddle with my attempt:
https://jsfiddle.net/9Lruxym8/33/
I started with css #keyframes but I think I need the width of the text itself if I want the text to run seamlessly. My idea was to write down the text two times and once the div with the texts has run exactly halfway, the animation starts again.
After #keyframes didn't work, I tried jQuery animation. It did work somewhat but didn't run smoothly. Now I'd like to do it via transition. I thought a combination of intervals and timeouts could do the trick but I still don't get it to work - and now, I don't know why. Does anyone have a hit for me?
function runText() {
var text_width = $('#runningP').width()/2;
console.log(text_width)
setInterval(function(){
console.log("interval");
$('.text').css({'transition':'margin-left 5s'});
$('.text').css({'margin-left':'-' + text_width + 'px'});
moveBack();
}, 3000);
function moveBack() {
console.log("timeout")
setTimeout(function(){
$('.text').css({'transition':'none'});
$('.text').css({'margin-left': 0});
}, 3000);
}
}
runText();
I've recently made a bit of custom code for this functionality.
Looking at my code, it seems a bit much having essentially 3 "levels" (.scrollTextWrap > .scrollingText > .scrollContent) but this was the structure I ended up using to get a clean and consistent effect.
I've added in an initialiser too so that you could simply add the scrollMe class and have them setup the html for you
In the snippet I've added a .parentContainer purely to show how it works when constrained
$(document)
.ready(function(){
// check that scrollingText has 2 scrollContent element
$('.scrollMe')
.each(function(){
initScrollingText($(this));
});
});
function initScrollingText($this){
// store text
var text = $this.text();
// empty element
$this.html(null);
var $wrap = $('<div class="scrollTextWrap" />'),
$text = $('<div class="scrollingText" />'),
$content = $('<div class="scrollContent" />');
// set content value
$content.text(text);
// duplicate content
$text
.append($content)
.append($content.clone());
// append text to wrap
$wrap.append($text)
// add $wrap to DOM
$wrap.insertAfter($this);
// remove old element
$this.remove();
}
/* to simulate width constraints */
.parentContainer {
width: 140px;
position:relative;
overflow:hidden;
}
.scrollTextWrap {
position:relative;
width:auto;
display:inline-block;
}
.scrollingText {
display: flex;
position:relative;
transition:left 0.1s;
animation: scrollText 5s infinite linear;
}
.scrollContent {
white-space: nowrap;
padding-right:5px;
}
#keyframes scrollText {
0% { left:0 }
100% { left:-50% }
}
<div class="parentContainer">
<div class="scrollMe">Content you want to scroll goes here</div>
<!-- alternatively you can just structure the html -->
<div class="scrollTextWrap">
<div class="scrollingText">
<div class="scrollContent">Content you want to scroll goes here</div>
<div class="scrollContent">Content you want to scroll goes here</div>
</div>
</div>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

Smooth background images transition - Javascript

http://www.chooseyourtelescope.com/ (>> Please watch it on a minimum 15'' screen, the site is not entirely responsive yet and you wont see what I'm talking about)
When you hover the buttons (moon, planet, etc...) it changes the background. But the transition is buggy on Chrome (image0>blank>image1). And worknig on IE11 but sometimes with a lag. I didn t try with the other browsers.
How to make a smooth transition?
A quick fade Image0>image1, not image0>transition color>image1
Here is the code for the MOON button. Thats the same with the others.
(I don't know anything about Javascript. I found the script below on Stackoverflow.)
HTML
<div class="top-logos-home" id="top-logos-moon-front"><img src="moon-logo.png" alt="MOON"></div>
CSS
.image-home {
position: absolute;
width: 100%;
height: 100%;
background-image: url(Frontpage.jpg);
background-size: cover;
display:inline;
top:0;
}
JAVASCRIPT
jQuery(function(){
var $body = $('.image-home');
$('#top-logos-moon-front').hover(function(){
$body.css('background-image', 'url("Frontpage-moon.jpg")')
}, function() {
$body.css('background-image', '')
})
})
You need to change just your script code if you want smooth transtion.
jQuery(function(){
var $body = $('.image-home');
$('#top-logos-moon-front').hover(function(){
$body.fadeOut('slow',function(){
$body.css('background-image', 'url("Frontpage-moon.jpg")').fadeIn('slow');
});
}, function() {
$body.css('background-image', '')
})
})
If you want to do best solution for this you need follow the steps below.
Firstly you need to defined your path of images in the js with the below code.
var imgs = [
'http://i.imgur.com/DwLjYhh.jpg',
'http://i.imgur.com/gAlqfUU.jpg'
];
After this step, you need to add new attiribute your buttons like data-id.
<div class="top-logos-home" id="top-logos-moon-front" data-id='0'>
<img src="button_image_jpg" alt="MOON">
</div>
When you defined all variables, you need to detect the hover with your current code and choose the right image that is in imgs array for your background.
jQuery(function(){
var $body = $('.image-home');
$('#top-logos-moon-front').hover(function(){
$body.fadeOut('slow',function(){
//fade out slowly element and after change the style of inner elements then fade in slowly.
$body.css('background-image','url('+imgs[$(this).attr('data-id')]+')').fadeIn('slow');
});
});
});
In my personal opinion; Image transitions shouldn't manage in this way. Create different element for each planets. When user click the button, planets slip and overlapping. You can see a demo in the below code.
http://codepen.io/thegeek/pen/GDwCa
I found a solution by using the opacity property. Now its working perfectly.
HTML
<img id="background-moon-front" class="hover-backgrounds" src="Frontpage-moon.jpg" />
CSS
.hover-backgrounds {
opacity:0;
transition: opacity 0.6s linear;
top:0;
position:absolute;
background-size: 100%;
}
JAVASCRIPT
$(document).ready(function (e) {
$("#top-logos-lune-front").hover(function (e) {
$("#background-moon-front").css("opacity", "1");
}, function() {
$("#background-moon-front").css("opacity", "0")
})
});

Cycle background with text overlay effect

So basically I found a really cool example for cycling background images using JavaScript and jQuery.
What would be the best approach to adding an overlay text description effect for each slide?
So for instance, each slide will also have a text description overlayed somewhere on each image with it's own style . Would it be possible to have this text also come in with it's own effects. So the image fades in, and then the text description slides in from the left, and so on
HTML
<body>
<div id="background_cycler">
<img class="active" src="https://upload.wikimedia.org/wikipedia/commons/thumb/c/c2/View_from_a_ridge_between_Segla_and_Hesten%2C_Senja%2C_Norway%2C_2014_August.jpg/1920px-View_from_a_ridge_between_Segla_and_Hesten%2C_Senja%2C_Norway%2C_2014_August.jpg" width="1000px" height="1000px" alt="" />
<img src="https://upload.wikimedia.org/wikipedia/commons/thumb/8/87/Amanhecer_no_Hercules_--.jpg/1920px-Amanhecer_no_Hercules_--.jpg" alt="" width="1000px" height="1000px" />
<img src="https://upload.wikimedia.org/wikipedia/commons/thumb/f/fc/Giant_Manta_AdF.jpg/1920px-Giant_Manta_AdF.jpg" alt="" width="1000px" height="1000px" />
</div>
JQUERY
$('#background_cycler').hide();
window.cycleImages = function() {
var $active = $('#background_cycler .active');
var $next = ($('#background_cycler .active').next().length > 0) ? $('#background_cycler .active').next() : $('#background_cycler img:first');
$next.css('z-index', 2); //move the next image up the pile
$active.fadeOut(1500, function() { //fade out the top image
$active.css('z-index', 1).show().removeClass('active'); //reset the z-index and unhide the image
$next.css('z-index', 3).addClass('active'); //make the next image the top one
});
}
$(window).load(function() {
$('#background_cycler').fadeIn(1500); //fade the background back in once all the images are loaded
// run every 7s
setInterval('cycleImages()', 7000);
})
CSS
#background_cycler {
padding: 0;
margin: 0;
width: 100%;
position: absolute;
top: 0;
left: 0;
z-index: -1;
}
#background_cycler img {
position: absolute;
left: 0;
top: 0;
width: 100%;
z-index: 1;
}
#background_cycler img.active {
z-index: 3;
}
Here's a solution like Andy's, but keeping the img tags:
https://jsfiddle.net/2y8fo13d/
Instead of using img tags, you can use more generic div tags to act as the slides. Then you can fill them with whatever content you wish, check out this as an example:
https://jsfiddle.net/00gow9Lt/1/
Here I have used div tags with some simple text and the original images as backgrounds.
You can style each one's content separately with css for a different look, but to have sliding effects on the text itself would require significantly more code. For that I would suggest reading up on jQuery animations in more detail.

How to slide a div by hovering over another div with jquery?

I have some code here and cannot find out how to make this work because I am still really new to javascript and jquery. I will have a demo below so you can see what I have going on. In the demo there is div positioned left:-60px so it is hidden, this div also has class of 'show' which positions the div to left:0 There is also the long black box which is another div. I want to make it so when you hover over the long black box, it will activate the 'show' property of the other div. Here is my code:
var $showSidemenu = $('#sidemenu');
var $sidemenuShowButton = $('#sidemenuShowButton');
function(showSidemenu){
$showSidemenu.onmouseover($sidemenuShowButton).addclass('show');
}
#sidemenuShowButton {
width:60px;
height:100%;
background:#000000;
top:0;
left:0;
position:fixed;
}
#sidemenu {
width: 60px;
height:100%;
background-color: #383D3F;
position: fixed;
top: 0;
left:-60px;
float: left;
z-index:0;
}
#sidemenu.show {
left: 0;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="sidemenuShowButton"></div>
<div id="sidemenu"></div>
try this jQuery:
var $showSidemenu = $('#sidemenu');
var $sidemenuShowButton = $('#sidemenuShowButton');
$(document).ready(function(){
$sidemenuShowButton.on('mouseover',function(){
$('#sidemenu').addClass("show");
});
$sidemenuShowButton.on('mouseout',function(){
$('#sidemenu').removeClass("show");
});
// to make the showed div stay while the mouse is still over it
$('#sidemenu').on('mouseover',function(){
$(this).addClass("show");
});
$('#sidemenu').on('mouseout',function(){
$(this).removeClass("show");
});
});
if you want a little animation, you can use CSS3 Transition for that, like this one:
#sidemenu {
transition: 1s;
}
HERE'S A WORKING DEMO
Use JQuery's show and hide functions. If you set your #sidemenu to display: none;. And then use this this function it will work:
$('#sidemenu').mouseenter(function(){
$("#sidemenuShowButton").show();
}).mouseleave(function(){
$("#sidemenuShowButton").hide();
});
No classes are needed in this way.
Your JS should looks like this:
var $showSidemenu = $('#sidemenu');
var $sidemenuShowButton = $('#sidemenuShowButton');
$sidemenuShowButton.on('mouseover', function(){
$showSidemenu.addClass('show')
});
First of all you are using function which never used and cannot be used since it have no name. Second, there is no onmouseover method in jQuery (read the manual ;-). Third you have to pass there a callback function which will be involved when 'mouseover' event occurs.
And if you wanna hide your div when mouse leaves add
$showSidemenu.on('mouseleave', function(){
$showSidemenu.removeClass('show')
});
You should use $showSidemenu in this case instead of $sidemenuShowButton because when $showSidemenu apears mouse leaves $sidemenuShowButton and enters $showSidemenu. But if you wanna use css3 animation - it's better to make appearing div nested to control div and use event bobbling.
And jsfiddle
Solution:Use mouseover and mouseout events to add and remove class "show"
I have intentionally added mouseout event on showSidemenu as when it slides in it goes over sidemenuShowButton div and comes on top of it, so attaching mouseout to sidemenuShowButton will cause flickering effect.
http://api.jquery.com/category/events/mouse-events/
$sidemenuShowButton.mouseover(function(){
$showSidemenu.addClass("show");
}
);
$showSidemenu.mouseout(function(){
$showSidemenu.removeClass("show");
}
);
Working JS Fiddle Example: http://jsfiddle.net/2cjjdm7j/1/

jQuery fade to new image

How can I fade one image into another with jquery? As far as I can tell you would use fadeOut, change the source with attr() and then fadeIn again. But this doesn't seem to work in order. I don't want to use a plugin because I expect to add quite a few alterations.
Thanks.
In the simplest case, you'll need to use a callback on the call to fadeOut().
Assuming an image tag already on the page:
<img id="image" src="http://sstatic.net/so/img/logo.png" />
You pass a function as the callback argument to fadeOut() that resets the src attribute and then fades back using fadeIn():
$("#image").fadeOut(function() {
$(this).load(function() { $(this).fadeIn(); });
$(this).attr("src", "http://sstatic.net/su/img/logo.png");
});
For animations in jQuery, callbacks are executed after the animation completes. This gives you the ability to chain animations sequentially. Note the call to load(). This makes sure the image is loaded before fading back in (Thanks to Y. Shoham).
Here's a working example
$("#main_image").fadeOut("slow",function(){
$("#main_image").load(function () { //avoiding blinking, wait until loaded
$("#main_image").fadeIn();
});
$("#main_image").attr("src","...");
});
Well, you can place the next image behind the current one, and fadeOut the current one so that it looks like as though it is fading into the next image.
When fading is done, you swap back the images. So roughly:
<style type="text/css">
.swappers{
position:absolute;
width:500px;
height:500px;
}
#currentimg{
z-index:999;
}
</style>
<div>
<img src="" alt="" id="currentimg" class="swappers">
<img src="" alt="" id="nextimg" class="swappers">
</div>
<script type="text/javascript">
function swap(newimg){
$('#nextimg').attr('src',newimg);
$('#currentimg').fadeOut(
'normal',
function(){
$(this).attr('src', $('#nextimg').attr('src')).fadeIn();
}
);
}
</script>
Are you sure you're using the callback you pass into fadeOut to change the source attr and then calling fadeIn? You can't call fadeOut, attr() and fadeIn sequentially. You must wait for fadeOut to complete...
Old question but I thought I'd throw in an answer. I use this for the large header image on a homepage. Works well by manipulating the z-index for the current and next images, shows the next image right under the current one, then fades the current one out.
CSS:
#jumbo-image-wrapper
{
width: 100%;
height: 650px;
position: relative;
}
.jumbo-image
{
width: 100%;
height: 100%;
position: absolute;
top: 0px;
left: 0px;
}
HTML:
<div id="jumbo-image-wrapper">
<div class="jumbo-image" style="background-image: url('img/your-image.jpg');">
</div>
<div class="jumbo-image" style="background-image: url('img/your-image-2'); display: none;">
</div>
</div>
Javascript (jQuery):
function jumboScroll()
{
var num_images = $("#jumbo-image-wrapper").children(".jumbo-image").length;
var next_index = jumbo_index+1;
if (next_index == num_images)
{
next_index = 0;
}
$("#jumbo-image-wrapper").children(".jumbo-image").eq(jumbo_index).css("z-index", "10");
$("#jumbo-image-wrapper").children(".jumbo-image").eq(next_index).css("z-index", "9");
$("#jumbo-image-wrapper").children(".jumbo-image").eq(next_index).show();
$("#jumbo-image-wrapper").children(".jumbo-image").eq(jumbo_index).fadeOut("slow");
jumbo_index = next_index;
setTimeout(function(){
jumboScroll();
}, 7000);
}
It will work no matter how many "slides" with class .jumbo-image are in the #jumbo-image-wrapper div.
For those who want the image to scale according to width percentage (which scale according to your browser width), obviously you don't want to set height and width in PIXEL in CSS.
This is not the best way, but I don't want to use any of the JS plugin.
So what can you do is:
Create one same size transparent PNG and put an ID to it as
second-banner
Name your original image as first-banner
Put both of them under a DIV
Here is the CSS structure for your reference:
.design-banner {
position: relative;
width: 100%;
#first-banner {
position: absolute;
width: 100%;
}
#second-banner {
position: relative;
width: 100%;
}
}
Then, you can safely fade out your original banner without the content which placed after your image moving and blinking up and down

Categories

Resources