Sliding and Fading Elements in and out of View - J Query

We want to reveal or toggle a block of content into view. This can be triggered by the user clicking some element or can be fired by some other event.Rather than just showing and hiding, which could be jarring visually, we want to create a gradual effect to reveal the content into view.For these solutions, I’ve assumed we want to allow the user to toggle the effect.


For reference, if we were just to show the element, our code would be as follows:

If we were to toggle the box but just toggle from visible and hidden, we would use the following instead of .show():

However, our solution wants to be a little more visually engaging than just toggling the display property. So, let’s look at using the slide and fade methods:



Because there’s no opacity toggle function, either we can use a combination of fade In and fadeOut:

or we can create our own fade toggle animation, using the fade To method:

However, I’m of the opinion that it reads better for future maintenance if we use the animate method:


If we want to toggle the height and opacity together, we can reuse the previous solution and add the height to toggle at the same time. This would cause the box to
fade out and slide up at the same time:


As we can see from the previous solutions, the slide and fade methods are the next step up from the straight show (and hide) and toggle methods. The slide methods come in the following flavors:

  • slideUp

  • slideDown

  • slideToggle

The fade methods don’t have an explicit toggle feature, but it can be achieved. Fading has the following methods:

  • fadeIn

  • fadeOut

  • fadeTo

With the exception of fade To, all these methods take speed as the first parameter and a callback function as the second—both of which are optional. The callback function is executed once the animation is complete, and the context is set to the element the animation ran against; i.e., the this variable is the current element.
The reason I would choose to use animate over fade To to toggle opacity is that the
fade To parameters read the wrong way around. If a new developer were coming to the code, using the animate function almost reads as plain English, therefore making it easier to skim and understand what is happening in the code.
It’s worth also adding that if you use the show (or hide) method using a speed, it will animate the height, width, opacity, margin, and padding all in one animation, as shown in

Passing a speed in to the show method animates height, width, padding, margin, and opacity Sliding

Figure :(Passing a speed in to the show method animates height, width, padding, margin, and opacity Sliding)

All rights reserved © 2018 Wisdom IT Services India Pvt. Ltd Protection Status

J Query Topics