Fade In and Fade Out with jQuery

To animate elements with a gradual fade in or out effect with jQuery use either the fadeIn() or fadeOut() methods.

 

Fade an Element Out

Let's create a button that when clicked will fade out after 0.4 seconds, which is the default behaviour of fadeOut().

 

<button type="button" id="foo">Click me</button>
$('#foo').click(function() {
  $(this).fadeOut();
});

 

To set a custom fade duration, pass it as the first argument of the method. The value is in milliseconds, so a value of 1000 would be one second.

 

<button type="button" id="foo">Click me</button>
$('#foo').click(function() {
  $(this).fadeOut(2000);
});

 

Fade an Element In

Let's create a fade-in effect on an element of 0.4 seconds, which is the default behaviour of fadeIn().

 

<div id="hidden" style="display: none;">Hello</div>

<button type="button" id="foo">Click me</button>
$('#foo').click(function() {
  $('#hidden').fadeIn();
});

 

To set a custom fade-in effect, pass milliseconds as the first argument of the function:

 

<div id="hidden" style="display: none;">Hello</div>

<button type="button" id="foo">Click me</button>
$('#foo').click(function() {
  $('#hidden').fadeIn(1000);
});

 

Fade in/out on Complete

Both the fadeIn() and fadeOut() methods accept a second function parameter that is called when the fade operation is complete. Let's create a fade-out on complete function that will show an alert. In a real-world scenario, you will probably be doing something more useful.

 

<div id="hidden" style="display: none;">Hello</div>

<button type="button" id="foo">Click me</button>
$('#foo').click(function() {
  $('#hidden').fadeIn(2000, () => {
     alert('Complete!');
  });
});
jquery

Related Tutorials

 thumbnail

The HTML <del> Tag

December 30, 2020