JQuery animate .css() rather then using .anmiate()? - javascript

I want to aniamte the change of the margin-top of a div.
Normally I would so this as such:
$("#mydiv").animate({ marginTop: '+='+myvar}, 200);
But this always adds (or subtracts) the value. I want a way to simply aniamte the change in value.
For example: if the div starts of with a margin top of 100 and myvar value is 50 I want to animate the div so it shrinks back to 50. Likewise if the myvar value is 200 I want to animate the change so grows to 200.
I can achieve this somewhat but resetting the CSS, eg:
$("#mydiv").css("margin-top", "0px");
$("#mydiv").animate({ marginTop: '+='+myvar}, 200);
each time but that makes it a bit clunky.
Does anyone know of a may to achieve this?
(Ps: without using CSS transitions)
EDIT: Added my code below
$("#info1tab").click(function() {
$(".textbox").slideUp('200');
$("#info1").delay(300).slideDown('200');
var itemheight = $("#info1").css("height");
var itemheightint = parseInt(itemheight);
$("#photobox").animate({ marginTop: itemheightint }, 200);
});
$("#info2tab").click(function() {
$(".textbox").slideUp('200');
$("#info2").delay(300).slideDown('200');
var itemheight = $("#info2").css("height");
var itemheightint = parseInt(itemheight);
$("#photobox").animate({ marginTop: itemheightint }, 200);
});

what is wrong with $('#mydiv').animate({marginTop: myvar});?
http://jsfiddle.net/muVsE/

Create additional CSS classes that has the CSS properties you want and then do:
$("#mydiv").addClass("classname", 1000);
OR
$("#mydiv").removeClass("classname", 1000);

Try this code:
$("#mydiv").css("margin-top", "0px");
$("#mydiv").animate({ marginTop: topMargin+myvar}, 200);

I hope this helps JSFiddle
$('#left-bg, #right-bg').click(
function(){
$(this).animate({'width': '100%'},600).siblings().animate({'width':'0'},600);
});
Or you can use this JSfiddle
$('#left-bg, #right-bg').click(
function(){
$(this).animate({'width': '100%'},600).siblings().animate({'width':'0'},600);
$('<button class="show">Show all</button>')
.appendTo('#wrapper');
});
$('.show').live('click',
function(){
$('#left-bg').animate(
{
'width': '50%'
},600);
$('#right-bg').animate(
{
'width': '50%'
},600);
$(this).remove();
});
Or you can use this to expand one div and shrink other at the same time:
$('.cell')
.on('mouseenter', function(){
$(this).animate ({width:"75%"},"slow").siblings('.cell').animate({'width': '15%'}, "slow");
})
.on('mouseleave', function(){
$(this).add($(this).siblings('.cell')).animate ({width:"45%"},"slow");
});
Regards.

Related

How do I restrict a jquery script to the size of the container div

