Skip to content

Instantly share code, notes, and snippets.

@user24
Created November 7, 2014 14:05
Show Gist options
  • Save user24/b6ae2948a7941eafe5a8 to your computer and use it in GitHub Desktop.
Save user24/b6ae2948a7941eafe5a8 to your computer and use it in GitHub Desktop.
$('#calendar .barIcons > .barIcon').each(function (i, icon) {
var left;
icon = $(icon);
left = parseInt(icon.position().left, 10);
alert(left); // increases each time
return; // Comment this and now the alert is zero each time.
icon.css({
"position": "absolute"
});
});
@user24
Copy link
Author

user24 commented Nov 7, 2014

(the parseInt was a desperate attempt to ensure that the value is completely divorced from the code that follows, omitting it still produces the odd behaviour. Also yeah it should be parseFloat).

@user24
Copy link
Author

user24 commented Nov 7, 2014

This code, OTOH, works perfectly - the icons stay in the same place but are now absolutely positioned there:

                    $('#calendar .barIcons > .barIcon').each(function (i, icon) {
                        $(icon).css({
                            "left": $(icon).position().left
                        });
                    }).css({
                        "position": "absolute"
                    });

@user24
Copy link
Author

user24 commented Nov 7, 2014

While this breaks (all lefts are set to zero):

                $('#calendar .barIcons > .barIcon').each(function (i, icon) {
                    $(icon).css({
                        "position": "absolute",
                        "left": $(icon).position().left
                    });
                });

@getify
Copy link

getify commented Nov 7, 2014

I'm not sure alert(..) is guaranteed to have to run synchronously. I think a browser could be free to defer it to happen at the end of the function. Not positive on that, but it's one way to explain the behavior you're seeing. I've seen this before in Chrome with console.log(..) as well.

@user24
Copy link
Author

user24 commented Nov 7, 2014

(The CSS and structure of the page shouldn't even make a difference - I just can't see how the position().left could POSSIBLY be affected by the position: absolute; it's value must have been resolved BEFORE the position absolute is applied.)

@user24
Copy link
Author

user24 commented Nov 7, 2014

@getify yeah I know console.log can be async - didn't think alert could. But even then, it is actually setting the values to zero too, even without the alert.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment