Basically I have a banner of images which are to scroll from left to right. I have it working fine with jQuery (code pasted below) however it can be very jittery and the client wants it smoother. So after some research the best way is to use CSS3 (probably should have started here). I haven't used much CSS3 other than the basics like border-radius so had to read up. After seeing some examples I was able to try out making the scroll however I couldn't get it to work with jQuery as well.
The intended effect:
scroll slowly from right to left 'forever'
when mouse is over it, it stops scrolling
I do this with the following jQuery:
$(document).ready(function() {
var $scrollMe = $('.ScrollMe');
$scrollMe.hover(stopBannerAnimation)
$scrollMe.mouseout(startBannerAnimation)
function stopBannerAnimation()
{
$(this).stop();
}
function startBannerAnimation()
{
/*if (Modernizr.csstransitions)
{
$scrollMe.css('left', '{xen:calc '{$scrollerWidth} * 100'}px');
}
else*/
{
$scrollMe.animate(
{left: -{$scrollerWidth}},
{xen:calc '{$scrollerWidth} * 60'},
'linear',
function(){
if ($(this).css('left') == '{$scrollerWidth}px')
{
$(this).css('left', 0);
startBannerAnimation();
}
}
);
}
}
startBannerAnimation();
$('.ScrollMe ol').clone().appendTo('.ScrollMe');
});
Can someone help me get this same functionality while using CSS3 to handle the actual scrolling so it is smoother (in theory)?
This is how I'd do it, using 5 seconds for the animation speed:
Step 1: write your CSS3 transition class
.ScrollMe{
-webkit-transition:left 5s ease; // here the animation is set on 5 seconds
-moz-transition:left 5s ease; // adjust to whatever value you want
-o-transition:left 5s ease;
transition:left 5s ease;}
}
Step 2: set up the jquery to toggle the left position
function DoAnimation () {
var $scrollMe = $('.ScrollMe');
if ($scrollMe.offset().left === 0) {
// I imagine you calculate $scrollerWidth elsewhere in your code??
$scrollMe.css('left', $scrollerWidth);
} else {
$scrollMe.css('left', 0);
}
setTimeout(function () {
if (LaunchAnimation === true) { DoAnimation(); }
}, 5000); // here also assuming 5 seconds; change as needed
}
Step 3: control animation start/stop
var LaunchAnimation = true;
$(document).ready(function() {
$('.ScrollMe').mouseover(function () {
//this stops the div from moving
if (LaunchAnimation === true) {
$(this).css('left', $(this).offset().left);
LaunchAnimation = false;
}
});
$('.ScrollMe').mouseleave(function() {
DoAnimation();
LaunchAnimation = true;
});
}
This way, you let the CSS rendering engine of the browser control the speed and movement of the div for smoothness and you use jquery only as the trigger mechanism.
Hope this helps.
Related
So I've been working in assembly for awhile and just came back to websites after quite some time and one of the questions that are still bothering me today is, why can't I change a class from one animation (open/slide into view animation) to the other (close/slide out of view animation)? I have been being required to set up four different class names to achieve this such as:
.open {
height: 50px;
animation: keyframe 1s forwards 1 0s;
}
.opened {
height: 50px;
}
.close {
height: 0;
animation: keyframe 1s reverse forwards 1 0s;
}
closed {
height: 0;
}
And then in my javascript I am forced to add the keyframe set a timeout and then change to the one without a keyframe otherwise if for say close is already happened and is left on without changing to a class without an animation and in javascript I make it go from close straight to open it will NOT do the open animation? So I've been having to do something like this in javascript:
if (window.pageYOffset == 0 && !elm.classList.contains("closed")) {
elm.className = "close";
setTimeout(() => {
elm.className = "closed";
}, 1000);
} else if (window.pageYOffset > 0 && !elm.classList.contains("opened")) {
elm.className = "open";
setTimeout(() => {
elm.className = "opened";
}, 1000);
}
What I'm wanting to do is this though:
if (window.pageYOffset == 0 && !elm.classList.contains("close")) {
elm.className = "close";
} else if (window.pageYOffset > 0 && !elm.classList.contains("open")) {
elm.className = "open";
}
But if you do that the browser, I am using is Google Chrome, will NOT switch and do the animation, and this brings me to the next part of my question what is the required timeout time in this case? It seems I have to at least have a timeout greater than 50ms for it to register the class switch and do the animations? How do I calculate the required time frame? I assume I am supposed to create an infinite loop on the after the remove class name portion and then once it is removed activate the second part of adding the other classname? I have to do this for example:
elm.className = "";
setTimeout(() => {
elm.className = "new_class"
}, 50);
This example is to show how I am being forced to at least remove the current "close" animation wait for timeout and then add the "open" animation but what I do not know is what is the required time frame for this timeout to be efficient? I have seen using anything less than 50ms will be unregistered and will not do the new animation.
I trying to make what appears to the user to be an image fader. A string of images fade into each other. All the solutions that I found were complex, and normally required an for every image. I've come up with what should be a simple solution. It's working 90% on Firefox/Chrome/IE11 on Windows. On Android Chrome it's having issues.
Basically my idea is, I have two divs, absolutely positioned, one on top of the other. Both start with a background, sized to cover. The top one fades out, revealing the bottom one, and at the end of the animation, the background-image of the top one (current hidden) is changed to image 3. After a pause, it fades back in, and the background-image of the bottom one is changed to image 4. This repeats indefinitely.
HTML:
<div class="slideshow" id="slideshow-top"></div>
<div class="slideshow" id="slideshow-bottom"></div>
CSS:
.slideshow {
display:block;
background-size:cover;
width: 100%;
height: 100%;
position:absolute;
top:0;
left:0;
}
#slideshow-top {
z-index:-5;
background-image:url(http://www.andymercer.net/wp-content/uploads/2013/12/slider-1.jpg);
}
#slideshow-bottom {
z-index:-10;
background-image:url(http://www.andymercer.net/wp-content/uploads/2013/12/slider-2.jpg);
}
Javascript:
var url_array = [
'http://www.andymercer.net/wp-content/uploads/2013/12/slider-1.jpg',
'http://www.andymercer.net/wp-content/uploads/2013/12/slider-2.jpg',
'http://www.andymercer.net/wp-content/uploads/2013/12/slider-3.jpg',
'http://www.andymercer.net/wp-content/uploads/2013/12/slider-4.jpg',
'http://www.andymercer.net/wp-content/uploads/2013/12/slider-5.jpg',
'http://www.andymercer.net/wp-content/uploads/2013/12/slider-6.jpg',
'http://www.andymercer.net/wp-content/uploads/2013/12/slider-7.jpg',
'http://www.walldoze.com/images/full/2013/12/04/wallpapers-desktop-winter-nature-x-wallpaper-backgrounds-natureabstract-designs-interesting-hd-19045.jpg'
];
var count = 1;
setInterval(function() {
if (count%2) { // Fade In
jQuery('#slideshow-top').animate({opacity:0}, '200000', function() {
jQuery('#slideshow-top').css('background-image','url('+url_array[count]+')');
});
}
else { //Fade Out
jQuery('#slideshow-top').animate({opacity:1}, '200', function() {
jQuery('#slideshow-bottom').css('background-image','url('+url_array[count]+')');
});
}
count = (count == url_array.length-1 ? 0 : count + 1);
}, 2000);
http://jsfiddle.net/5eXy9/
As seen in the Fiddle above, this mostly works. However, it seems to ignore the length of the animation. Using .fadeOut has the same effect. I've tried going from 200 to 20000, and there doesn't seem to be a difference.
I'm not sure if this is tied into the other issue, which is that on Android (Galaxy S4, Chrome, Android 4.x), the animation doesn't occur at all. It simply changes images. Any ideas?
EDIT: Jan 10 - Timing problem is fixed, but the main issue (Android) is still unsolved. Any thoughts?
The interval keeps going, so when increasing the animation speed, you have increase the interval speed as well.
The way you've built this, you should always keep the speed of both animations equal to the interval, or if you need a delay, increase the interval compared to the animations so it at least has a higher number than the highest number used in the animations.
The reason changing the speed doesn't work at all for you, is because it should be integers, not strings, so you have to do
jQuery('#slideshow-top').animate({opacity:0}, 200000, function() {...
// ^^ no quotes
I would do something like this
var url_array = [
'http://www.andymercer.net/wp-content/uploads/2013/12/slider-1.jpg',
'http://www.andymercer.net/wp-content/uploads/2013/12/slider-2.jpg',
'http://www.andymercer.net/wp-content/uploads/2013/12/slider-3.jpg',
'http://www.andymercer.net/wp-content/uploads/2013/12/slider-4.jpg',
'http://www.andymercer.net/wp-content/uploads/2013/12/slider-5.jpg',
'http://www.andymercer.net/wp-content/uploads/2013/12/slider-6.jpg',
'http://www.andymercer.net/wp-content/uploads/2013/12/slider-7.jpg',
'http://www.walldoze.com/images/full/2013/12/04/wallpapers-desktop-winter-nature-x-wallpaper-backgrounds-natureabstract-designs-interesting-hd-19045.jpg'];
var count = 1;
var speed = 2000,
delay = 1000;
$.each(url_array, function(source) { // preload
var img = new Image();
img.src = source;
});
setInterval(function () {
if (count % 2) { // Fade In
jQuery('#slideshow-top').animate({
opacity: 0
}, speed, function () {
jQuery('#slideshow-top').css('background-image', 'url(' + url_array[count] + ')');
});
} else { //Fade Out
jQuery('#slideshow-top').animate({
opacity: 1
}, speed, function () {
jQuery('#slideshow-bottom').css('background-image', 'url(' + url_array[count] + ')');
});
}
count = (count == url_array.length - 1 ? 0 : count + 1);
}, speed + delay);
FIDDLE
I'd like to add a slide & fade effect to a DIV, with purely Javascript, using "onclick".
The code is here: http://jsfiddle.net/TCUd5/
The DIV that has to slide has id="pulldown_contents_wrapper".
This DIV is contained in a SPAN, that also triggers it:
<span onclick="toggleUpdatesPulldown(event, this, '4');" style="display: inline-block;" class="updates_pulldown" >
<div class="pulldown_contents_wrapper" id="pulldown_contents_wrapper">
And I think the JS code that controls the SPAN onclick is:
var toggleUpdatesPulldown = function(event, element, user_id) {
if( element.className=='updates_pulldown' ) {
element.className= 'updates_pulldown_active';
showNotifications();
} else {
element.className='updates_pulldown';
}
}
If it is not possible to make it with pure JS, do you have an idea how could I do it with Mootools? (*I'd like to use only pure JS or the Mootols framework).
I have tried to implement the code from: why javascript onclick div slide not working? but with no results.
Thanks a lot.
I have managed to make it with Mootools, but I can't figure it out how to add a slide & fade effect, and a delay on mouseout
window.addEvent('domready', function() {
$('updates_pulldown').addEvents({
mouseenter: function(){
$('updates_pulldown').removeClass('updates_pulldown').addClass('updates_pulldown_active')
$('pulldown_contents_wrapper').set('tween', {
duration: 1000,
physics: 'pow:in:out',
transition: Fx.Transitions.Bounce.easeOut // This could have been also 'bounce:out'
}).show();
},
mouseleave: function(){
$('pulldown_contents_wrapper').set('tween', {
duration: 1000,
delay: 1000,
}).hide();
$('updates_pulldown').removeClass('updates_pulldown_active').addClass('updates_pulldown')
},
});
});
var toggleUpdatesPulldown = function(event, element, user_id) {
showNotifications();
}
Any idea?
jQuery is a lot easier, but with pure javascript you can do it.
In the CSS you'll need to use transitions
#thing { position:relative;
top: 0px;
opacity: 0.8;
-moz-transition: top 1s linear, opacity 1s linear;
-webkit-transition: top 1s linear, opacity 1s linear;
}
then in the javascript when you change the position of the element, it should change via the css transitions.
var toggleUpdatesPulldown = function(event, element, user_id) {
if( element.className=='updates_pulldown' ) {
element.style.top = someValue; //something like '100px' will slide it down 100px
element.style.opacity = '1.0'; //will fade the content in from 0.8 opacity to 1.0
element.className= 'updates_pulldown_active';
showNotifications();
EDIT - provided jQuery code
call the jQuery library, most easily done from the google hosting
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.1/jquery.min.js"></script>
make the hover function
$(document).ready(function() {
$('.updates_pulldown').hover( //first function is mouseon, second is mouseout
function() {
$(this).animate({top: '50px'}).animate({opacity: '1.0'});
},
function() { //delay 1000 milliseconds, animate both position and opacity
$(this).delay(1000).animate({top: '0px'}).animate({opacity: '0.5'});
}
)
})
the function timing will be the same as whatever you set it to in the css with transition tags. using 'this' instead of the class name again makes sure that the effect only occurs on the specific instance of the class that is hovered over. im not sure if this animation is exactly what you were asking for, but if i understand the question correctly then the main functionality will work for you. just change the numbers and such to fit your needs.
In this example; i am trying to create a jQuery animation with css3 rotate property. I can manage this animation with css3 transition and jQuery css() but i want to do this with jQuery animate() for rotating deg value according to my jQuery variatons.
Is it possible use animate with css3 property value with jQuery 1.8.0?
Here is jsFiddle to inspect.
jQuery:
var rotateVal = 90;
//this method isn't working
$('.red').animate({
'transform':'rotate('+rotateVal+'deg)'
},500);
//this way works but i don't want to do this with transitions
$('.black').css({
'transform':'rotate('+rotateVal+'deg)',
'transition':'1s'
});
html:
<span class="black"></span>
<span class="red"></span>
Edit: Vendor prefixes removed, like -webkit-. Thanks to Kevin B.
It is possible, but it isn't easy.
var red = $(".red"),
rotateVal = 90;
$("<div />").animate({
height: rotateVal
},{
duration: 500,
step: function(now){
red.css('transform','rotate('+now+'deg)');
}
});
This basically creates a fake animation of a detached div, then on each step, updates the rotation of the target div.
Edit: Oops! wrong argument order. Here's a demo. http://jsfiddle.net/qZRdZ/
note that in 1.8.0 i don't think you need to specify all the vendor prefixes.
Using this method, you can animate almost anything as long as you keep in mind that things like += and -= won't work properly unless coded for.
Update: Here's a combination of my solution and cuzzea's solution abstracted behind a function. http://jsfiddle.net/qZRdZ/206/
$.fn.rotate = function(start, end, duration) {
console.log(this);
var _this = this;
var fakeDiv = $("<div />");
_this.promise().done(function(){
_this.animate({"a":end},{duration:duration});
fakeDiv.css("height", start).animate({
height: end
}, {
duration: duration,
step: function(now) {
_this.css("transform", "rotate(" + now + "deg)");
},
complete: function() {
fakeDiv.remove();
}
});
});
return _this;
};
var red = $('.red');
red.click(function() {
if ( !$(this).is(':animated') ) {
red.rotate(45,135,500);
setTimeout(function(){
red.rotate(135,190,500);
},750);
setTimeout(function(){
red.rotate(190,45,500);
},1500);
}
});
});
Kevin is corect, almost. :)
Here is working jsFiddle.
You don't have to use another element and height, you can do something like:
var red = $('.red'),
max_rot = 45,
start_from = 90;
red.css({a:0}).animate(
{'a':1},
{ step: function(value,tweenEvent)
{
rotateVal = start_from + max_rot * value;
red.css({
'transform':'rotate('+rotateVal+'deg)',
});
}
},
1000);
The ideea is simple. First we create a bogus css property 'a' and set it to 0, and then we animate it to 1, so the step function will give you a value of 0 to 1 that you can use to set the custom transform.
An alternative method would be to use jQuery to change the dom to something that css would respond to.
We can set our css to look like this:
.object {
-webkit-transition:all .4s;
-moz-transform:all .4s;
-o-transform:all .4s;
-ms-transform:all .4s;
transform:all .4s;
}
.object[data-rotate="false"] {
-webkit-transform:rotate(0deg);
-moz-transform:rotate(0deg);
-o-transform:rotate(0deg);
-ms-transform:rotate(0deg);
transform:rotate(0deg);
}
.object[data-rotate="true"] {
-webkit-transform:rotate(90deg);
-moz-transform:rotate(90deg);
-o-transform:rotate(90deg);
-ms-transform:rotate(90deg);
transform:rotate(90deg);
}
Our jQuery would look like this:
$('#trigger').live('click',function(){
if($('.object').attr('data-rotate') = true) {
$('.object').attr('data-rotate',false);
}
else {
$('.object').attr('data-rotate', true);
}
});
Obviously, the browser has to support the ability to transform whatever animation you want to run, so its its hit or miss depending on the type of animation, but its nicer to work with if you have a ton of stuff going on or you have some children you want to animate concurrently.
Example fiddle:
http://jsfiddle.net/ddhboy/9DHDy/1/
I just want the #menu to fade when the scroll bar is moving to provide a less cluttered interface. Is there code that would allow this?
I guess basically what I'm looking for is how to grab the scroll bar movement event. To slowly fade out the #menu after 1 seconds of scrolling and bring back the #menu after 2 second of scroll-bar inactivity.
Thank you so much!
var $menu = $("#menu");
var opacity = $menu.css("opacity");
var scrollStopped;
var fadeInCallback = function () {
if (typeof scrollStopped != 'undefined') {
clearInterval(scrollStopped);
}
scrollStopped = setTimeout(function () {
$menu.animate({ opacity: 1 }, "slow");
}, 2000);
};
$(window).scroll(function () {
if (!$menu.is(":animated") && opacity == 1) {
$menu.animate({ opacity: 0 }, "slow", fadeInCallback);
} else {
fadeInCallback.call(this);
}
});
http://jsfiddle.net/zsnfb/9/
This sets the scroll event to do a few things. First it clears a timeout to fade the menu div back in. After that, if the menu isn't already faded out, it fades the menu out and sets the timeout in the callback. If the menu is already faded out, it just sets the timeout. If the user stops scrolling, the menu will fade back in after 2 seconds.
There are other solutions that use fadeOut() and fadeIn(). My only issue with those functions in this case is that setting display: none; to the menu div will affect the layout of the page, where setting visibility: hidden; or opacity: 0; shouldn't affect the layout.
Right using the following:
$('body').scroll(function(){
$('#menu').fadeOut();
var scrollA = $('body').scrollTop();
setTimeout(function(){
if(scrollA == $('body').scrollTop()){
$('#menu').fadeIn();
}
}, 200);
})
So we record the scroll amount, wait 200 milliseconds and then see if the scroll has changed, if not we fade the menu back in.
I think this is what you are looking for http://jsfiddle.net/wfPB6/