1

can someone help me properly add calc width with jquery? Or maybe theres a better option for dynamic width in jquery than applying css3 calc width?

var calc = "calc(100% - 270px)";

$(".two").focus(function () {
    $('.one').animate({ width: "85px" });
    $(this).animate({ "width": calc + "px" });
});

http://jsfiddle.net/N6vaj/1/

Let me know if you need more description. Thanks~

3
  • 2
    You can't animate calc, only numerical regular css values can be animated. What exactly are you trying to do here ? Commented Mar 28, 2014 at 17:35
  • 1
    calc is a css property. You shouldn't do calc + "px" in your javascript, just leave it as width:calc. And I don't think it works with animate, either. Commented Mar 28, 2014 at 17:35
  • this is going to be a form on mobile so I want the width to be dynamic depending on container width / mobile device size. when a user clicks each input, all other inputs should get smaller to a point and the selected input should get bigger / fill up the remaining space Commented Mar 28, 2014 at 17:38

1 Answer 1

1

In javascript calc(100% - 270px) would roughly equal getting the width of the parent element (100%) and subtracting 270

$(this).parent().width() - 270;

which leaves you with this

$(".two").focus(function () {
    var w = $(this).parent().width() - 270;

    $('.one').animate({ width: "85px" });
    $(this).animate({ "width": w });
});

FIDDLE

To make it work on all of them, you could do

var inputs = $(".one, .two, .three");

inputs.on('focus', function () {
    var w = $(this).parent().width() - 270;

    inputs.not(this).animate({ width: "85px" });
    $(this).animate({ "width": w });
});

FIDDLE

Sign up to request clarification or add additional context in comments.

1 Comment

your right, 100% is technically talking about 100% of the parent element that makes so much sense. Thank you its exactly what I needed!!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.