jquery floating div

Example : In this example we are using position() and scrollTop() functions. The object returned by position() function has top and left properties, which can be used to know the current top and left positions (coordinates). We are using this function to find the top position of the div element that we want to keep floating as we scroll down. To get the current vertical position of the scroll bar, we are using scrollTop() function.  

As we scroll and when the current vertical position of the scroll bar becomes GREATER THAN the top position of the div element, then we want the div element to start floating. To do this set position style to fixed. A fixed position element is positioned relative to the browser window. So as you scroll down it will be floating in the browser window. 

If the current vertical position of the scroll bar becomes LESS THAN the top position of the div element, then we don't want the div element to float, so we set position style to relative. A relative position element is positioned relative to itself. So if you set position to relative and top to 0, it will continue to stay where it is without floating. 


<html>
<head>
    <script src="jquery-1.11.2.js"></script>
    <script type="text/javascript">
        $(document).ready(function () {
            var floatingDiv = $("#divfloating");
            var floatingDivPosition = floatingDiv.position();
            $(window).scroll(function () {
                var scrollPosition = $(window).scrollTop();
                if (scrollPosition >= floatingDivPosition.top) {
                    floatingDiv.css({
                        'position': 'fixed',
                        'top': 3
                    });
                } else {
                    floatingDiv.css({
                        'position': 'relative',
                        'top': 0
                    });
                }
            });
        });
    </script>
</head>
<body style="font-family:Arial;">
    <table align="center" border="1" style="border-collapse:collapse">
        <tr>
            <td style="width:500px">
                Main Page Content
            </td>
            <td style="width:150px; vertical-align:top">
                Side panel content
                <br /><br />
                <div id="divfloating" style="background-color:silver;
                                             width:150px; height:150px">
                    Floating Div - Keeps floating as you scroll down the page
                </div>
            </td>
        </tr>
    </table>
</body>
</html>

Comments

Popular posts from this blog

Drag and Drop multiple File upload using jQuery AJAX in ASP.Net using C# and VB.Net

jQuery dynamic menu from database in asp.net

Automatically send Birthday email using C#.Net