Ichimonban
Ichimonban

Reputation: 97

jQuery calculate width, and apply width to desired container

I am attempting to calculate the viewport width, and then subtract a value from that then apply the result to the desired container. I've found some examples that are close and managed to cobble together the following but it's not doing any thing at all.

$(document).ready(function() {
var aa = $(window).width(); 
var bb = $(“#controlWidget”).width();
var cc = (aa – bb) + "px";
document.getElementById(‘thumbList’).style.width = cc;
});

Thanks in advance!

Upvotes: 1

Views: 1697

Answers (2)

Demian Brecht
Demian Brecht

Reputation: 21378

A few things:

$(function() {
    $("#thumbList").width($(window).width() - $("#controlWidget").width());
});

Unless you're using them for something else, the temp variables are not needed.

Also, I have no idea if this is due to whatever editor you're using, but you've inserted invalid characters into your sample code block. For example, should be " and should be - (notice the subtle differences in both). Javascript interpreters bork on those characters as they're invalid in the given context.

Finally, you shouldn't mix pure Javascript with jQuery, it doesn't make a whole lot of sense. Rather than applying the width through document.getElementById, you should simply use jQuery's width function, which also allows you to set the width.

Upvotes: 3

Fabrizio Calderan
Fabrizio Calderan

Reputation: 123428

  1. check the value of aa and bb before last statement (use an alert or a console.log() )
  2. be sure element thumbList exists
  3. change last statement with a simpler $(#thumbList).width(aa-bb)

jQuery width can also be used to set a width, from http://api.jquery.com/width/

If no explicit unit was specified (like 'em' or '%') then "px" is concatenated to the value.

Upvotes: 1

Related Questions