Imesh Chandrasiri
Imesh Chandrasiri

Reputation: 5689

Changing an element to absolute postion

I want to make a set of elements position:absolute using jQuery and I've written the below code. The problem is, I cannot chain the two loops into one where the offset end up returning the same value for each element.

$(navSelector + ' > li', this).each(function () {
    var position = $(this).offset().left - $(this).parent().scrollLeft();
    $(this).attr('data-absolute-position', (position + 5));
});

$(navSelector + ' > li', this).each(function () {
    $(this).css({
       'left': $(this).data('absolute-position'),
       'position': 'absolute'
    });
});

if I combine the two loops as following the position will return the same value for each ul > li element. What am I doing wrong here?

$(navSelector + ' > li', this).each(function () {
            var position = $(this).offset().left - $(this).parent().scrollLeft();
            $(this).attr('data-absolute-position', (position + 5)).css({
                'left': $(this).data('absolute-position'),
                'position': 'absolute'
            });;
        });

Sorry guys but the HTML is a bit complex and I've found a work around to my issue. I've simply added a setTimeout and the change works fine! Bt What I'm not sure is, whether this is the best way to do it?

$(navSelector + ' > li', this).each(function(){
            var el = $(this);
            var curPos = el.offset().left - el.parent().scrollLeft();
            var absPos = curPos + 5;

            el.attr('data-absolute-position',absPos);

            setTimeout(function(){
                el.css({
                    'left': absPos,
                    'position': 'absolute'
                });
            },0);

        })

Upvotes: 0

Views: 75

Answers (2)

UIPassion
UIPassion

Reputation: 120

A fiddle will be helpful. But as per my understanding of your requirement, you can't have it chained in one line. You need to split as follows:

$(navSelector + ' > li', this).each(function () {
    var position = $(this).offset().left - $(this).parent().scrollLeft();
    $(this).attr('data-absolute-position', (position + 5));
    $(this).css({
       'left': $(this).data('absolute-position'),
       'position': 'absolute'
    });
});

With the following code that you gave, maybe its not able to properly find and apply the css effect to element.

$(this).attr('data-absolute-position', (position + 5)).css({
                'left': $(this).data('absolute-position'),
                'position': 'absolute'
            });;

Upvotes: 0

Dr3am3rz
Dr3am3rz

Reputation: 563

I'm not sure what you are trying to say.

Probably you can try to find out your total number of li then do a for loop in the each function and return the value.

Upvotes: 1

Related Questions