I have a function that is in charge of creating elements dynamically , what I have is the following:
function create_db_container(i) {
var db = document.createElement("div");
var db_icon = document.createElement("i");
var db_label = document.createElement("label");
var options = document.createElement("div");
var delete_db = document.createElement("button");
var edit_db = document.createElement("button");
$(db_icon).html('dns');
$(db_icon).addClass('material-icons db_icon');
$(db_icon).appendTo(db);
//Label - name of the database
$(db_label).html(dbs[i]);
$(db_label).addClass('db_label');
$(db_label).appendTo(db);
//Buttons inside options div
//Drop button
$(delete_db).attr('name',dbs[i]);
$(delete_db).addClass('material-icons db_button_label kill');
$(delete_db).html('close');
$(delete_db).appendTo(options);
//Edit button
$(edit_db).attr('name',dbs[i]);
$(edit_db).addClass('material-icons db_button_label edit');
$(edit_db).html('mode_edit');
$(edit_db).appendTo(options);
$(options).addClass("options");
$(options).appendTo(db);
$(db).attr('id',dbs[i]);
$(db).addClass('database_container');
$(db).appendTo("#databases");
/*
Aquí he probado a usar
$(db).appendTo("#databases").fadeIn(500);
*/
}
for (var i=0; i < dbs.length; i++) {
if (dbs.length == 1 && dbs[0] == "") {break;}
create_db_container(i);
}
As you can see in the comment inside the script, what I intend is that every time the element is added db
to #databases
do an effect like fadeIn
.
I would appreciate any possible help
First hide it because when you add it it will be visible by default. After hiding it very fast (0ms) you show it again with a longer time:
Also, preferably don't use a loop to add dynamic content as the execution of a loop will not wait for a function call to finish, instead it will continue its execution, which can lead to undesirable effects. Instead of a for use a recursive function:
Example
To call the function again, it
create_db_container
first waits for the animation to finish to get a "reveal" type effect, this is done through a callback tofadeIn
, which jQuery will execute once the animation has completed.It's not really a JavaScript issue but a style issue. When you create the ones
div
with class "database_container", by default they are visible, so doingfadeIn
nothing happens (they are already visible, there is really nothing to do).For it to work
fadeIn
you must make itdiv.database_container
hidden by default (usingdisplay:none
CSS) and you will see the effect: