Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass jquery selector to function

Tags:

jquery

Hello this may be an easy stupid question but how do i pass a jquery selector to a function?

Im doing this but its not working. Thanks in advance!

var $list=$('#startlist')
var $container=$list.parent();
var $containerTop=$('#toprow');
var $containerTwo=$('#etrow #bottomrow');

var $li=$list.find('li');

var totHt=0;
var totItems=$li.length;
var listCount = 0;
    $li.each(function( idx){

    var ht=$(this).outerHeight(true);

    if( totHt + ht >= maxHt || totHt + ht + 10 >=maxHt || idx==totItems-1){
        if (listCount>=3 && listCount < 6)
            createNewList($containerTop);
        else if (listCount >=6)
            createNewList($containerTwo);
        else
            createNewList($container);
        totHt=0;
        listCount++;
    }else{
        totHt += ht;
    }

});

function createNewList ($cont)
{
    $('<ul>').append( $(this).prevAll().andSelf() ).appendTo( $cont );

}

I get this error:

Uncaught Error: NOT_FOUND_ERR: DOM Exception 8

If i replace the if block with this it works fine:

if (listCount>=3 && listCount < 6)
                    $('<ul>').append( $(this).prevAll().andSelf() ).appendTo( $containerTop);
        else if (listCount >=6)
             $('<ul>').append( $(this).prevAll().andSelf() ).appendTo($containerTwo);
                else
             $('<ul>').append( $(this).prevAll().andSelf() ).appendTo($container);
like image 799
Scoota P Avatar asked Jun 12 '26 07:06

Scoota P


1 Answers

Since you are defining your function outside of the .each, it is losing the context. Try using .call to properly set the context to what you expect it to be.

createNewList.call(this,$containerTop)
like image 75
Kevin B Avatar answered Jun 14 '26 21:06

Kevin B



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!