BillyBelly
BillyBelly

Reputation: 523

multiple dom updates in the same function

I have a JavaScript function that takes some time to get executed, from the start to the end of the instructions contained inside. During the execution I would like to display a div element, then after the execution I would like to hide it. I wrote this simple code snippet but doesn't work:

<div style="height: 100px; width: 100px; background-color: red; display: none;" id="d"></div>

<script>

    document.getElementById('d').style.display='block';
    console.log('start');

    xmlhttp=new XMLHttpRequest();
    xmlhttp.open("POST","http://www.google.com",false);
    xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");

    try{
        xmlhttp.send();
    } catch (e) {

    }

    var response = xmlhttp.responseText

    document.getElementById('d').style.display='none';
    console.log('finish');
</script>

If you look at the console, you see tat there is an interval between the "start" and the "finish" statement, but the div stays hidden! How is this possible and how to fix it?

Upvotes: 0

Views: 99

Answers (1)

Deepak
Deepak

Reputation: 51

If you want to make your life simple with jQuery(http://jquery.com/) Do the following: 1. Include jQuery to your page 2. Do the following:

<div style="height: 100px; width: 100px; background-color: red; display: none;" id="d"></div>
<script>
    $("#d").show();
    $.ajax({
        type:'POST',
        url:'http://www.google.com',

        success: function(data) {
        //code on successful response
        },
        error: function(xhr) {
        // code on error response
        },
        complete:function(){
         // code on  - success/failure
         $("#d").hide();
        }
    });
</script>

Enjoy

Upvotes: 1

Related Questions