Abdur Rahman
Abdur Rahman

Reputation: 39

how can I append dynamic div using jquery?

I want to create some dynamic div on each click of a button. If there is already such div at the top, the next such div will show below all of them but if there is none, this new div will start from top.

Also, after five seconds of adding, each div should vanish itself and all divs below this vanishing div should come upwards?

Here is my code:

 $("body").append("<div style='position:
 absolute;top:0;right:0'     
 class='dynamic alert-danger'>something wrong!!!!</div>");
setTimeout(function() {
 $('.dynamic').fadeOut('fast');
 }, 5000);

Upvotes: 0

Views: 142

Answers (1)

Mohit Bhardwaj
Mohit Bhardwaj

Reputation: 10083

var bubbleCounter = 0;
$("#add-bubble").on("click", function(e){
  e.preventDefault();
  var counter = bubbleCounter + 1;
  var htmlString = '<div class="bubbles" id="bubble-'+counter+'">'+counter+'</div>';
  $("#bubbles-container").append( htmlString );
  setTimeout(function(){
    $("#bubble-"+counter).remove();
  }, 3000 );
  bubbleCounter = counter;
});//#add-bubble click()
body{
  position: relative;
}
#bubbles-container{
  position: absolute;
  top: 0;
  right: 0;
  width: 100px;
}
#bubbles-container .bubbles{
  color: #fff;
  width: 100px;
  height: 100px;
  border-radius: 50%;
  background-color: orange;
  line-height: 100px;
  text-align: center;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<div id="bubbles-container"></div>
<button id="add-bubble">Add bubble</button>

Upvotes: 1

Related Questions