sahana sahana - 4 months ago 26
CSS Question

Making a div flash just once

I want to make my div flash or highlight just once on a particular click event. I tried the following code

function blink() {
var f = document.getElementById('divId');
setInterval(function() {
f.style.display = (f.style.display == 'none' ? '' : 'none');
}, 500);
}


But I keeps blinking. I want to use just JavaScript.
Any leads?

Answer

Understand the use of the two timer functions in JavaScript:

  • setTimeout - Do once after a specified time.
  • setInterval - Do infinite times every specified time.

Simply replace setTimeout with setInterval:

function blink() {
   var f = document.getElementById('divId');
   setTimeout(function() {
      f.style.display = (f.style.display == 'none' ? '' : 'none');
   }, 500);
}

Or, if you wanna make it really blink, do this, as the above one just flips it once, and you need to do it twice:

function blink() {
   var f = document.getElementById('divId');
   setTimeout(function() {
      f.style.display = (f.style.display == 'none' ? '' : 'none');
   }, 500);
   setTimeout(function() {
      f.style.display = (f.style.display == 'none' ? '' : 'none');
   }, 1000);
}

If not twice, use it nested:

function blink() {
   var f = document.getElementById('divId');
   setTimeout(function() {
      f.style.display = (f.style.display == 'none' ? '' : 'none');
       setTimeout(function() {
          f.style.display = (f.style.display == 'none' ? '' : 'none');
       }, 500);
   }, 500);
}

See the timing functions and seconds for both the functions.


Update

Looks like the OP wants an Yellow Fade Effect once the page is loaded:

$(function () {
  $("#fade-it").delay(150).animate({
    "background-color": "#fc9"
  }, 350, function () {
    $("#fade-it").animate({
      "background-color": "#fff"
    }, 200);
  });
});
* {font-family: 'Segoe UI', sans-serif; margin: 0; padding: 0; list-style: none;}
#fade-it {padding: 15px; text-align: center;}
<script src="http://code.jquery.com/jquery-2.2.4.min.js"></script>
<script src="http://code.jquery.com/ui/1.12.0/jquery-ui.min.js"></script>
<div id="fade-it">
  Welcome!
</div>

Note: I have used jQuery and jQuery UI for this, we can also perform in pure CSS.


Update: Using pure CSS animation.

* {
  font-family: 'Segoe UI', sans-serif;
  margin: 0;
  padding: 0;
  list-style: none;
}
#fade-it {
  padding: 15px;
  text-align: center;
}
@-webkit-keyframes yellow-fade {
  from {
    background: #f96;
  }
  to {
    background: #fff;
  }
}
@-moz-keyframes yellow-fade {
  from {
    background: #f96;
  }
  to {
    background: #fff;
  }
}
@keyframes yellow-fade {
  from {
    background: #f96;
  }
  to {
    background: #fff;
  }
}
#fade-it {
  -webkit-animation: yellow-fade 1s ease-in-out 0s;
  -moz-animation: yellow-fade 1s ease-in-out 0s;
  -o-animation: yellow-fade 1s ease-in-out 0s;
  animation: yellow-fade 1s ease-in-out 0s;
}
<div id="fade-it">
  Welcome!
</div>

Comments