Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use css calc() in jquery

How can I do this?

$('#element').animate({ "width": "calc(100% - 278px)" }, 800);
$('#element').animate({ "width": "calc(100% - 78px)" }, 800);

I can do it if it's only % or only px, but not calc(), can I use some other option of jQuery? or some other trick of JavaScript?

It's a change that have to be done when the user clicks some element, so:

$("#otherElement").on("click", FunctionToToggle);

when the user clicks the $("#otherElement") the toggle effect has to occur.

like image 520
Albert Cortada Avatar asked Feb 20 '14 14:02

Albert Cortada


2 Answers

maybe this helps:

$('#element').animate({ "width": "-=278px" }, 800);

every time this script will remove 278px from the element

edit: Try this it will recalculate when the window is resized. If i understand you correctly that should help.

$(window).on("resize",function(){
   $('#element').css("width",$('#element').width()-275+"px");
});

CSS3 option

Since CSS3 has an animateion function you could also use this:

#element{
   -webkit-transition:all 500ms ease-out 0.5s;
   -moz-transition:all 500ms ease-out 0.5s;
   -o-transition:all 500ms ease-out 0.5s;
   transition:all 500ms ease-out 0.5s;
}

If you want to animate the element. And you could do this:

 $('#element').css("width","calc(100% - 100px)");

In this case the CSS will do the animation.

Please notice that this will not work for older browsers

like image 199
Rickert Avatar answered Sep 19 '22 05:09

Rickert


I'm not sure using calc is going to work out. My answer checks the parent's width, then performs an operation on it, and then animates the element.

elWidth = $('#element').parent().width(); // Get the parent size instead of using 100%
elWidth -= 20; // Perform any modifications you need here
$('#element').animate({width: elWidth}, 500); //Animate the element

http://jsfiddle.net/yKVz2/2/

like image 31
Joe Cullinan Avatar answered Sep 23 '22 05:09

Joe Cullinan