July 17, 2010

Dynamically adding a div element in jquery

Question by Chendur Pandian

I use the following function to show a status message after a form submit from my asp.net page.. The function gets called but it(alertmsg div) doesn’t seem to show up why?

 function topBar(message) {
        var $alertdiv = $('<div id = "alertmsg"/>');
        $alertdiv.text(message);
        alert($alertdiv);
        alert($alertdiv.text(message));
        $alertdiv.click(function() {
            $(this).slideUp(200);
        });
        $(document.body).append($alertdiv);
        setTimeout(function() { $alertdiv.slideUp(200) }, 5000);
    }

What happens is both the alert statements show [Object object]… I think both need to show different outputs… Any suggestion..

css:

#alertmsg
{
  font-family:Arial,Helvetica,sans-serif;
   font-size:135%;
   font-weight:bold;
  overflow: hidden;
  width: 100%;
  text-align: center;
  position: absolute;
  top: 0;
  left: 0;
  background-color: #404a58;
  height: 0;
  color: #FFFFFF;
  font: 20px/40px arial, sans-serif;
  opacity: .9;
}

Answer by Jim Schubert

You’re alerting the jQuery object. Try changing your alert to:
alert($alertdiv.get(0).innerText);

Other than that, your div may not be showing because you’re adding the click event before you add the div element to the page.

Try changing:

$alertdiv.click(function() {
            $(this).slideUp(200);
        });

To:

$alertdiv.bind('click', function() {
            $(this).slideUp(200);
        });

or even:

$alertdiv.live('click', function() {
            $(this).slideUp(200);
        });

I think this may be the only way to bind dynamically generated elements. I’ve never tried .click() outside of the document ready function.

Edit:
In addition to the above suggestion for jQuery, your css should be changed to specify a height for the div. Your height of 0 will cause it to render, technically, and possibly slide up. But, you won’t be able to see it because it is 0 pixels tall at point 0,0.

Answer by Starx

To insert a <div> dynamically you can use this

$('<div>Test</div>').insertAfter('.inner'); //to insert after an element with class inner

or better

$("#myparent").html("<div id='mynewdiv'>hi</div>");
...

Please fill the form - I will response as fast as I can!