CptFishPants
CptFishPants

Reputation: 145

Resize div and dynamically detect width

This is probably a simple thing, but being a little bit of a javascript/jquery noob im botching it.

I would like to be able to have a div class, where on changing its size (either manually or as a result of dynamic size 30% etc) reports its size in pixels.

I have found various scripts some of which do similar things, but either they are not quite right .. some do window, some do document, I even found paragraph, but nothing with a div. Or I cant make sense of how its working.

Example of what I want but DIV NOT window:
http://www.mkyong.com/jquery/jquery-resize-example/

Demo: http://www.mkyong.com/wp-content/uploads/jQuery/jQuery-resize-example.html

I suspect I need to change $(window).resize(function () to $(div.class).resize(function () or something but I just cant get it.

Upvotes: 0

Views: 2118

Answers (4)

CptFishPants
CptFishPants

Reputation: 145

Worked it out in the end: http://jsfiddle.net/ablueman/2uvpk2d5/

//DIV with .change class
$('#changelog').text(' W: ' + $('.change').width() + 'px , H:' + $('.change').height() + 'px ');

$(window).resize(function () {
$('#changelog').text(' W: ' + $('.change').width() + 'px , H:' + $('.change').height() + 'px ');
});

Thanks all.

Upvotes: 0

patrykf
patrykf

Reputation: 449

This should work

setInterval(function() {
    $('div#change').text("Width " + $('div#change').width() + ", height " + $('div#change').height()); 
}, 100);

You just simply need to use jQuery resize() method which fires when the target element is resized.

jsfiddle

Upvotes: 0

Yunus Aslam
Yunus Aslam

Reputation: 2466

You have to use window resize function . I think this will help you

$(window).resize(function(){
    console.log($("yourdiv").width()); // This will report the width of your div in px.
});

Hope this helps.

Upvotes: 2

thirdtiu
thirdtiu

Reputation: 91

maybe all you need is jquery ui resizable? since you're using jquery.

http://jqueryui.com/resizable/

and it has lots of options and methods:

http://api.jqueryui.com/resizable/

Upvotes: 0

Related Questions