Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery position altering for sticky headers

The following is a little script that simulates the sticky header effect seen on iOS devices.

$('.scrolllist').scroll(function(){
        $(this).find('ul').each(function(){
            if($(this).position().top <= 0){
                $(this).addClass('abs').find('strong').removeClass('mov');

                if($(this).position().top <= ($(this).height() * -1)){
                    $(this).removeClass('abs');
                    $(this).find('strong').addClass('mov');            
                }
                else {
                    $(this).addClass('abs');
                    $(this).find('strong').removeClass('mov');   
                }
            }
            else {
                $(this).removeClass('abs').find('strong').removeClass('mov');
            }
        });
    });

It changes the position of each element by changing its status from postion:absolute, top:0 to position:absolute, bottom:0; whilst also changing the containing <ul> from position:relative to position:static

SAMPLE: http://jsfiddle.net/dMJqj/80/

Is there anything that can be done to smoothen it up a bit. It looks a bit jerky on Chrome and Firefox and sometimes it can take a fraction of a second to trigger which is noticeable because the sticky header appears to flash.

like image 231
RIK Avatar asked Sep 21 '12 16:09

RIK


People also ask

How do I fix the header position?

To fix the position of the header in the webpage, use position: fixed, and to fix it at top use to top:0.

How do I make the top of my header sticky?

Here are three simple steps: Find the correct style so you can declare the element as sticky using position:sticky; (don't forget browser prefixes like position: -webkit-sticky; ). Choose the “sticky edge” (top, right, bottom, or left) for the item to “stick” to.


1 Answers

I'd imagine that the twitching you're seeing is a result of performance issues within jQuery and JavaScript

These articles are rich with some tips on optimizing the performance of your scripts:

Also -- more than that, it looks like the abs class is getting repeatedly added and remove at every firing of the scroll event when a list's position.top < 0

By itself that doesn't cause visual twitching but it does cause a small bit of memory to be burned unnecessarily.

Also as a few mentioned up above, your HTML was not valid.

See this fiddle with a few optimization techniques applied, valid HTML and removal of some unnecessary class manipulation:

http://jsfiddle.net/DW4pP/

like image 181
tmsimont Avatar answered Oct 02 '22 03:10

tmsimont