John John - 1 month ago 10
jQuery Question

Javascript not following step by step instruction

this is my html



$(function(){
$(".button1").on("click",function(){
$(".img").css("display","block");
$(".bord").append('<div class="test1">11111111</div>');
$(".img").css("display","none");
});
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>

<div class="parent">
<div class="button1">button1</div>
<div class="button2">button2</div>
</div>

<div class="bord">
<img src="http://www.mtlexs.com/images/reload.gif" class="img" style="display: none;">
</div>







Here i write the code , when button1 click show image, then display text, then hide image . But here image is not showing

Then i change the code so show image and display text , and it is working



$(function(){
$(".button1").on("click",function(){
$(".img").css("display","block");
$(".bord").append('<div class="test1">11111111</div>');
});
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<div class="parent">
<div class="button1">button1</div>
<div class="button2">button2</div>
</div>

<div class="bord">
<img src="http://www.mtlexs.com/images/reload.gif" class="img" style="display: none;">
</div>





So what is the problem in my first code ?

I need to
show image->show text-->hide image


Please check .

Answer

You are updating the value of display to quicky. If you add a timeout you will see that the image is actually showing then hidding.

The change are not directly rendered (See @Maximus's answer)

Add a timeout and it will work as you want

$(function() {

  $(".button1").on("click", function() {

    $(".img").css("display", "block");
    $(".bord").append('<div class="test1">11111111</div>');
    setTimeout(
      function() {
            $(".img").css("display", "none");
      }, 2000);
  });

});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>

<div class="parent">
  <div class="button1">button1</div>
  <div class="button2">button2</div>
</div>

<div class="bord">
  <img src="http://www.mtlexs.com/images/reload.gif" class="img" style="display: none;">
</div>