if / else in jquery animation not working - javascript

I'm trying to use an if statement in jQuery to animate a div and all that's inside of it. I'm using code that's worked in other instances. For some reason the else statement has no effect, is it something about using it with animation?
$(document).ready(function() {
$('.container ').on('click', enlarge);
function enlarge() {
if ($(this).css('font-size') != '100%')
$(this).animate({ 'font-size': '100%' }, 1000);
else
$(this).animate({ 'font-size': '62.5%' }, 1000);
};
});
The if works fine. The container loads on the page at 62.5%, and clicking on it enlarges it to 100%. Now I want to shrink it if someone clicks a second time, thus the else. But nothing happens on the second click.
If I take out the word else, then on click it enlarges to 100%, then shrinks back down again to 62.5%, which makes sense. But so the shrinking code works.
I also tried including the following in place of else, but same result, nothing.
else if
($(this).css('font-size') == '100%')

$(this).css('font-size')
above code returns 'px' value.
if you want to get percentage value use this
$('.container')[0].style.fontSize

Related

jQuery- animate() only works once

I have some functionality on my web page to hide or show the side-menu. I have two divs, #collapse-side-nav, and #expand-side-nav. The way it is set up right now is that by default #expand-side-nav's style is set to display:none; . Then when the user clicks on the collapse-side-nav id the side-nav collapses and then #expand-side-nav gets displayed.
I noticed that the new #expand-side-nav's positioning needs to be further to the right and a little bit higher than #collapse-side-nav's div, and I wanted to achieve this with animations so that it looks sleek. My code is below. However, when I test this out in the browser the animation only works once.
$('#collapse-side-nav').click(function() {
$('.side-nav').toggle(300);
$('#collapse-side-nav').css('display', 'none');
$('#expand-side-nav').css('display', 'inherit');
$('#expand-side-nav').animate({
'margin-left' : 34,
'margin-top' : 2
}, "slow");
$('.container').animate({
'padding-left' : 0
}, "slow");
});
$('#expand-side-nav').click(function() {
$('.side-nav').toggle(325);
$('#expand-side-nav').css('display', 'none');
$('#collapse-side-nav').css('display', 'inherit');
$('.container').animate({
'padding-left' : 200
}, "slow");
});
EDIT:
I will try and post a fiddle later today. I also tried incrimenting rather than declaring exact pixels (jQuery- animate() only works once)
However this increments each and every time meaning the css will keep getting pushed further and further to the right every single time the user clicks on the div.

jQuery Animation is delayed on scroll

I have it set to a div's width increases when I scroll past it with the following code. Now I do this same thing except with .fadeIn() and it works fine. But when I use the .animate() i'll scroll to that location and nothing will happen, but like randomly 30-40 seconds later it will just decide to animate without me even touching/moving anything. Any reason why that is?
HTML
<div>
2500px of CONTENT
</div>
<div class="statbar"></div>
CSS
.statbar {
width:100px;
height:30px;
background-color:#ff4200;
}
jQuery
$(document).scroll(function () {
var y = $(this).scrollTop();
if (y > 2500) {
$('.statbar').animate({width:'200px'}, 300);
} else {
$('.statbar').animate({width:'10px'}, 300);
}
});
Here's a JSFiddle example: https://jsfiddle.net/kr4yeyw3/2/
If you wait like 30 seconds at the div, you'll see the animation will take place (need it to happen instantly like the fadeIn() does.
EDIT: It works when I change those 300 to zeros, but it doesn't animate! Just changes width instantly without "sliding" it over.
EDIT2: Finally figured it out for anyone who one day scrolls across this page looking for a similar answer.
Adding clearQueue(), stop() and easing seemed to do the trick
$('.statbar').clearQueue().stop().animate({width:'75%'}, { "duration": 400, "easing": "linear" });
clearQueue or Stop will do fix the animation, but it doesn't address the real problem with your code. In your else statement, which is hit like 2000 times as you scroll to the bottom of the page, you are starting an animation with a duration of 400 milliseconds.
jQuery animate puts all animations into a queue and calls them one after the other so it creates a huge delay before the animation you actually want to see. api.jquery.com/animate/
Here's how I think you should rework your code:
var isExpanded = false;
$(document).scroll(function () {
var y = $(this).scrollTop();
if (y > 2500) {
$('.statbar').animate({width:'200px'}, 300);
isExpanded = true;
} else if(isExpanded) {
$('.statbar').animate({width:'10px'}, 300);
isExpanded = false;
}
});
Here I use a flag to determine if the animation needs to be run and just toggle it as we switch display modes.

Make Image Grow Larger On Press And Toggle

