js- m
js- m

Reputation: 143

.offset() and checking the position in jQuery

This is my HTML code:

<div class="snake">
        <div class="body"></div>
    </div>

In script I have a function that creates body parts and appends them to .snake.

It looks something like this:

$('.btn1').click(function() {
    length++;
    $('<div></div>').addClass('body').appendTo('.snake').css('left', xPos * length * 1.2 + '%');   
});

Then another function removes the last body part, creates a new one, puts it on the top and gives it .head class.

$('.snake').children().last().remove();
$('<div></div>').addClass('body').prependTo('.snake').css('top', 0 + '%').css('left', xPos * blocks_moved * 1.2 + '%');
$('.snake').children().removeClass('head');
$('.snake').children().first().addClass('head');

So every time this function is called new <div> is given the .head class.

var headPos = $('.head').offset();
            alert(headPos);

In the two lines of code above I tried to alert .head's position but I used .offset() so it should alert coordinates depending on document not on parent element. This two lines are also in teh function above. It alerts something like [object Object]. Why isn't this working? I need this variable so I can set .snake position the same as .head position.

I tried this with $('.snake').position(headPos); but I think that .position() function can't set the position. Any other ways of doing this and some help with .offset() would be great. I'm new to programming so any advices would be helpful. :)

P.S.

I forgot one more thing. What about css? Which position values should I use? I used position: absolute; with both head and body parts.

Upvotes: 0

Views: 144

Answers (1)

roryok
roryok

Reputation: 9645

offset() is an object containing two properties, top and left.

use offset().top to get the y position

var headPos_x = $('.head').offset().left;
var headPos_y = $('.head').offset().top;
alert("x:" + headPos_x + ", y:" + headPos_y);

Upvotes: 2

Related Questions