"fadeTo" function ignores the time - javascript

I have a div and I animate it's position with two divs(which are named as open and close).
I want "open" div to be fade out and invisible when opening animation completes. And become visible with fading in when closing animation completes.
But there is problem with the fading in. Time parameter is ignored and it appears when click action happens.
Here are my codes and a fiddle to see clearly what is going on with the codes;
$('.open').on('click', function(){
$('.menu').animate({"marginLeft":"-30px"},1000);
$('.open').fadeTo(1000, 0);
setTimeout(function () {
$('.open').css({"display":"none"})}, 1000);
});
$('.close').on('click', function(){
$('.menu').animate({"marginLeft":"82%"},1000);
$('.open').fadeTo(1000, 100);
});
the fiddle is http://jsfiddle.net/ctarimli/B9h2w/
as I know; the first paremeter is for time and the second one is the opacity in "fadeTo".
Tell me If I am wrong or what is the solution for this?

Opacity runs from 0 to 1, not 0 to 100. Use:
$('.close').on('click', function () {
$('.menu').animate({
"marginLeft": "82%"
}, 1000);
$('.open').fadeTo(1000, 1);
});
jsFiddle example
From the docs on .fadeTo():
opacity Type: Number A number between 0 and 1 denoting the target
opacity.

Related

Using a jquery slider for text instead of images?

