Jquery width detection
- Started
- Last post
- 10 Responses
- ESKEMA
How can I monitor the width changes I make to a div via jQuery? It seems that it always reports the initial width..
example:
http://jsfiddle.net/EfEwa/1/In this example I need to update a margin depending on a div width, but the solution would need to work for other stuff..
please help, thanks
- ESKEMA0
no one? :(
- colossalhead0
Basically your variable $coltotal is being set once when the page is loaded in line 3, and it is not being updated as the margins change.
- sublocked0
This is basic, basic javascript stuff dude.
$(function () {
var win, lazyResize;function handleResize() {
var divWidth = $('#somediv').width();
// now do something with that...
}// debounce is an underscore.js function.
// We debounce so it doesn't fire too many times, taking up
// cycles on the user's computer.
lazyResize = _.debounce(handleResize, 100);
// Hold reference to window for speed.
win = $(window);
// Apply event handler on resizing window...
win.on('resize', lazyResize);
// Call it once to start
lazyResize();
});
- sublocked0
Bah...here's a link to a Github gist instead...
- ESKEMA0
Didn't tested your code but isn't that for window resize?
Yeah I'm not great at JS, I'm still trying to learn that shit..
- sublocked0
You asked...
> How can I monitor the width changes I make to a div via jQuery? It seems that it always reports the initial width.
I'm guessing that resizing your browser is changing the width of your div...no? Is it something else?
Whatever it is, you need to figure out the event that's causing it, then bind your event handler it.
- ESKEMA0
Did you see the jsfiddle?
I'm expanding a div on hover, and changing the margin of another, but the margin isn't updating, and because of my poor skills I didnt find a solution yet. Was hoping for some help here
- colossalhead0
Instead of calling changeMargin() immediately, try adding a callback to your animate effect. (see http://api.jquery.com/animate/)
In the callback function (which is executed when the animation is completed) update your coltotal value and then execute the changeMargin function. Basically something like this:
$(this).stop( true, true ).animate({width: "180px"},200, function() {
// Animation complete.
col1 = $(".col1").outerWidth();
col2 = $(".col2").outerWidth();
colTotal = col1 + col2;
$(".col3").text(colTotal);
changeMargin();
});
- ESKEMA0
^^
Yes, thank you, that works!Now, just to fuck things up,
Is this the only way? can't I have both happening at the same time? can't I make simply the variable listen to the div width live somehow?
Right now the margin only updates when the animation is complete (And I'll be content with this result if I can't find another one), the awesome result would be to have the margin update while the width is being updated too!
- ESKEMA0
Ok, I got it like I wanted by putting the changeMargin inside animate progress and it's perfect!
result:
http://jsfiddle.net/EfEwa/2/Cheers!