How to Fade and Slide Elements in and out of View in jQuery

In this article, I’m going to toggle or reveal a block of content into view with jQuery. We can trigger the function by just clicking on some element or by any event trigger. For explaining the concept I’m going to use the following code structure:

 

[code type=”php”]
<html>
<head>

<script type=”text/javascript” src=”http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js”></script>
</head>

<body>

<button id=”submit”>Click Now</button>

<p style=” display:none;”>This is the text you will like. This is the text you will like. This is the text you will like. This is the text you will like. This is the text you will like. This is the text you will like. This is the text you will like. This is the text you will like.
</p>

</body>

</html>
[/code]

Toggling

By default, I set the <p> tag to display none. So if we want to show the <p> after clicking on the button we will put the jQuery in the <head> section something like this.

[code type=”php”]
<script type=”text/javascript”>

$(document).ready(function() {

$(“#submit”).click(function() {

$(“.show_hide”).toggle();

});

});

</script>
[/code]

But what if you want to view the content with a slide view. We can use slideToggle for this. For example:

[code type=”php”]
<script type=”text/javascript”>

$(document).ready(function() {

$(“#submit”).click(function() {

$(“.show_hide”).slideToggle(‘slow’);

});

});

</script>
[/code]

Above code will generate the code with slide view after putting it in the <head> section.

Fading:

We can also use jQuery’s fade effects for showing up the text. For example, we can use something like this:

[code type=”php”]
<script type=”text/javascript”>

$(document).ready(function() {

$(“#submit”).click(function() {

var $get_the_element = $(“.show_hide”);

if($get_the_element.is(‘:visible’)) {

$get_the_element.fadeOut(‘slow’);

} else {

$get_the_element.fadeIn(‘slow’);

}

});

});

</script>
[/code]

What above will code, when you will click on button it will check the visibility of the <p> element. If <p> will be visible it will fade out the text, otherwise it will fade in the text.

Duan Lingxin

Duan Lingxin

Content crafter and chief editor at Scratching Info. Also regular contributor on other major online tech platforms. Security Specialist by day and a writer by night, he does his best to instill his knowledge about tech while delivering inspiring and life changing resources through his writing,

More Posts - Website

Leave a Comment