Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set width and height dynamically using jQuery

Tags:

html

jquery

I would like to set the width and the height of the div element dynamically using jQuery.

I was trying to replace

<div id="mainTable" style="width:100px; height:200px;"></div> 

with this:

$("#mainTable").css("width", "100"); $("#mainTable").css("height", "200"); 

but, it does not work for me.

Please help to understand why.

Thank you all !

The problem was with the quotation marks on numbers. This works fine:

$("#mainTable").css("width", 100); $("#mainTable").css("height", 200); 
like image 639
Misha Moroshko Avatar asked Apr 27 '10 14:04

Misha Moroshko


People also ask

How do I set dynamic height in jQuery?

Answer: Use the JavaScript height() method You can set the height of a <div> box dynamically using the jQuery height() method.

How do I set the width of an element in jQuery?

jQuery width() Method The width() method sets or returns the width of the selected elements. When this method is used to return width, it returns the width of the FIRST matched element. When this method is used to set width, it sets the width of ALL matched elements.

How do I change the width of a DIV dynamically?

Answer: Use the JavaScript width() method You can set the width of a <div> box dynamically using the jQuery width() method.

How do I change the height of a DIV dynamically?

The content height of a div can dynamically set or change using height(), innerHeight(), and outerHeight() methods depending upon the user requirement.


2 Answers

You can do this:

$(function() {   $("#mainTable").width(100).height(200); }); 

This has 2 changes, it now uses .width() and .height(), as well as runs the code on the document.ready event.

Without the $(function() { }) wrapper (or $(document).ready(function() { }) if you prefer), your element may not be present yet, so $("#mainTable") just wouldn't find anything to...well, do stuff to. You can see a working example here.

like image 199
Nick Craver Avatar answered Oct 28 '22 11:10

Nick Craver


As @Misha Moroshko has already posted himself, this works:

$("#mainTable").css("width", 100); $("#mainTable").css("height", 200); 

There's some advantage to this technique over @Nick Craver's accepted answer - you can also specifiy different units:

$("#mainTable").css("width", "100%"); 

So @Nick Craver's method might actually be the wrong choice for some users. From the jquery API (http://api.jquery.com/width/):

The difference between .css(width) and .width() is that the latter returns a unit-less pixel value (for example, 400) while the former returns a value with units intact (for example, 400px). The .width() method is recommended when an element's width needs to be used in a mathematical calculation.

like image 20
DomTomCat Avatar answered Oct 28 '22 10:10

DomTomCat