Make sure to set the margin within the loop where the margin variable is established. When a variable is declared in a function/loop, its 'scope' is restricted to that specific function/loop.
$('ul li').hover(function() {
$(this).prevAll().each(function() {
var margin = $(this).width();
$(this).css('margin-left', margin + 'px');
});
});
If you need to access the margin value outside the loop, you must define it beforehand like so:
$('ul li').hover(function() {
var margin = 0;
$(this).prevAll().each(function() {
margin = $(this).width();
});
$(this).css('margin-left', margin + 'px');
});
To have a global scope for the margin variable, declare it before any other actions:
var margin = 0;
$('ul li').hover(function() {
$(this).prevAll().each(function() {
margin = $(this).width();
});
$(this).css('margin-left', margin + 'px');
});
//Now, the margin can be utilized here as well.
The initial solution should suit your current needs, but I've provided the alternate approach just in case you encounter similar situations in the future.