I want the javascript code to show a div in slow motion.
function showDiv(divID)
{
if(document.getElementById(divID).style.display=='none')
{
document.getElementById(divID).style.display='block';
}
}
Here div appears, but not in slow motion. Can anyone help ??
Thanks in advance
Dev..
There is no need of jQuery in this atall , its just a basic I am using your function to explain how thats done.
function showDiv(divID)
{
if(document.getElementById(divID).style.display=='none')
{
document.getElementById(divID).style.display='block';
}
}
What your function is doing is basically removing the whole Element from BOX Model ( the toggle of block and none removes the element totally from the BOX Model so it doesnt occupies any space or anything , this but may / may not cause some layout issues );
Now to animate it in slow motion you need a timing function.
a timing function is a simple mathematical function which gives the value of the property ( opacity in your case ) for a given time or depending on other parameters .
Other then that you also need to use properties like opacity in order to fade it (Opacity is a CSS property that defines the transparency of an element and its childrens )
So let us begin with a very basic show / hide using setTimeout Function in JS.
function getValue(t,dir){
if( dir > 0){
return 0.5*t; /* Y = mx + c */
}else{
return 1-(0.5*t);
}
/*
Here the slope of line m = 0.5.
t is the time interval.
*/
}
function animator(divID){
if(!(this instanceof animator)) return new animator(divID); /* Ignore this */
var Node = document.getElementById(divID),
start = new Date.getTime(), // The initiation.
now = 0,
dir = 1,
visible = true;
function step( ){
now = new Date.getTime();
var val = getValue( now - start,dir)
Node.style.opacity = val;
if( dir > 0 && val > 1 || dir < 0 && val < 0 ){
visible = !(visible*1);
// Optionally here u can call the block & none
if( dir < 0 ) { /* Hiding and hidden*/
Node.style.display = 'none'; // So if were repositioning using position:relative; it will support after hide
}
/* Our animation is finished lets end the continous calls */
return;
}
setTimeout(step,100); // Each step is executated in 100seconds
}
this.animate = function(){
Node.style.display = 'block';
dir *= -1;
start = new Date.getTime();
setTimeout(step,100);
}
}
now you can simply call the function
var magician = new animator('divName');
then toggle its animation by
magician.animate();
Now playing with the timing function you can create whatever possibilities you want as in
return t^2 / ( 2 *3.23423 );
or even higher polynomial equations like
return t^3+6t^2-38t+12;
As you can see our function is very very basic but it explains the point of how to make animations using pure js . you can later on use CSS3 module for animation and trigger those classes with javascript :-)
Or perhaps write a cross browser polyfill using CSS3 where available ( it is faster ) , and JS if not :-) hope that helps
Crossbrowser solution (without jQuery) :
HTML :
<div id="toChange" ></div>
CSS :
#toChange
{
background-color:red;
width:200px;
height:200px;
opacity:0;//IE9, Firefox, Chrome, Opera, and Safari
filter:alpha(opacity=0);//IE8 and earlier
}
Javascript :
var elem=document.getElementById("toChange");
var x=0;
function moreVisible()
{
if(x==1)clearInterval(t);
x+=0.05;
elem.style.opacity=x;
elem.style.filter="alpha(opacity="+(x*100)+")";
}
var t=setInterval(moreVisible,25);
Fiddle demonstration : http://jsfiddle.net/JgxW6/1/
So you have a few jQuery answers but I wouldn't recommend jQuery if fading the div is all you want.
Certainly jQuery makes things easier but it is a lot of overhead for a single simple functionality.
Here is someone that did it with pure JS:
Fade in and fade out in pure javascript
And a CSS3 example:
How to trigger CSS3 fade-in effect using Javascript?
You can use jquery $.show('slow') for the same, if you want to do the same without using jquery then you might be required to code something to show the effect yourself, you may have a look at source of jquery's show function http://james.padolsey.com/jquery/#v=1.6.2&fn=show . alternatively , you can also use fadein() for fade in effect in jquery
Yes you can do it using Jquery. Here is my sample example
$('#divID').click(function() {
$('#book').show('slow', function() {
// Animation complete.
});
});
For details clik here
Thanks.
Related
I have the following code that is using JQuery i would like to use only Angular. And i don't know how i can do it. Thanks
var startProduct = $("#product-overview").position().top - 60;
var endProduct = $("#global-features").position().top + 150;
$(document).scroll(function () {
var y = $(this).scrollTop();
if ($routeParams.section) {
$("#product-submenu").show();
} else if (y > startProduct) {
$("#product-submenu").fadeIn();
} else {
$("#product-submenu").hide();
}
if (y > endProduct) {
$("#product-submenu").css("opacity", "0");
} else {
$("#product-submenu").css("opacity", "1");
}
});
The $ is just a shortcut for a lot of things; for instance $("#product-submenu") is the short form of document.getElementById("product-submenu").
You will also, in the case of the .css functions, need to use document.getElementById("product-submenu").style.opacity = "1" to update CSS rather than the accessor functions jQuery provides.
For .show() and .hide() you can use document.getElementById("product-submenu") followed by .style.display="block" and .style.display="none" respectively.
As for .fadeIn() this would require a bit more work, and might depend on your application how you want to implement it. If you would like fancy effects like fadeIn you might just want to include jQuery in the first place, but if this is the only one you need you can write a javascript function to change the opacity of the element. If the fadein effect isn't necessary, you can use display="block" as above and while it will not fade, it will show the element.
I have a web page with three divs that are synced together.
+----------+
| TOP |
+---+----------+
| | ||
| L | CENTER ||
| |_________||
+---+----------+
<!--Rough HTML-->
<div>
<div class="topbar-wrapper">
<div class="topbar"></div>
</div>
<div class="container">
<div class="sidebar-wrapper">
<div class="sidebar"></div>
</div>
<div class="center-wrapper"> <!-- Set to the window size & overflow:scroll -->
<div class="center"></div> <!-- Has the content -->
</div>
</div>
</div>
The center div has scroll bars, both horizontal and vertical. The top and left divs do not have scroll bars. Instead, when the horizontal scroll bar is moved, the scroll event updates the top div's margin-left appropriately. Likewise when the vertical scroll bar is moved, the margin-top is updated. In both cases, they are set to a negative value.
$('.center-wrapper').scroll(function(e) {
$('.sidebar').css({marginTop: -1 * $(this).scrollTop()});
$('.topbar').css({marginLeft: -1 * $(this).scrollLeft()});
});
This works fine in Chrome and Firefox. But in Safari, there is a delay between moving the scroll bar and the negative margin being properly set.
Is there a better way to do this? Or is there some way to get rid of the lag in Safari?
EDIT:
Check out this Fiddle to see the lag in Safari: http://jsfiddle.net/qh2K3/
Let me know if this JSFiddle works better. I experienced the same "lag" on my end too (Safari 7 on OS X) and these small CSS changes significantly improved it. My best guess is that Safari is being lazy and has not turned on its high-performance motors. We can force Safari to turn it on using some simple CSS:
.topbar-wrapper, .sidebar-wrapper, .center-wrapper {
-webkit-transform: translateZ(0);
-webkit-backface-visibility: hidden;
-webkit-perspective: 1000;
}
This enables hardware accelerated CSS in Safari by offloading some of the work to the GPU. It improves rendering in the browser, which may have been the issue in the delay.
I've had this issue a few times, where safari seems to be lagging when incrementally moving elements based on events like this.
Here's how I've solved the problem in the past.
In browsers that support hardware acceleration, using any "3d" CSS property will enable the hardware acc.
If 3D transforms is supported, we might as well use translate3d to move the elements, as that makes for smoother movements than shifting pixels.
This means we first have to figure out the right prefix for the CSS transform property, then check support for 3D transforms. If we have support, translate the elements, if not shift pixels.
By figuring out the prefixes and 3D support without libraries it should be just about as fast as it can get, and has no dependencies.
var parent = document.querySelector('.center-wrapper'),
sidebar = document.querySelector('.sidebar'),
topbar = document.querySelector('.topbar'),
has3D = false,
transform = null,
transforms = {
'webkitTransform' : '-webkit-transform',
'OTransform' : '-o-transform',
'msTransform' : '-ms-transform',
'MozTransform' : '-moz-transform',
'transform' : 'transform'
};
for (var k in transforms) if (k in parent.style) transform = k;
if ( transform !== null ) {
sidebar.style[transform] = 'translate3d(0,0,0)'; // start hardware acc
topbar.style[transform] = 'translate3d(0,0,0)'; // start hardware acc
// check support
var s = window.getComputedStyle(sidebar).getPropertyValue(transforms[transform]);
has3D = s !== undefined && s.length > 0 && s !== "none";
}
if (has3D) {
parent.onscroll = function (e) {
sidebar.style[transform] = 'translate3d(0px, '+ (this.scrollTop * -1) +'px, 0px)';
topbar.style[transform] = 'translate3d('+ (this.scrollLeft * -1) +'px, 0px, 0px)';
}
}else{
parent.onscroll = function (e) {
sidebar.style.marginTop = (this.scrollTop * -1) + 'px';
topbar.style.marginLeft = (this.scrollLeft * -1) + 'px';
}
}
FIDDLE
Remember to put this after the elements in the DOM, as in right before </body>, or if that's not possible, it has to be wrapped in a DOM ready handler.
As a sidenote, querySelector is not supported in IE7 and below, if that's an issue you have to polyfill it.
Caching selectors will help.
Changing :
$('.center-wrapper').scroll(function(e) {
$('.sidebar').css({marginTop: -1 * $(this).scrollTop()});
$('.topbar').css({marginLeft: -1 * $(this).scrollLeft()});
});
To :
var _scroller = $('.center-wrapper'),
_swrapper = $('.sidebar-wrapper'),
_twrapper = $('.topbar-wrapper');
_scroller.scroll(function (e) {
_swrapper.scrollTop(_scroller.scrollTop());
_twrapper.scrollLeft(_scroller.scrollLeft());
});
.scroll() will be working very hard if it has to recreate jquery objects $(this) each time.
Wrote this in a comment last night, and while not been able to test yet, actually felt today that this is should be added as directly relates to performance.
We can try it out - here
More / The Methods - making them native too
There are also another jquery method calls we can cut out too. .scrollTop() and .scrollLeft() by caching and returning the native _scrollernative = _scroller.get(0) to make use of the readily available properties scrollLeft.
Like :
var _scroller = $('.center-wrapper'),
_scrollernative = _scroller.get(0),
_swrapper = $('.sidebar-wrapper').get(0),
_twrapper = $('.topbar-wrapper').get(0);
_scroller.scroll(function (e) {
_swrapper.scrollTop = _scrollernative.scrollTop;
_twrapper.scrollLeft = _scrollernative.scrollLeft;
});
We can try this here
I appreciate that your code might be looking at more than one of these controls on the page, and that's why you have used classes and needing to find S(this) instead of using ID's.
For that I would still use the above caching methods but before that we need to create them one by one. ( caching before we initialise the scroll() function per instance )
(function() {
var _scroller = $('.center-wrapper'),
_swrapper = $('.sidebar-wrapper').get(0),
_twrapper = $('.topbar-wrapper').get(0);
function setScrollers(_thisscroller) {
_scrollernative = _thisscroller.get(0);
/* start the scroll listener per this event */
_thisscroller.scroll(function (e) {
_swrapper.scrollTop = _scrollernative.scrollTop;
_twrapper.scrollLeft = _scrollernative.scrollLeft;
});
}
_scroller.each(function() { setScrollers($(this)); });
})();
We can try this here
But As I see that .sidebar-wrapper and .topbar-wrapper are unique, mabye .center-wrapper is unique too.
So how about finally using id's for these elements to shorten everything up.
var _scroller = document.getElementById('center-wrapper'),
_swrapper = document.getElementById('sidebar-wrapper'),
_twrapper = document.getElementById('topbar-wrapper');
_scroller.onscroll = function() {
_swrapper.scrollTop = _scroller.scrollTop;
_twrapper.scrollLeft = _scroller.scrollLeft;
};
We can try this here
Instead of using marginTop & marginLeft to change margins of .sidebar & .topbar use scrollTop & scrollLeft for the overflowing divs .sidebar-wrapper & .topbar-wrapper and see if it now works in Safari:
Demo Fiddle
$('.center-wrapper').scroll(function(e) {
$('.sidebar-wrapper').scrollTop($(this).scrollTop());
$('.topbar-wrapper').scrollLeft($(this).scrollLeft());
});
Try this fiddle made to look best in safari and tested
I have to make a long animation with jQuery, full of fadeOuts,fadeIns,slideIns,...
The problem I am having is that my code looks ugly and it is full of callback. Also, if I want to stop animation for some time like: slideOut->wait 5 seconds->slideIn I have to use delay and I am not sure if that is the best practice.
Example:
/* Slides */
var slide1 = $('div#slide1'),
slide2 = $('div#slide2'),
slide3 = $('div#slide3');
$(document).ready(function(){
slide1.fadeIn(function(){
slide2.fadeIn(function(){
slide3.fadeIn().delay(3000).fadeOut(function(){
slide2.fadeOut(function(){
slide1.fadeOut();
});
});
});
});
});
JSFIddle: http://jsfiddle.net/ZPvrD/6/
Question: Is there any other way of building animations in jQuery, possibly even some great plugin to help me solve this problem?
Thanks!
Here's the plugin you were looking for :) Does the exact same thing, but is much more flexible than your existing code http://jsfiddle.net/ZPvrD/11/
(function($){
$.fn.fadeInOut = function(middleDelay) {
middleDelay = middleDelay || 0;
var index = 0,
direction = 1, // 1: fading in; -1: fading out
me = this,
size = me.size();
function nextAnimation() {
// Before the first element, we're done
if (index === -1 ) { return; }
var currentEl = $(me.get(index)),
goingForward = direction === 1,
isLastElement = index === (size - 1);
// Change direction for the next animation, don't update index
// since next frame will fade the same element out
if (isLastElement && goingForward) {
direction = -1;
} else {
index += direction;
}
// At the last element, before starting to fade out, add a delay
if ( isLastElement && !goingForward) {
currentEl.delay(middleDelay);
}
if (goingForward) {
currentEl.fadeIn(nextAnimation);
} else {
currentEl.fadeOut(nextAnimation);
}
}
nextAnimation();
return this;
}
})(jQuery);
And you call it like
$('div.slideWrapper>div.slide').fadeInOut(3000);
This process of traversing up and down a list of jQuery elements waiting for each animation to finish could be abstracted so that it could be used for other things besides fadeIn and fadeOut. I'll leave that for you to try out if you feel adventurous.
Try this:
/* Slides */
var slide = $('div[id*="slide"]');
$( function(){
slide.each( function( k ){
$( this ).delay( 500 * k ).fadeIn();
});
});
JQuery animations take two parameters (maximum), duration and complete, duration is the time in milliseconds for how long you want your animation to complete, or you can use "slow" or "fast", and the second params complete which is the callback function.
If don't want to use delay, you may make the previous animation slow.
e.g.
slide1.fadeIn(5000, function(){
slide2.fadeIn();
};
I'm using a js image gallery on a magento site. Because Magento uses prototype, I've used prototype for this gallery; it's a simple application and I thought it unnecessary to load jQuery library as well just for this one element.
If you have a look at http://web74.justhost.com/~persia28/ in IE8 or less, the transitions between gallery slides is so slow, to the point where the text from one slide remains visible for a short time when the next slide is in place.
I know IE is rubbish with js, but I thought the extent of the slowness here is extreme, even for IE.
I don't want to load jQuery library just for this one gallery, Magento is enough of a tank as it is; so if it came to that I might opt for just putting the text in the images, not in HTML.
Anyway, would be great to hear your wisdom.
Many thanks, and here is the js code for the gallery.
var i = 0;
// The array of div names which will hold the images.
var image_slide = new Array('image-1', 'image-2', 'image-3');
// The number of images in the array.
var NumOfImages = image_slide.length;
// The time to wait before moving to the next image. Set to 3 seconds by default.
var wait = 4000;
// The Fade Function
function SwapImage(x,y) {
$(image_slide[x]).appear({ duration: 1.5 });
$(image_slide[y]).fade({duration: 1.5});
}
// the onload event handler that starts the fading.
function StartSlideShow() {
play = setInterval('Play()',wait);
$('PlayButton').hide();
$('PauseButton').appear({ duration: 0});
}
function Play() {
var imageShow, imageHide;
imageShow = i+1;
imageHide = i;
if (imageShow == NumOfImages) {
SwapImage(0,imageHide);
i = 0;
} else {
SwapImage(imageShow,imageHide);
i++;
}
}
function Stop () {
clearInterval(play);
$('PlayButton').appear({ duration: 0});
$('PauseButton').hide();
}
function GoNext() {
clearInterval(play);
$('PlayButton').appear({ duration: 0});
$('PauseButton').hide();
var imageShow, imageHide;
imageShow = i+1;
imageHide = i;
if (imageShow == NumOfImages) {
SwapImage(0,imageHide);
i = 0;
} else {
SwapImage(imageShow,imageHide);
i++;
}
}
function GoPrevious() {
clearInterval(play);
$('PlayButton').appear({ duration: 0});
$('PauseButton').hide();
var imageShow, imageHide;
imageShow = i-1;
imageHide = i;
if (i == 0) {
SwapImage(NumOfImages-1,imageHide);
i = NumOfImages-1;
} else {
SwapImage(imageShow,imageHide);
i--;
}
}
I looked at the site and it doesn't seem slow, it takes the same time to run. It looks as though the text is not changing in opacity until the end of the animation then is just being hidden. When I look with IE7 it works normally which is a clue, IE8 has a different way of making transparencies.
Magento still ships with Prototype 1.6.0 when I know that Prototype 1.6.1 fixes several IE8 bugs and Prototype 1.7 fixes some IE9 bugs too. You could try upgrading Prototype and Scriptaculous in the js/prototype/ and js/scriptaculous/ directories. I don't know if that exact problem is included which is why you should make a backup before overwriting files, if this doesn't work you will have something to rollback to.
I want to be able to do a cross fade transition on large images whose width is set to 100% of the screen. I have a working example of what I want to accomplish. However, when I test it out on various browsers and various computers I don't get a buttery-smooth transition everywhere.
See demo on jsFiddle: http://jsfiddle.net/vrD2C/
See on Amazon S3: http://imagefader.s3.amazonaws.com/index.htm
I want to know how to improve the performance. Here's the function that actually does the image swap:
function swapImage(oldImg, newImg) {
newImg.css({
"display": "block",
"z-index": 2,
"opacity": 0
})
.removeClass("shadow")
.animate({ "opacity": 1 }, 500, function () {
if (oldImg) {
oldImg.hide();
}
newImg.addClass("shadow").css("z-index", 1);
});
}
Is using jQuery animate() to change the opacity a bad way to go?
You might want to look into CSS3 Transitions, as the browser might be able to optimize that better than Javascript directly setting the attributes in a loop. This seems to be a pretty good start for it:
http://robertnyman.com/2010/04/27/using-css3-transitions-to-create-rich-effects/
I'm not sure if this will help optimize your performance as I am currently using IE9 on an amped up machine and even if I put the browser into IE7 or 8 document mode, the JavaScript doesn't falter with your current code. However, you might consider making the following optimizations to the code.
Unclutter the contents of the main photo stage by placing all your photos in a hidden container you could give an id of "queue" or something similar, making the DOM do the work of storing and ordering the images you are not currently displaying for you. This will also leave the browser only working with two visible images at any given time, giving it less to consider as far as stacking context, positioning, and so on.
Rewrite the code to use an event trigger and bind the fade-in handling to the event, calling the first image in the queue's event once the current transition is complete. I find this method is more well-behaved for cycling animation than some timeout-managed scripts. An example of how to do this follows:
// Bind a custom event to each image called "transition"
$("#queue img").bind("transition", function() {
$(this)
// Hide the image
.hide()
// Move it to the visible stage
.appendTo("#photos")
// Delay the upcoming animation by the desired value
.delay(2500)
// Slowly fade the image in
.fadeIn("slow", function() {
// Animation callback
$(this)
// Add a shadow class to this image
.addClass("shadow")
// Select the replaced image
.siblings("img")
// Remove its shadow class
.removeClass("shadow")
// Move it to the back of the image queue container
.appendTo("#queue");
// Trigger the transition event on the next image in the queue
$("#queue img:first").trigger("transition");
});
}).first().addClass("shadow").trigger("transition"); // Fire the initial event
Try this working demo in your problem browsers and let me know if the performance is still poor.
I had the same problem too. I just preloaded my images and the transitions became smooth again.
The point is that IE is not W3C compliant, but +1 with ctcherry as using css is the most efficient way for smooth transitions.
Then there are the javascript coded solutions, either using js straight (but need some efforts are needed to comply with W3C Vs browsers), or using libs like JQuery or Mootools.
Here is a good javascript coded example (See demo online) compliant to your needs :
var Fondu = function(classe_img){
this.classe_img = classe_img;
this.courant = 0;
this.coeff = 100;
this.collection = this.getImages();
this.collection[0].style.zIndex = 100;
this.total = this.collection.length - 1;
this.encours = false;
}
Fondu.prototype.getImages = function(){
var tmp = [];
if(document.getElementsByClassName){
tmp = document.getElementsByClassName(this.classe_img);
}
else{
var i=0;
while(document.getElementsByTagName('*')[i]){
if(document.getElementsByTagName('*')[i].className.indexOf(this.classe_img) > -1){
tmp.push(document.getElementsByTagName('*')[i]);
}
i++;
}
}
var j=tmp.length;
while(j--){
if(tmp[j].filters){
tmp[j].style.width = tmp[j].style.width || tmp[j].offsetWidth+'px';
tmp[j].style.filter = 'alpha(opacity=100)';
tmp[j].opaque = tmp[j].filters[0];
this.coeff = 1;
}
else{
tmp[j].opaque = tmp[j].style;
}
}
return tmp;
}
Fondu.prototype.change = function(sens){
if(this.encours){
return false;
}
var prevObj = this.collection[this.courant];
this.encours = true;
if(sens){
this.courant++;
if(this.courant>this.total){
this.courant = 0;
}
}
else{
this.courant--;
if(this.courant<0){
this.courant = this.total;
}
}
var nextObj = this.collection[this.courant];
nextObj.style.zIndex = 50;
var tmpOp = 100;
var that = this;
var timer = setInterval(function(){
if(tmpOp<0){
clearInterval(timer);
timer = null;
prevObj.opaque.opacity = 0;
nextObj.style.zIndex = 100;
prevObj.style.zIndex = 0;
prevObj.opaque.opacity = 100 / that.coeff;
that.encours = false;
}
else{
prevObj.opaque.opacity = tmpOp / that.coeff;
tmpOp -= 5;
}
}, 25);
}