To use this website fully, you first need to accept the use of cookies. By agreeing to the use of cookies you consent to the use of functional cookies. For more information read this page.

jQuery element display4.1

One of the most important things jQuery can do is animation and controlling style (CSS) properties of elements. As such, jQuery has the ability to make elements visible or invisible, that is, control their CSS display properties.

There are four different methods that make it easy to control the display properties of an element:

  • hide
  • show
  • fadeOut
  • fadeIn

This demo will be affected whenever the code is run on any of the samples following:

Display

The jQuery hide method will add the CSS display : none property and value set to an element.

JavaScript
jQuery("#main_image_display").hide();
		

The jQuery show method will simply remove the CSS display : none property and value set from an element.

JavaScript
jQuery("#main_image_display").show();
		

Fade

The jQuery fadeOut method is slightly more advanced. What this method does is animates the opacity property of the element from 1 to 0, ensuring it becomes completely transparent. When it reaches 0, the element is then given the property and value pair display : none.

The following example delays the effect so that it can be observed above when run, but it does not need to be in any time out as shown below for it to function:

JavaScript
setTimeout(function(){
  jQuery("#main_image_display").fadeOut();
}, 4000);
		

Much like the fadeOut method, the fadeIn method works with the opacity property of the element, but it takes the opacity from 0 to 1 as opposed to taking it from 1 to 0. It also removes the display : none property and value pair from the element when the element becomes completely opaque.

As before, to ensure that the effect is observable it is within a timeout.

JavaScript
setTimeout(function(){
  jQuery("#main_image_display").fadeIn();
}, 4000);
		

Both the fadeOut and fadeIn methods also can take parameters to change how long they take to complete and what to do after the animation finishes.

The first parameter decides how long the animation should take, whereas the second parameter, which should be a function handle, decides what to do after the animation has finished.

JavaScript
setTimeout(function(){
  jQuery("#main_image_display").fadeOut(10000, function(){
    alert("Fade out complete");
  });
  jQuery("#main_image_display").fadeIn(10000, function(){
    alert("Fade in complete");
  });
}, 4000);
		

Write the code that will make the image shown disappear over 10 seconds. Once the image has disappeared, make it reappear instantly. The image has the ID attribute with a value theimage.

Petro
Feedback 👍
Comments are sent via email to me.