Lahib
Lahib

Reputation: 1365

Run javascript after element is added to body

I have a <div> element that does not appear on the page unless some function is activated. I want to remove this <div> after it appears on the page.

how do I run my JavaScript code when and only when this <div> element is added ?

I am new at this and would appreciate some help. Thanks.

ps. element is generated by jquery and only has classname.

Detailed explanation:

I implementing a excel export in an existing web application.
I am using a form surrounding filters for search and a ajaxgrid gridstate. This form is submitted to a controller that has the corresponding viewmodels.

My code for submitting the form is this:

$(function () {
    $('div.btn-group #export-citizen-list').on('click', function () {
        var gridstate = $('#citizenIndexGrid').ajaxgrid('getState');
        var form = $('#create-citizen-csv-file');

        // add ajaxgrid state to post data
        $.each(gridstate, function (k, v) {
            form.addAjaxgridHidden(k, v);
        });

        // submit entire form, with ajaxgrid state
        form.submit();

        // remove all hiddenfields that belongs to ajaxgrid
        form.find(":hidden.ajaxgrid").remove();
        document.getElementById("filterSearch").className = "default ui-button ui-widget ui-state-default ui-corner-all";
        $('#filterSearch').removeAttr('disabled');
// function that removes unwanted <div> ---->$('.ajaxWorkingNotification').slideUp();
    })

    jQuery.fn.addAjaxgridHidden = function (name, value) {
        return this.each(function () {
            var input = $('<input>').attr('type', 'hidden').attr('name', name).attr('class', 'ajaxgrid').val(value);
            $(this).append($(input));
        });
    };
});

When I submit my form the excel is downloaded and the unwanted <div> is inserted in the DOM. The thing is that I don't know when the postback is returned in this case. And therefore I don't know when this <div> is inserted.

Hope this clarifies my issue.

Upvotes: 3

Views: 2844

Answers (2)

RyanB
RyanB

Reputation: 1297

You can do it by implement a listener on DOM node insertion event.

There was an explanation here on how to detect DOM node insertion & pure javascript code to demonstrate how it works

And if you like a jQuery version, then here is the sample code that I translated from above link.

HTML:

<input type="button" id="addme" value="Add"/>
<div id="container">
</div>

CSS:

@keyframes nodeInserted {  
    from { opacity: 0.99; }
    to { opacity: 1; }  
}

#container div#mydiv {
    animation-duration: 0.001s;
    animation-name: nodeInserted;
}

Javascript:

$(function () {
    $('#addme').click(function () {
    var div = $('<div/>').attr('id', 'mydiv').html("Hello");
    $('#container').append(div);
  });

  var handler = function (e) {
    if (e.originalEvent.animationName == "nodeInserted")
        alert("An HTMLElement has been inserted to DOM tree !")
  };

  var eventSignature = 'MSAnimationStart';
  if ($.browser.webkit) eventSignature = 'webkitAnimationStart';
  if ($.browser.mozilla) eventSignature = 'animationstart';
  $(document).on(eventSignature, handler);
});

JSFiddle Demo

Upvotes: 2

narendranathjoshi
narendranathjoshi

Reputation: 3096

You can do something like this.

// Assuming your element is created by this line ...
$(".your_elements_class_name").ready(function() {
    // write code here
    // this is executed after the element is created and added to DOM
})

Upvotes: 2

Related Questions