mike
mike

Reputation: 749

setting width calc with jquery

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~

Upvotes: 1

Views: 1832

Answers (1)

adeneo
adeneo

Reputation: 318242

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

Upvotes: 1

Related Questions