• Geek Answers Handbook

    Can I use jQuery to easily move li elements up or down?

    I have the following menu:

        <ul id="menu" class="undecorated"> 
            <li id="menuHome"><a href="/">Home</a> </li> 
            <li id="menuAbout"><a href="/Usergroup/About">About</a> </li> 
            <li id="menuArchives"><a href="/Usergroup/Archives">Archives</a> </li> 
            <li id="menuLinks"><a href="/Usergroup/Links">Links</a> </li> 
        </ul> 
    

    Is there an easy way to use jquery to reorder items? I imagine something like this:

    $('#menuAbout').moveDown().moveDown()
    

    But any other way to achieve this is appreciated.

    +5
    javascript jquery dom
    George mauer Sep 28 '09 at 2:26
    source share
    2 answers

    This is actually not so difficult. JQuery almost gets you there using the "insertBefore" and "insertAfter" methods.

    function moveUp($item) {
        $before = $item.prev();
        $item.insertBefore($before);
    }
    
    function moveDown($item) {
        $after = $item.next();
        $item.insertAfter($after);
    }
    

    You can use them as MoveDown ($ ('# menuAbout')); and the menuAbout element will move down.

    If you want to extend jQuery to include these methods, you should write it like this:

    $.fn.moveUp = function() {
        before = $(this).prev();
        $(this).insertBefore(before);
    }
    
    $.fn.moveDown = function() {
        after = $(this).next();
        $(this).insertAfter(after);
    }
    

    ,   $ ( "# MenuAbout" ) MoveDown();.

    +22
    villecoder 28 . '09 2:43

    , :

    $.fn.moveDown = function() {
        return this.each(function() {
            var next = $(this).next();
            if ( next.length ) {
                $(next).after(this);
            } else {
              $(this).parent().append( this );
            }
        })
    }
    
    $('#menuAbout').moveDown().moveDown()
    

    jQuery.prototype.after

    +5
    meder omuraliev 28 . '09 2:31

    More articles:

    • The default Xcode editor is (void) instead of - (voidPtr)? - objective-c
    • C ++ Syntax: if var! = Type int - c ++
    • Сохранение паролей внутри приложения - c++
    • При тестировании модулей вам нужно использовать базу данных для проверки операций CRUD? - unit-testing
    • Can you trust mono as a startup platform? - c #
    • Eval Within Block Instance - ruby ​​| fooobar.com
    • How can I verify that all my init functions have been called? - c
    • The operation completed using WebClient.DownloadFile and fixed the URL - c #
    • Scope and ways to narrow it using VB.Net - scope
    • Is frequent demotion in the class hierarchy always evil? - oop

    All Articles

    Geek Answers | 2019