Reputation: 35983
To set the margin of an element I'd like to calculate it's difference in size before browser resize and after. How would I access the resizeW variable outside of the resize function, or use the startW inside the resize function without it changing.
var startW = $('li').width(); // width before resize
$(window).resize(function() {
var resizeW = $('li').width(); // width after resize
var diff = (startW - resizeW); // startW and resizeW are the same
} );
$('li').css('margin-left',(startW - resizeW)); // resizeW is not defined
For example: If the element I'm getting the width of is 300 pixels before resize and then I trigger resize. Afterwards the element is 200 pixels. I want to calculate the difference. 300 - 200
Upvotes: 2
Views: 1939
Reputation: 1139
your resizeW is defined in the inside of the function... so you have a scope problem... try the following:
var startW = $('li').width(); // width before resize
var resizeW = startW;
$(window).resize(function() {
resizeW = $('li').width(); // width after resize
var diff = (startW - resizeW); // startW and resizeW are the same
} );
$('li').css('margin-left',(startW - resizeW)); // resizeW is not defined
Upvotes: 0
Reputation: 673
The main problem in your code is that the resize will be called when the window is resized, but you are doing the $('li').css('margin-left',(startW - resizeW));
just after declaring the resize listener, so it will do nothing even if you put the var resizeW
outside.
I think startW
should not be the same as resizeW
inside the resize function, so there has to be something more. If you want to change the margin-left every time the window is resized, just put the $('li').css('margin-left',(diff));
also inside the resize function.
Upvotes: 0
Reputation: 206078
var $li = $('li'), // Cache your element
startW = $li.width(); // Store a variable reference
function setMarginDiff(){ // Create a function that modifies the margin
var currW = $li.width(),
diff = startW - currW ;
$li.css({marginLeft : diff});
}
setMarginDiff(); // Do on DOM ready
$(window).resize(setMarginDiff); // and on resize
Upvotes: 2