I have created a gallery and buttons to control the gallery as well. I am a newbie to jquery and used a small script to change the margin by a fixed amount on a div container. The script works great but it extends past the top and bottom of the div contents. I would set a specific size to the div, but the idea is to use this on multiple pages with varying amounts of content.
How do I restrict the the button function to not expand past the content inside the div?
$('.scrolltdup').click(function(event) {
event.preventDefault();
$('.wrap').animate({
marginTop: "+=160px"
}, "fast");
});
$('.scrolltddown').click(function(event) {
event.preventDefault();
$('.wrap').animate({
marginTop: "-=160px"
}, "fast");
});
I made a jsfiddle with the page content I have. Any help would be greatly appreciated. This is my first from scratch site using html5, CSS3 and jquery. It's a learning experience. :)
Thanks in advance
Just add some if statements:
Updated fiddle: https://jsfiddle.net/2LcumL6p/4/
$('.scrolltdup').click(function(event) {
event.preventDefault();
if (parseInt($('.wrap').css('margin-top')) < 0) {
$('.wrap').animate({
marginTop: "+=160px"
}, "fast");
}
});
$('.scrolltddown').click(function(event) {
event.preventDefault();
if (parseInt($('.wrap').css('margin-top')) > -($('.wrap').height() - 160)) {
$('.wrap').animate({
marginTop: "-=160px"
}, "fast");
}
});
The container is a fixed shape, showing 3 visible boxes at once, so you can get the number of sets of 3 with var totalRows = Math.max( $(".box").length / 3 ).
From there, you can extrapolate the max marginTop before you run out of projects, and just test the marginTop before animating. The most minimal way to detect maxScroll and minScroll on page load (setting them to the maximum and minimum marginTops), and then drop a ternary operator into your animate code.
Change marginTop: "+=160px"
To marginTop: "+=" + ( $(".wrap").css( "margin-top" ) > maxScroll ? "0px" : "160px";
and do the same for marginTop: "-=160px" .
Considering Each Row will have two Div with class box here is a working code that will find the max height of the two div and animate accordingly
var presentRow=1;
function getHeight(elem1,elem2){
return Math.max($(elem1).outerHeight(),$(elem2).outerHeight())+10;
}
$('.scrolltdup').click(function(event) {
event.preventDefault();
height=getHeight($(".wrap .box:nth-child("+presentRow+")"),$(".wrap .box:nth-child("+(presentRow+1)+")"));
$('.wrap').animate({
marginTop: "+="+height+"px"
}, "fast",function(){
presentRow=presentRow-2;
});
});
$('.scrolltddown').click(function(event) {
event.preventDefault();
height=getHeight($(".wrap .box:nth-child("+presentRow+")"),$(".wrap .box:nth-child("+(presentRow+1)+")"));
$('.wrap').animate({
marginTop: "-="+height+"px"
}, "fast",function(){
presentRow=presentRow+2;
});
});
You can add some validation too by checking the presentRow variable.

change css of body on mouseover

I want to get an highlighting effect on some various div container while the rest of the site should be dampened down in opacity including the background-image.
Any idea?
Why does this code not work? tried .hover() instead of .mouseover() too but the function won't react on any input...
$(function () {
$('body').mouseover(function () {
$('body').prop({
"background-color": "red";
});
});
});
Another try would be to set a frame around the body tag in the html and then set props to that frame while the hovered frame is in normal state but I have no idea how to do this. Just beginning with js dev. :)
EDIT: did a fail...
$(function () {
$('body').mouseover(function () {
$('body').css({
"opacity": "0.3";
});
});
});
should be that way...
any way to apply the opacity to the background image too?!
fiddle Demo
Use .css()
Set one or more CSS properties for the set of matched elements.
$(function () {
$('body').mouseover(function () {
$(this).css({
"background-color": "red"
});
//or $(this).css("background-color","red");
});
});
this
.prop()
Set one or more properties for the set of matched elements.
.prop() will set the property for a particular element. In your case you have to use .css() to set the style. Please read .prop() and .css() to see the difference.
Try this,
$(function(){
$('body').mouseover(function(){
$(this).css({"background-color":"red"});
});
});
DEMO
Here's a FIDDLE
body {
background: gray;
min-height: 1000px; /* For demo purposes */
}
css
$(function() {
$('body').on('mouseover', function() {
$(this).css({ backgroundColor: 'red' });
});
});
animate
$(function() {
$('body').on('mouseover', function() {
$(this).animate({ backgroundColor: 'red' }, 600);
});
});
*Note: For some reason it doesn't work with jQuery 1.x(edge).
I think this is what you might want: a "dim" DIV element that adds a semi transparent black box on the entire page, that puts itself "below" the DIV you want to highlight, and then some javascript to turn it off and on, and rearrange the z indexes. The HTML would look something like this:
this is some text
<div id="div1" class="dimmable">hello</div>
<div id="div2" class="dimmable">goodbye</div>
<div id="dim"></div>
And then the JS:
$('div.dimmable').hover(function() {
$(this).css('z-index', 101);
$('#dim')
.css('z-index', 100)
.width($(window).innerWidth())
.height($(window).innerHeight())
.fadeIn();
}, function() {
var dimmable = $(this);
$('#dim').fadeOut({complete: function() {
dimmable.css('z-index', 99);
}});
});
You can see it working here.
A slight catch: the DIVs need to have position:relative, otherwise you can't change their z-indexes and you can't put them on top of the "dim" DIV. Also, anything with a higher z-index will not stay behind the "dim", of course, but you can just use higher numbers as a workaround.

How to use queue in jQuery animate?

