简体   繁体   中英

Hook elements with insertAfter, but stay in parent - jQuery

I'm using jQuery to change certain elements' position dynamically. I found something that works here: https://stackoverflow.com/a/18593267/1419575 , but if the index number is higher than the children count, the element goes out of the parent.

Is there a way to make the child stay inside the parent element?

CSS

#hook-header {
    background: #dadada;
    margin: 10px;
    padding: 10px;
}

HTML

<header id="hook-header">
    <div id="ImTheFirstElement"><h1>This is the header hook</h1></div>
</header>

<div id="example-one">01</div>
<div id="example-nintynine">99</div>

jQuery

$(document).ready(function () {
    $('#example-one').appendTo('#hook-header');

    $.fn.appendToIndex=function(to,index){
        if(! to instanceof jQuery){
            to=$(to);
        };
        if(index===0){
            $(this).prependTo(to)
        }else{
            $(this).insertAfter(to.children().eq(index-1));
        }
    };
    $('#ImTheFirstElement').appendToIndex($('#hook-header'),0) 
    $('#example-one').appendToIndex($('#hook-header'),1)  
    $('#example-nintynine').appendToIndex($('#hook-header'),99)
});

DEMO

Modify the plugin to use the last element if eq(index) doesn't return an element

$(document).ready(function () {
    $('#example-one').appendTo('#hook-header');

    $.fn.appendToIndex=function(to,index){
        if(! to instanceof jQuery){
            to=$(to);
        };
        if(index===0){
            $(this).prependTo(to)
        }else{
            var el = to.children().eq(index-1);
            el = el.length ? el : to.children().last();
            $(this).insertAfter(el);
        }
    };
    $('#ImTheFirstElement').appendToIndex($('#hook-header'),0) 
    $('#example-one').appendToIndex($('#hook-header'),1)  
    $('#example-nintynine').appendToIndex($('#hook-header'),99)
});

FIDDLE

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM