Pergunta

Hi I'm working on a fixed / pinned Div also after re-sizing the Browser Window. To fix the Div is no problem but I'm not able to auto resize the width with jquery. My current code is:

 <script type="text/javascript">
    $(window).load(function(){
        function fixDiv() {
            var $cache = $('.pin');
            if ($(window).scrollTop() > 100)
                $cache.css({'position': 'fixed', 'top': '10px', width: $('.pin-wrapper').width()});
           else
                $cache.css({'position': 'relative', 'top': 'auto', width: $('.pin-wrapper').width()});
        }
        $(window).scroll(fixDiv);
        fixDiv();
    });
    $(document).ready(function(){
        fixDiv();
    });
    $(window).resize(function(){
        fixDiv();
    });
</script>

The Html looks like this:

<div class="grid-12 parent"> <!-- Kolos 12.02.2014 -->
        <div class="pin-wrapper">
                <div id="header" class="main-menu-container grid-12 hide-mobile pin"></div></div></div>

thanks for any help Cheers, Carol

Foi útil?

Solução

You are facing scoping issue, fixDiv() method being declared inside onload handler. You could use instead:

function fixDiv() {
    var $cache = $('.pin');
    if ($(window).scrollTop() > 100) $cache.css({
        'position': 'fixed',
        'top': '10px',
        width: $('.pin-wrapper').width()
    });
    else $cache.css({
        'position': 'relative',
        'top': 0,
        'width': $('#header').width()
    });
}
$(window).on('load resize scroll', fixDiv);

But in your posted HTML markup, it appears than there is no element with class header, looks like you are targeting element with ID header. But then, #header is the same element as $cache, quite confusing.

Outras dicas

As A. Wolff mentioned, you shouldn't add your events in the load function. Because you were doing that, your scroll event was not fired.

You actually don't need load at all as can be seen here:

http://jsfiddle.net/uwkc9/3/

If you scroll or resize you will see that both work.

Also, from practice, I recommend separating your scroll and resize events to use a separate function. It will be easier to maintain in the feature.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top