Aviel Fedida
Aviel Fedida

Reputation: 4102

JQuery, wrong left position

I have this code:

$(this).closest("p").after('<strong>' + arMess[iCurIndex] + '</strong>').next().animate({
            top: $(this).offset().top - 57,
            left: -$(this).width() //[First value] Here i get 148px on chrome and 150px on firefox

        }, 300,function(){
            alert($(this).offset().top - 57);
            alert(-$(this).width()); //[Second value] Here i get the true width the one i want to present the left
        });

Code overview: At the first line i animate the STRONG element

As you can see i get 2 different values from -$(this).width():

The first value: I get during the animation process.

The second value: I get after the animation finished.

If anyone got idea about the reason i get 2 different values, I will be very thankful.

Upvotes: 0

Views: 140

Answers (2)

moiter
moiter

Reputation: 162

The problem here is that the javascript keyword this does not have the same value in the inner function that is called after the animation as it does when you are setting the width. For the first value this is the object that triggers the animation. In the function where the alert is called this is the object that is being animated.

Try this:

var $strongElement = $(this).closest("p").after('<strong>' + arMess[iCurIndex] + '</strong>').next();

$strongElement.animate({
       top: $(this).offset().top - 57,
       left: -$strongElement.width() 
    }, 300, function(){
    alert(-$(this).width()); 
});

See http://jsfiddle.net/vtyjf/

Upvotes: 1

Barlas Apaydin
Barlas Apaydin

Reputation: 7315

Try outerWidth or check your element's css if it got float:left

$(this).closest("p").after('<strong>' + arMess[iCurIndex] + '</strong>').next().animate({
            top: $(this).offset().top - 57,
            left: -$(this).outerWidth();
                         // use .outerWidth(true); if you want to 
                         //calculate with margin and border values

}, 300,function(){
            alert($(this).offset().top - 57);
            alert(-$(this).outerWidth());
});

Upvotes: 1

Related Questions