Search code examples
javascriptjquerychaining

Carry out function after append


Seems to be discussed a lot but can't find an easy answer. I want to ensure a function is carried out after I added a loader icon to the DOM but understand append doesn't support this. Are there any easy solutions?

Current code:

$('#tab').on('shown.bs.tab', function(e) {
    $("#htmlelement").append('<i class="fa fa-spinner fa-spin fa-fw"></i>');
    functionafterappend();
});

Solution

  • .append is a synchronous function. Therefore, this solution is valid and your functionafterappend() will execute only after append is executed.

    For instance, look at the following example where I'm triggering an alert 3 secs after the append is done

    $('div')
        .append(`<p>1. Append at ${console.log(new Date())}</p>`)
    $('span')
        .append(`<span> 2. Another Append at ${console.log(new Date())}</span>`);
        
        // setTimeout(() => alert("Append has been completed"), 3000);
       
    body {
      padding:50px;   
    }
    
    div {
      border:2px solid #bbb;
      background-color:#eee;
      padding:10px;
      margin:10px auto;
    }
    
    span {
      display:block;
      width:65px;
      font:bold 12px Arial,Sans-Serif;
      color:white;
      padding:5px 10px;
      background-color:black;    
    }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <div>Lorem ipsum dolor sit amet consectetur adipiscing elitr sed diam nonumy tempe goreng.</div>

    It's the simplest way to do something after an append. Except of course, if you wanna chain functions like so:

    .append('<span>1. Append</span>') .prepend('<span>1. Append</span>')

    If you want to go completely functional, you can even do function composition like so using Lodash:

    const newFunc = pipe(append, prepend);