Cameron
Cameron

Reputation: 28783

jQuery position element based on window resize

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

Upvotes: 4

Views: 16044

Answers (1)

Andy
Andy

Reputation: 30135

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'
        });
    }
});

Upvotes: 4

Related Questions