I want to increase/decrease the font of and element, then the next element of that class and so forth, for a set of elements as <div class="test"></div> <div class="test"></div> ..... I mean
step 1: enlarging the first element and returning to normal size
step 2: enlarging the second element and returning to normal size
....
My basic code is
$(document).ready(function() {
$('.test').animate({
left:50,
fontSize: "2em"},
"slow")
.animate({
left:-50,
fontSize: "1em"},
"slow");
This will affect all the elements at once. How can I make a queue to make the changes one by one. Having one enlarged element at a time.
You could do it with
$('.test').each(function(idx){
var duration = 1200; // duration for all animations (2 x slow)
$(this)
.delay(duration*idx)
.animate({ left:50, fontSize: "2em" }, 'slow')
.animate({ left:-50, fontSize: "1em" }, 'slow');
});
Demo at http://jsfiddle.net/gaby/rz5Es/
For more precise control and more freedom on queuing look at my answer at a similar question:
A non-nested animation sequence in jQuery?
You need to use callbacks and an array of the elements you want to sequentially animate...
function animateSequence(elements){
var element = $(elements).first();
var originalSize = $(element).css('font-size');
elements = $(elements).not($(element));
$(element).animate(
{ fontSize: "2em" },
"slow",
function(){
$(this).animate(
{ fontSize: originalSize },
"slow",
function(){
if(elements.length > 0)
animateSequence(elements);
}
)
}
);
}
animateSequence($('.test'));
If you want to play with it: http://jsfiddle.net/xS7X7/
You will need to loop thru all elements and execute animate on each of them sequentially, here is sample code to do that recursively
function animate_sequential(elems, css, delay, index){
if(index===undefined) index = 0;
if(index >= elems.length) return;
$(elems[index]).animate(css, delay, function(){
animate_sequential(elems, css, delay, index+1)
})
}
animate_sequential($('div'), {'font-size':'30px'}, 500)
animate_sequential($('div'), {'font-size':'15px'}, 500)
See it in action http://jsfiddle.net/anuraguniyal/QJc9L/
It can be easily converted to a jQuery plugin, so that you can do $('div').animate_sequential and keep same interface as jQuery animate, you can also further enhance it so that it brings back to original css by passing the original css or getting it from element.
As I understand you are trying to do something like this,
$(document).ready(function() {
(function mycallback(i) {
var elems = $('.test');
elems.eq(i).animate({
left:50,
fontSize: "2em"}, function () {
mycallback(i + 1 < elems.length ? i + 1 : 0);
});
}(0));
});
​DEMO
UPDATE:
It was an example code, you can change it like this if you want to reverse effects,
$(document).ready(function() {
(function mycallback(i) {
var elems = $('.test');
elems.eq(i).animate({
left:50,
fontSize: "2em"}, function () {
$(this).animate({
left:-50,
fontSize: "1em"},
"slow");
if (i + 1 < elems.length)
mycallback(i+1);
});
}(0));
});
​UPDATED DEMO
So much simpler, readable, and scalable with Frame.js:
$('.test').each(function(i){
var element = $(this);
var originalSize = element.css('font-size');
Frame(function(next){
element.animate({ fontSize: "2em" }, "slow", next);
});
Frame(function(next){
element.animate({ fontSize: originalSize }, "slow", next);
});
});
Frame(function(next){
// add a callback after all the animations have finished
next();
});
Frame.start();

How to add an animation to this margin-top value change?

I've got a basic little js/jquery function, but I can't seem to get the animation work for a change to the Body's "margin-top" - I need the current value of 3em to animate down to 0em. Here's my function:
$(".notify-close").click(function () {
$('#notify-container').css('display', 'none');
$('body').css("margin-top", "0em");
});
One part I can't figure out is how to remove pixels (or EM in this case) - for example, here's an idea regarding adding 50 pixels to a current margin-top, with a "+=50" value, but what's the REMOVAL equivalent to this in EM? Like "-3EM" ????:
$("body").animate({
margin-top: "+=50"
}, 1500 );
Did you try this?
$("body").animate({
margin-top: "-=50em"
}, 1500 );
$("body").animate({
margin-top: "50px"
}, 1500 );
I just used this script - it's not 100% animated in regards to changing the EM value for the body's margin-top value, but its a basic fix for now:
<script>
$(".notify-close").click(function () {
$('#notify-container').css('display', 'none');
$('body').css("margin-top", "0");
});
</script>

Setting height of text area based on text inside of it using jQuery

I have a <textarea> element in my form that has this code attached to it:
$('#links').focusin(function() {
$('#links').animate({
height: '100px'
}, 300, function() {
// done
});
});
This works perfectly, when the text area gets focus it increases in height nicely to 100px. Now, I want it to shrink back down to a suitable size based on the text inside it when it loses focus. I wrote this:
$('#links').focusout(function() {
$('#links').animate({
height: 'auto'
}, 300, function() {
// done
});
});
But it doesn't work, it just stays at the same height (100px). Is there any way to do this?
Thanks. :)
Edit: To save some confusion, the even handler for $('#links').focusout works fine, that's the first thing I tested. So I assume it's a problem with the animation or the CSS property.
Try $( '#links' ).blur( function(){ ... } ) instead
http://api.jquery.com/blur/
Edit, your actual code:
$('#links').blur(function() {
$('#links').animate({
height: 'auto'
}, 300, function() {
// done
});
});
Some other notes.. You can use $( '#links' ).focus() instead of focusin, and also, once you're in the function, you can use $( this ).animate(), as a shortcut. Just little tips and whatnot.
This isn't quite the same as what you're doing, but quite similar: http://james.padolsey.com/javascript/jquery-plugin-autoresize/
auto_height_link = $( '#links' ).css('height');
$('#links').focusin(function() {
$(this).animate({
height: '100px'
}, 300, function() {
// done
});
}).focusout(function() {
$(this).animate({
height: auto_height_link
}, 300, function() {
// done
});
});
but anyways the animate doesnt read the css value auto for height
i stumbled upon this http://www.unwrongest.com/projects/elastic/ which is what you need i guess
You can't use auto to animate in jQuery. You should set it to auto, then get the actual height (in px) and finaly animate it.
Take a look here

Categories

Resources