Shniper
Shniper

Reputation: 854

How to automatically hide and show an element with a delay

JSfiddle

I have a button that when clicked creates an h1 input and starts a progress bar. I want the text to dissapear right before the progress bar fills up and appear when it starts filling again every time it fills up. I've tried jquery hide(), remove(), detach() and empty() but can't find a way to make it be able to do what I want.

var auto = 3;
var nb = 0;

var progress = function(sec) {
  var interval = 1000; //milliseconds
  setTimeout(function() {
    sec = sec + 25;
    $('#bar').val(sec);
    if (sec > 100) {
      $('#bar').val(0);
      sec = 0;
      nb++;
    }
    if (nb < auto) 
      progress(sec); //call self with new value
  }, interval)
}

$('#battle').click(function() {
  $('#dam').html("You have hit the " + $('#monsters').val() + " for 5 damage").delay(4500).fadeOut(400);
  progress(0); //initialize progress bar
});

Upvotes: 2

Views: 73

Answers (1)

Try this.

var auto = 3;
var nb = 0;

var progress = function(sec) {
  $('#dam').html("You have hit the " + $('#monsters').val() + " for 5 damage").show().delay(4500).fadeOut(400);
  var interval = 1000; //milliseconds 
  setTimeout(function() {     
    sec = sec + 25;
    $('#bar').val(sec);
    if (sec > 100) {
      $('#bar').val(0);
      sec = 0;
      nb++;
    }
    if (nb < auto) progress(sec); //call self with new value
  }, interval)
}

$('#battle').click(function() {  
  progress(0); //initialize progress bar
});
body {
  background-color: #000;
}

progress {
   appearance: none;
   -webkit-appearance: none;
   width: 100%;
}

progress[value]::-webkit-progress-bar {
  background-color: #000;
  border: 1px solid #81ff14;
  border-radius: 5%;
}

progress[value]::-webkit-progress-value {
  color: #81ff14;
}

select {
  background-color: rgba(0, 0, 0, 0);
  border-color: #81ff14;
  color: #81ff14;
  margin-left: 100px;
  margin-top: 15px;
}

button {
  background-color: rgba(0, 0, 0, 0);
  border-color: #81ff14;
  color: #81ff14;
  border-radius: 10%;
  float: right;
  margin-right: 100px;
  margin-top: 15px;
}

#dam {
  color: #81ff14;
  font-family: sans-serif;
  font-size: 18px;
  max-width: 60%;
  text-align: center;
  float: right;
  margin-top: 40px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<progress max="100" value="0" id="bar"></progress>

<select id="monsters">
  <option>Fly</option>
  <option>Mouse</option>
  <option>Rat</option>
  <option>Rabbid Rabbit</option>
  <option>Baby Ent</option>
  <option>Murloc</option>
  <option>Ent</option>
</select>

<button type="button" id="battle">Battle!</button>

<p id="dam">

</p>

Upvotes: 1

Related Questions