On a website, I have a list of news articles mentioning a certain thing. I want the articles to be able to be pressed, and when they are, the image source will switch with the image source of the actual article, and the image will grow to an arbitrary size. When you click the image again, it should go back to normal. I also want it to set itself to be absolutely positioned or something that way it doesn't push elements out of its way when it grows.
I guess my first question would be, is there already a code snippet or easy implementation of this or something similar? I have not been able to find one.
Second, I am in the process of making my own, and for whatever reason, when the page loads, every image just fades to disappearing without anything being pressed. Here is my code so far...
$(".newsCover").toggle(function () {
$(this).animate({
width: "auto",
height: "1000px"
}, 1500);
}, function () {
$(this).animate({
width: "auto",
height: "300px"
}, 1500);
});
Can anyone tell me what is wrong with it and how to fix it? I have a feeling its just something really stupid...
Thanks so much!
The .animate() method allows us to create animation effects on any
numeric CSS property.
All animated properties should be animated to a single numeric value, except as noted below;
http://api.jquery.com/animate/
However, you can hack it by determining the auto height/width as a hard number:
JavaScript jQuery Animate to Auto Height
The toggle function that you are using was deprecated in 1.8, and removed in 1.9, see here: http://api.jquery.com/toggle-event/ In v 1.9+, the toggle function now simply hides the element.
With no parameters, the .toggle() method simply toggles the visibility
of elements
The parameters that can be passed to the new toggle function can be found here: http://api.jquery.com/toggle/ With the new toggle function, you are unable to run the .animate() function within it. To achieve what you're trying to do, you could do something like:
$(".newsCover").click(function() {
if($(this).height() > 300) {
$(this).animate({
width: "auto",
height: "1000px"
}, 1500);
}
else {
$(this).animate({
width: "auto",
height: "300px"
}, 1500);
}
});

Javascript move div onClick

I'm trying to get a div #sidebar that rests above my main #stream div to move from position left: 565px; to position left: 0px; onClick of one image in the #sidebar div (the red arrow in the images below), and do the reverse onClick of the same image. I know I have to use JavaScript, but I have no idea what the code would be. If possible, I would like to animate the div move too.
The pre-clicked state (the arrow will be my link):
The post-clicked state:
Thanks in advance!
If you want to animate it using animate have a look at this. It should get you pointed in the right direction:
http://jsfiddle.net/3DpfJ/5/embedded/result/ - Full screen result
http://jsfiddle.net/3DpfJ/5/ - source code
So what I simply did was this:
$(function()
{
var expanded = false;
$('#sidebar').click(function()
{
if (!expanded)
{
$(this).animate({'left' : '0px'}, {duration : 400});
expanded = true;
}
else
{
$(this).animate({'left' : '565px'}, {duration: 400});
expanded = false;
}
});
});
This is probably the simplest way of doing it via animation. Duration is set to 400 so it will take 0.4 seconds to animate. Adjust as you please.
This script should be executed as soon as you load the page to ensure that the expand works. You will want to create <script type="text/javascript"></script> tag in the header and put the code there.
Hope it works for you.
$('#sidebar').click(function(){
$(this).animate({"left": "0"});
});
jquery uses toggle to handle this. It works better than a regular "animate" because it combines the hide and show into one function (toggle).
You might need to do some tweaking to fit your needs but this should get you started:http://jqueryui.com/toggle/

Set height as auto on expanding DIV with jQuery

I am trying to set the height of a DIV to auto when I expand it, but when ever I do just '' it shrinks it down, or when I do 'auto' it does nothing. How do I get it to change the height to auto? I have content that will be all different heights and dont want to have to pass in a height parameter every time I set one of these up .This is what I have that is not working properly. The DIV will start out at a static height then needs to expand to expose all of the text in the DIV.
My jsFiddle:
http://jsfiddle.net/gNsrG/
This is my jQuery code:
function changeheight(_this) {
var thisText = $(_this).text() ;
if (thisText == 'more') {
$('#overviewtext').animate({
'height': ''
}, 600);
$(_this).text((thisText == 'more') ? 'less' : 'more');
}
else if (thisText == 'less') {
$('#overviewtext').animate({
'height': '150px'
}, 600);
$(_this).text((thisText == 'more') ? 'less' : 'more');
}
return false;
};
You shouldn't have to change the height ever. You should just be using JQuery's slidedown and slideup
I've made some changes to you example on jsfiddle
EDIT
I misunderstood what the question was. You want some text to show then you click more and more text shows. Then click less and less text shows. I've accomplished this but it is a bit hacky. Apparently JQuery doesn't do well with animating auto and percentages. Basically is what I did is when you click more. I stored the current height. Temporarily changed it to auto which makes it fully open. Got that height. Changed it back to closed (Hopefully the user doesn't see this). Then took that height and used it for the animate. I'm hoping there is an easier way but right now I can't find it.
My example is here jsfiddle
The only other way I can think of to accomplish this is to have an inner div that contains all the "MORE" text that you slidedown and slideup on but you would have to be able to differentiate where the cutoff was for the more text.
Improved code:
function changeheight(_this) {
$('#overviewtext').slideToggle(600);
$(_this).text($(_this).text() == 'more' ? 'less' : 'more');
return false;
};
Demo here http://jsfiddle.net/gNsrG/3/
you can change an element's css using .css(), in this case it would look like
$('#overviewtext').css('height', 'auto');
you might try adding that line after the animate call.
I had a similar problem and my solution was to use JqueryUI which animate classes on toggle when clicking in the actual text
jQuery ("#box_description_texts p").click(function() {
jQuery(this).toggleClass("box_text_expanded", 250);
});
and in the CSS
#box_description_texts p.box_text_expanded {height: auto;}

Categories