简体   繁体   中英

In JQuery how do I get the offset().top of an element after a user removes an element from the DOM with a click

Long title I know. Sorry.

I just want to know how I get the new position after a click event that removes an element. Essentially I have a bar that is removed once the user does a click. There are some buttons on my page that have a fixed position when the distance of the scroll is greater than the offset so it looks like they unhook.

I tried to do offset().top in a callback after a click event, but it just outputs the original offset value not the distance minus the element removed. This makes the buttons just look like they jump into the fixed position as it's not removing the clicked element's height from the offset.

var distance = $('.anchor-con').offset().top;

alert($('.anchor-con').offset().top);

$(".icon-cross").click(function(){

    distance = $('.anchor-con').offset().top;
    alert($('.anchor-con').offset().top);

});

Hope that makes sense. Some help on this would be great.

Thanks

Rob

You can use mouseup event instead of click as you want to know the new position after the click.

try the following code

var distance = $('.anchor-con').offset().top;

alert($('.anchor-con').offset().top);

$(".icon-cross").mouseup(function(){
    distance = $('.anchor-con').offset().top;
    alert($('.anchor-con').offset().top);
});

so you want to know the new top of your anchor after the bar is removed by a click. use a setTimeout in your click handler with 0 delay just to ensure that the bar is removed. the way you are doing does not guarantee that bar is already removed because the bar removal click handler may be executing after your position calculator handler. following will work if i correctly understood your question.

var distance = $('.anchor-con').offset().top;    
alert($('.anchor-con').offset().top);

$(".icon-cross").click(function(){
    setTimeout(function(){
        distance = $('.anchor-con').offset().top;
        alert($('.anchor-con').offset().top);
    }, 0);
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM