3

How can I sort the list without realoading the iframe inside the li? (appendChild makes the iframe reload)

<script>
window.onload = function () {
    var my_ul = document.getElementById('my_ul'),
        my_button = document.getElementById('my_button');

    function sort_function() {
        for(var i = 0; i < 5; i++) {
            var list = [1, 2, 3, 4, 5];
            my_ul.appendChild(document.querySelector('[data-sort="' + list[i] + '"]'));
        }
    }

    my_button.onclick = function () {
        sort_function();
    }

}
</script>

<a id=my_button href="#">Sort</a>
<ul id=my_ul>
    <li data-sort=3>3<iframe src="#3"></iframe>
    <li data-sort=2>2<iframe src="#2"></iframe>
    <li data-sort=4>4<iframe src="#4"></iframe>
    <li data-sort=1>1<iframe src="#1"></iframe>
    <li data-sort=5>5<iframe src="#5"></iframe>
</ul>
MaxArt
  • 22,200
  • 10
  • 82
  • 81
user1087110
  • 3,633
  • 11
  • 34
  • 43
  • Check this http://stackoverflow.com/questions/7434230/how-to-prevent-an-iframe-from-reloading-when-moving-it-in-the-dom – Sanghyun Lee May 02 '13 at 08:53

1 Answers1

0

If you move an object in the DOM, it will get removed and re-appended. The result is that the contents of the iframe will be reloaded.

I don't know what you're showing in those iframes, but maybe you can get rid of them and load the content dynamically using AJAX (f.e. jQuery.get()).

If you really want to use iframe and you really want to avoid reloading them, I think the only way is to make the li elements floating and to reposition them dynamically.

I've created a jsFiddle that demonstrates this. The code uses jQuery.

HTML

Close the li tags

<a id="my_button" href="#">Sort</a>
<ul id="my_ul">
    <li data-sort=3>3<iframe src="#3"></iframe></li>
    <li data-sort=2>2<iframe src="#2"></iframe></li>
    <li data-sort=4>4<iframe src="#4"></iframe></li>
    <li data-sort=1>1<iframe src="#1"></iframe></li>
    <li data-sort=5>5<iframe src="#5"></iframe></li>
</ul>

CSS

Use absolute positioning for li elements

#my_ul li {
   position: absolute;
   display: block;
}

Javascript

var iframeTop = 0;

// Initial positioning at document load
$(function() {
    var ofsTop = $("#my_ul li:first-child").position().top;
    $("#my_ul li").each(function(index, value) {
        $(value).css({ top: ofsTop + 'px'});
        ofsTop += $(value).height();
    });
});

// Re-position when user clicks #my_button
$("#my_button").click(function() {
    // sort li depending on data-sort
    var sorted = $("#my_ul li").sort(function(a, b) {
        return $(a).data("sort") - $(b).data("sort");
    });
    // re-position li's
    if (!iframeTop) iframeTop = $("#my_ul li:first-child").position().top;
    var ofsTop = iframeTop;
    $.each(sorted, function(index, value) {
        $(value).css({ top: ofsTop + 'px'});
        ofsTop += $(value).height();
    });
});
huysentruitw
  • 27,376
  • 9
  • 90
  • 133