Search code examples
javascripthtmlfadeincreateelement

How do I add fade on document.createElement?


I am unsure of how to add a fade effect to the object created with document.createElement. I have tried different methods with no result.

I am fairly new to JavaScript and could use some help. Does anyone have any solution for this?

Thanks in advance!

HTML

<fieldset>
<p id="drinkNameHeadline"> Drink Name </p>                          
<label for='drinkName'></label>
<input id="drinkName" type="name" name="drinkName">
<p id="ingredients"> Ingredients </p>

<label for='ingredient'></label>
<input id="textBar" type="name" name="ingredient">

<div id="textBarPosition"></div>
<input id="addBar" type="button" value="Add Ingredient Bar">    

<input class="submit" type="submit" value="Submit">                     
</fieldset> 

JavaScript

function createSector() {
  var input = document.createElement('input'); input.setAttribute("id", 'textBar');
  input.type = 'text';
  input.name = 'name[]';
  return input;
}

var form = document.getElementById('textBarPosition');
document.getElementById('addBar').addEventListener('click', function(e) {
  form.appendChild(createSector());
});

Solution

  • To achieve a fade in effect, you have to add the element as child in 3 steps :

    1. Set the opacity of your element to 0
    2. Append it to the parent
    3. do the animation of the opacity from 0 to 1 (the fade in effect)

    In your code, something like that:

    document.getElementById('addBar').addEventListener('click', function(e) {
        // step 1: create element and set opacity to 0.
        var selector = createSelector();
        selector.style.opacity = 0; // be careful this is not working in IE before 9.
    
       // step 2: append it to its parent.
        form.appendChild(selector);
    
        // step 3: fade in (we choose to do 20 steps in 1 second to go from 0 to 1. Steps are 50ms each)
        var steps = 0;
        var timer = setInterval(function() {
            steps++;
            selector.style.opacity = 0.05 * steps;
            if(steps >= 20) {
                clearInterval(timer);
                timer = undefined;
            }
        }, 50);
    });
    

    If this code should work in IE 7 or 8 you have to add this line each time you set opacity:

    element.style.filter = "alpha(opacity=0)"; // for step 1
    ...
    element.style.filter = "alpha(opacity=" + (5 * steps) + ")"; // for step 3
    

    If you use jQuery your code can be simpler to write and you don't have to worry about IE compatibility for the opacity :

    document.getElementById('addBar').addEventListener('click', function(e) {
        // step 1: create element and set opacity to 0.
        var selector = $(createSelector());
        selector.css("opacity", 0);
    
       // step 2: append it to its parent.
        $(form).append(selector);
    
        // step 3: fade in
        selector.fadeIn();
    });