jQuery position element based on window resize

15,612

you'll need to calculate the position in the window resize event:

$(window).resize(function() {
  // your positioning code here
});

$(document).ready(function() {

    calculation();
    $(window).resize(calculation);

    function calculation() {
        var location = $("#link").offset();

        var top = location.top;

        var left = location.left;
        left = left - $('#tip').width();
        left = left - 15;

        $("#tip").css({
            'position': 'absolute',
            'top': top + 'px',
            'left': left + 'px'
        });
    }
});
Share:
15,612

Related videos on Youtube

Cameron
Author by

Cameron

Updated on June 14, 2022

Comments

  • Cameron
    Cameron about 2 years

    If you look at this page: http://dev.driz.co.uk/tips/ I'm doing some experimentation to learn more about jQuery and how to develop things similar to what we've seen on Facebook.

    You will see I have a tooltip that is positioned relative to the redbox. However if you resize the window it doesn't adjust the tip in relation to it. How do I fix this?

    Also considering that the element is quite tall if the user resizes the window height then I would want the tip to move upwards so it appears within the screen viewport in other words always having about 20px away from the bottom of the page BUT keeping the arrow in the same place it is now so it's only the box that adjusts itself.

    Can anyone help me to achieve those two things? Much appreciated. Thanks

  • Cameron
    Cameron almost 13 years
    Okay how do I use that effectively with my code as if you check now my code ONLY runs when the user resizes the window. I'd rather not wrap the code in a function and then call it in both ready and resize as then I'm repeating myself... Cheers
  • Andy
    Andy almost 13 years
    @Cameron: then do your calculation in a function and call it on resize and on ready. I updated my answer