This may be a little too specific, but I have a jquery slider that I am using <p> classes instead of images to cycle through customer quotes. Basically the problem I am running into right now is when it is static and non moving (JS code is commeneted out) they are aligned how I want them to be. As soon as the JS is un commented, they stretch out of view and you just see a white box?
Any ideas?
How I want each panel to look like:
jsfiddle
So I sort of made this my Friday project. I've changed a whole lot of your code, and added a vertical-align to the quotes and authors.
Here's the fiddle http://jsfiddle.net/qLca2fz4/49/
I added a whole lot of variables to the top of the script so you could less typing throughout.
$(document).ready(function () {
//rotation speed and timer
var speed = 5000;
var run = setInterval(rotate, speed);
var slides = $('.slide');
var container = $('#slides ul');
var elm = container.find(':first-child').prop("tagName");
var item_width = container.width();
var previous = 'prev'; //id of previous button
var next = 'next'; //id of next button
Since you used a % based width I'm setting the pixel widths of the elements in case the screen is reszed
slides.width(item_width); //set the slides to the correct pixel width
container.parent().width(item_width);
container.width(slides.length * item_width); //set the slides container to the correct total width
As you had, I'm rearranging the slides in the event the back button is pressed
container.find(elm + ':first').before(container.find(elm + ':last'));
resetSlides();
I combined the prev and next click events into a single function. It checks for the ID of the element targeted in the click event, then runs the proper previous or next functions. If you reset the setInterval after the click event your browser has trouble stopping it on hover.
//if user clicked on prev button
$('#buttons a').click(function (e) {
//slide the item
if (container.is(':animated')) {
return false;
}
if (e.target.id == previous) {
container.stop().animate({
'left': 0
}, 1500, function () {
container.find(elm + ':first').before(container.find(elm + ':last'));
resetSlides();
});
}
if (e.target.id == next) {
container.stop().animate({
'left': item_width * -2
}, 1500, function () {
container.find(elm + ':last').after(container.find(elm + ':first'));
resetSlides();
});
}
//cancel the link behavior
return false;
});
I've found mouseenter and mouseleave to be a little more reliable than hover.
//if mouse hover, pause the auto rotation, otherwise rotate it
container.parent().mouseenter(function () {
clearInterval(run);
}).mouseleave(function () {
run = setInterval(rotate, speed);
});
I broke this in to its own function because it gets called in a number of different places.
function resetSlides() {
//and adjust the container so current is in the frame
container.css({
'left': -1 * item_width
});
}
});
//a simple function to click next link
//a timer will call this function, and the rotation will begin :)
And here's your rotation timer.
function rotate() {
$('#next').click();
}
It took me a little bit, but I think I figured out a few things.
http://jsfiddle.net/qLca2fz4/28/
First off, your console was throwing a few errors: first, that rotate wasn't defined and that an arrow gif didn't exist. Arrow gif was probably something you have stored locally, but I changed the 'rotate' error by changing the strings in the code here to your actual variables.
So, from:
run = setInterval('rotate()', speed);
We get:
run = setInterval(rotate, speed);
(No () based on the examples here: http://www.w3schools.com/jsref/met_win_setinterval.asp)
But I think a more important question is why your text wasn't showing up at all. It's because of the logic found here:
$('#slides ul').css({'left' : left_value});
You even say that this is setting the default placement for the code. But it isn't..."left_vaule" is the amount that you've calculated to push left during a slide. So if you inspect the element, you can see how the whole UL is basically shifted one slide's worth too far left, unable to be seen. So we get rid of 'left_value', and replace it with 0.
$('#slides ul').css({'left' : 0});
Now, there's nothing really handling how the pictures slide in, so that part's still rough, but this should be enough to start on.
Let me know if I misunderstood anything, or if you have any questions.
So, a few things:
1) I believe you are trying to get all of the lis to be side-by-side, not arranged up and down. There are a few ways to do this. I'd just make the ul have a width of 300%, and then make the lis each take up a third of that:
#slides ul {
....
width: 300%;
}
#slides li {
width: calc(100% / 3);
height:250px;
float:left;
}
2) You got this right, but JSFiddle automatically wraps all your JS inside a $(document).ready() handler, and your function, rotate needs to be outside, in the normal DOM. Just change that JSFiddle setting from 'onload' to 'no wrap - in head'
3) Grabbing the CSS value of an element doesn't always work, especially when you're dealing with animating elements. You already know the width of the li elements with your item_width variable. I'd just use that and change your code:
var left_indent = parseInt($('#slides ul').css('left')) - item_width;
$('#slides ul').animate({'left' : left_indent}, 1500, function () {
to:
$('#slides ul').stop().animate({'left' : -item_width * 2}, 1500, function () {
4) Throw in the .stop() as seen in the above line. This prevents your animations from overlapping. An alternative, and perhaps cleaner way to do this, would be to simply return false at the beginning of your 'next' and 'prev' functions if #slides ul is being animated, like so:
if ($('#slides ul').is(':animated')) return false;
And I think that's everything. Here's the JSFiddle. Cheers!
EDIT:
Oh, and you may also want to clearInterval at the beginning of the next and prev functions and then reset it in the animation callback functions:
$('#prev').click(function() {
if ($('#slides ul').is(':animated')) return false;
clearInterval(run);
$('#slides ul').stop().animate({'left' : 0}, 1500,function(){
....
run = setInterval('rotate()', speed);
});
});

Make .delay() and .animate() function re-run everytime a classes div opens

So, I'm sure there is a simple answer to this, but after 2 days of research I cannot find a solution.
The Story:
I have a dynamic page. When you get to one section and click on one of the 6 options it pulls up some info (name, place, etc.). I have a jQuery function that makes that info hide about half way after a few seconds. When you hover over that section with the mouse it also will animate up and back down as the mouse leaves it.
The Problem:
How do I make the whole function run again if another of those 6 option is clicked? Each time an option is selected the class with that info comes up, but after this function runs once (the delay part and animate down part) it just stays minimized unless you hover over it. I want it to appear every time and then run through the function. I have tried a number of things, and I'm sure there is a simple solution, just not sure what it is.
Here is a link to my codepen with a sample: http://codepen.io/jsegarra/pen/GxByr
I have also tried to wrap that all in a click function, for clicking on one of those 6 options and thought that would do the trick, but still the same thing:
$(document).ready(function () {
$('.title').click(function () {
$('.bottomTab').delay(5000).animate({
height: '50px' // to 50px
}, 'slow');
$(".bottomTab").hover(
//on mouseover
function () {
$(this).stop().animate({
height: '+=100' //adds 50px
}, 'slow');
},
//on mouseout
function () {
$(this).stop().animate({
height: '50px' //back to 50px
}, 'slow');
});
});
});
Just reset the div css before re-running the function
$(document).ready(function () {
$('.title').click(function () {
$('.bottomTab').css('height', '100px').delay(500).animate({
height: '50px' // to 50px
}, 'slow');
$(".bottomTab").hover(
//on mouseover
function () {
$(this).stop().animate({
height: '+=100' //adds 50px
}, 'slow');
},
//on mouseout
function () {
$(this).stop().animate({
height: '50px' //back to 50px
}, 'slow');
});
});
});
Here is the html I used with that javascript
<div class="title">title</div>
<div class="bottomTab">This is going to move from just being about 50 pixels high to about 100 pixels high after i add in some mouseenter and mouse out events</div>
I used the same CSS of your code pen, and the result was a full reclickable option
I don't see the problem. Your code seems to works fine. You've just typed an error while transfering to CodePen. Replace $('this').hover( with $('.bottomTab').hover(.

How to use fadeOut jQuery property with Javascript Text Snippet

http://api.jquery.com/fadeOut/ <- fadeOut api
I'm trying to learn Javascript and I've been playing with a snippet I found on Codepen.
I'm having trouble trying to get the random text array snippet to have the text fadeOut when it transitions away to another text object. Right now, the array cycles through and randomly selects a string from the array using the Math.Random function (5*1) and it fades in each time a new text object loads in, however I want it to fade out and I don't think I'm utilizing the .fadeOut property properly. How can I get it so that the text fadesOut, so the text does fadeIn fadeOut, instead of fadeIn, insta kill?
var textTimer;
var inTransition = false;
startTimer();
function startTimer() {
clearTimeout(textTimer);
textTimer = setTimeout(changeTitle, 3500);
}
changeTitle();
var titleNumber = Math.floor(Math.random() * 5) + 1;
function changeTitle() {
var titleArray = [
"Test1",
"Test2",
"Test3",
"Test4",
"Test5"
];
var tempTitleLength = titleArray.length - 1;
if (inTransition == false) {
inTransition = true;
titleNumber++;
if (titleNumber > tempTitleLength){
titleNumber = 0
}
$('.text').html('');
$('.text').css({opacity: '0'});
$('.text').html(titleArray[titleNumber]);
$('.text').fadeOut();
$('.text').stop().delay(0).animate({
opacity: 1
}, 1500, function() {
inTransition = false;
startTimer.()
});
}
}
Thanks! :D
The HTML is pretty straight forward
<div class="text"></div>
Multiple problems:
$('.text').html('');
$('.text').css({opacity: '0'});
$('.text').html(titleArray[titleNumber]);
You are already removing the text in html('') without fading out,
setting css opacity to 0 without any delay, setting html new text without any animation.
There is a syntax error also startTimer.() I guess is typo.
Remove first 2 lines and set new text after fade out is done.
You also need to wait for fadeOut to finish before doing fadeIn.
So, sequence: fadeOut, set new text, fadeIn.
Like this:
$('.text').fadeOut(1500, function () {
$('.text').html(titleArray[titleNumber]);
$('.text').fadeIn(1500, function () {
inTransition = false;
startTimer()
});
});
JSFiddle: http://jsfiddle.net/Dzyzw/
You have syntax errors in your code: you have startTimer.() should be startTimer() and you did not close your startTimer function with a }. I corrected this for you and set up a sample JSFiddle for you review. Seems to be working otherwise.
Here is the sample JSFiddle: CLICK HERE
Here's what I think you're going for--
Set initial text.
Fade out your text.
Change the text.
Fade in the new text.
Wait a while, then return to step 2.
I would drop all the transition flags and use the optional callback functions that are fired when fadeOut and fadeIn complete to move from step to step, e.g.
$('.text').fadeOut(1000, function() {
$('.text').html(get_next_word());
$('.text').fadeIn(500);
});
Just fire that off on a timer that is 1500 milliseconds + the time you want the text to be fully visible.

Second animation not working

In an UL list do I want to animate the first LI inside. The first animation will remove the CSS class for the blue background and adds a new CSS to it to make it have a dark background. It also adds a new a line of code inside. The second animation will push the same div up with a fade on it so it disappears. Then it will get removed.
Both animations I have tested separated by commenting out the other animation and work proper.
The problem is that I can't run them together, if I do the first animation then the second animation won't work at all.
listTop = $('#ypPlaylist > ul li:first');
setTimeout(function ()
{
listTop.css('background', '#2d89ef').removeClass('bg-color-blue');
listTop.animate({ backgroundColor: '#1d1d1d' }, 300);
listTop.prepend('<b>Running: </b>').fadeTo(300);
}, 1000)
setTimeout(function ()
{
listTop.animate({ marginTop: '-=82px', opacity: 0 }, 800, function ()
{
listTop.remove();
});
}, 3000);
You can concatenate everything together, set a delay in between and remove the setTimeouts-function.
Checkout http://api.jquery.com/animate/ and http://api.jquery.com/delay/
There is also a short example $('#foo').slideUp(300).delay(800).fadeIn(400);

jQuery animate within animate callback works only once

I have two pagination links which trigger a jQuery animation.
A callback function on the animation triggers a second animation.
This works fine, however, it only works the first time the function is called.
Each time after, the first of the 2 animations works and the second one does not, it merely changes the CSS without the effect.
I'm racking my brain here, to no effect (pun intended).
function switchItem(e) {
e.preventDefault();
// If not current piece
if($(this).hasClass('light')) {
/* VARIABLES */
var container = $('.portfolio footer .portfolio_content');
var link = $(this).attr('id');
var newItem = $(this).html();
/*===================================================
* This is the Key part here
===================================================*/
/* FIRST ANIMATION */
container.animate({
'right':'-100%'
}, 300, 'swing',
// Callback Function
function() {
$(this).html('').css({'left':'-100%'});
$.get('inc/portfolio/'+link+'.php', function(data) {
container.html(data);
/* SECOND ANIMATION */
container.animate({
'left':'0%'
}, 300, 'swing');
});
});
}
}
Here is the demonstration: http://eoghanoloughlin.com/my_site/#portfolio
See working sample here, your left is conflicting with your first right -100% animation and at the end if you don't reset the right then it will conflict with your second left animation
http://jsfiddle.net/PAdr3/2/
reset left before animating
container.css('left', 'auto');
and reset right when complete
container.animate({
'left':'0%'
}, 300, 'swing', function() {
$(this).css('right', 'auto');
});
When you replace the html in a page with new content, it will not automatically add listeners or other jquery enhancements that are added via javascript.
I suspect you need to apply these again after you put the content you fetched with $.get into the page.
Another alternative, is to add all the content in one load, but make the second page hidden. This is probably a nicer alternative than using $.get
I think that the animate function does not string until the first animate is ready. The docs say:
If supplied, the complete callback function is fired once the
animation is complete. This can be useful for stringing different
animations together in sequence.
Something like this might work:
function switchItem(e) {
e.preventDefault();
// If not current piece
if($(this).hasClass('light')) {
/* VARIABLES */
var container = $('.portfolio footer .portfolio_content');
var link = $(this).attr('id');
var newItem = $(this).html();
/*===================================================
* This is the Key part here
===================================================*/
/* FIRST ANIMATION */
container.animate({
'right':'-100%'
}, 300, 'swing',
// Callback Function
function() {
$(this).html('').css({'left':'-100%'});
$.get('inc/portfolio/'+link+'.php', function(data) {
container.html(data);
});
}).complete(
/* SECOND ANIMATION */
container.animate({
'left':'0%'
}, 300, 'swing');
);
}
}

Categories

Resources