Search code examples
javascriptappendfadein

Append HTML but have separate fadeIn on document click


I am appending a div every time the user clicks anywhere on the page. I want the div's to fadeIn but the way I first did this each div that was appended had the same ID. This is a problem if I want each letter div to fadeIn separately. So I tried to use a count to make each div I append have a separate name but this hasn't work. Each time a new div is appended all appended divs fadeIn not just the one just recently added. How might I change this?

var count = 0;
if(firstLetter != "") {

    count++;

    //Create a new circle letter by inserting new div class
    $("p").append('<div class="circle' + count +'" style="border-radius: 50%;width:    36px;height:36px;padding:8px;background:#FF7D5C;color:black;text-align:center;font:32px Arial, sans-serif;display:inline-block;margin-right:4px;margin-bottom:4px;">' + firstLetter.toUpperCase() + '</div>').hide().fadeIn('slow');
}

Many Thanks :)


Solution

  • Try this. In your code all the divs play the effect because the element returned by all the functions that you're calling is the < p > element.

    $("p").append('<div class="circle' + count +'" style="border-radius: 50%;width:    36px;height:36px;padding:8px;background:#FF7D5C;color:black;text-align:center;font:32px Arial, sans-serif;display:inline-block;margin-right:4px;margin-bottom:4px;">' + firstLetter.toUpperCase() + '</div>');
    
    $("p").children().last().hide().fadeIn();
    

    OR a simpler way

    $("p div:last").hide().fadeIn();