Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Capture the event after a section element has finished loading

I have a div that contains sections:

<div class="Placeafterthis">
</div>
...
<div class="k-content">
<section class="rbs-section" id="id1" name="">
.. // section content
</section>
<section class="rbs-section" id="id2" name="">
.. // section content
</section>
<section class="rbs-section" id="id3" name="">
.. // section content
</section>
</div>

Now basically these sections are loaded when the DOM is ready. Is there a way I could check when a particular section has finished loading? Once its finished loading I need to clone that section and place it just after the "Placeafterthis" div. Any suggestions on how I can achieve this?

like image 472
Neophile Avatar asked Sep 04 '15 10:09

Neophile


People also ask

What event do you use to perform something after the page has finished loading?

The onload event occurs when an object has been loaded. onload is most often used within the <body> element to execute a script once a web page has completely loaded all content (including images, script files, CSS files, etc.).

How do you check if page is loaded completely?

You can check the document. readyState property. From MDN: Returns "loading" while the document is loading, "interactive" once it is finished parsing but still loading sub-resources, and "complete" once it has loaded.

How do you make JavaScript wait until the page is loaded?

Use the window. onload Event to Wait for the Page to Load in JavaScript.


2 Answers

You can use a MutationObserver to detect when nodes are added to .k-content, clone them using jQuery, and append them after .Placeafterthis (demo):

var kContent = $('.k-content'); // the original container in which the items will be placed
var $Placeafterthis = $('.Placeafterthis'); // the cloned elements target marker placeholder

function mutationHandler(mutation) { // the mutation handler will deal with the addition of new nodes to the original container
    var addedNodes = mutation.addedNodes;

    if (!addedNodes.length) { // if no added nodes return
        return;
    }

    $.each(addedNodes, function () { // iterate the add nodes
        var $element = $(this);

        if (!$element.hasClass('rbs-section')) { // if the node doesn't have the right class continue to the next one
            return true;
        }

        var $prevSections = $Placeafterthis.find('~ .rbs-section'); // find if there are already sections append to the target
        var $target = $prevSections.length === 0 ? $Placeafterthis : $prevSections.last(); // if there are sections take the last, if not use the marker

        /** note that using .clone(true) will also clone all jQuery event handlers and data from the original element. If you don't need this behavior, just use .clone() **/

        $target.after($element.clone(true)); // append after the target
    });
}

var observer = new MutationObserver(function (mutations) { // create a new mutation observer
    mutations.forEach(mutationHandler);
});

var config = { // config should include only childList because we just want added nodes 
    childList: true
};

observer.observe(kContent.get(0), config); // watch the original container with the observer
like image 118
Ori Drori Avatar answered Sep 30 '22 04:09

Ori Drori


Try utilizing $.get() , appending response to .k-content , filtering id of selected section element at response to clone , add character to id to prevent duplicate id's in DOM , insert after .Placeafterthis ; define getSections set with jQuery promise object as this , recursively call getSections to return Array.prototype.shift() on sections array to return $.get() for each item at index 0 in order, else if false returned by !! operator on section[0] return this.promise()

    // `id`s of `section` elements to append to `.k-content`
    var sections = ["#id1", "#id2", "#id3"];
    // selected `id` to do stuff with
    var selected = sections[1];
    // container
    var container = $(".k-content");
    // `complete` handler for `$.get()` requests
    function selectedId(html, textStatus, jqxhr) {
        // decode `data` : `id` sent with request
        var id = decodeURIComponent(this.url.split("?")[1]).split("=")[1];
        // append `section` to `container`
        container.append($(html).filter(id));
        // if `selected` appended to `container` ,
        // and `selected` is not in `DOM` directly after `.Placeafterthis` element
        // clone `selected` , append after `.Placeafterthis` element
        if (container.find(selected).is("*") 
          && !$(".Placeafterthis + " + selected + "-a").is("*")) {
            var clone = $(selected, container).clone()
                        .attr("id", selected.slice(1) + "-a");
            $(".Placeafterthis").after(clone)
        }
    }

    var getSections = function getSections() {
        var p = sections.shift();
        return !!sections 
               && $.get("http://fiddle.jshell.net/guest271314/rvt8evoy/show/"
               , {"id": p}, selectedId).then(getSections)
    };

    getSections()
    .then(function() {
      console.log("complete")
    })

jsfiddle http://jsfiddle.net/1d6vmdpt/5/

like image 33
guest271314 Avatar answered Sep 30 '22 04:09

guest271314