onclick button show and hide div using JQuery

Hi friends, Today we will learn how can you show and hide div on click button using JQuery.
most of the website use Jquery because with jquery we can make our website more attractive and dynamic.

We can do this by CSS also.

So let's start.

Jquery Hide and Show onclick Button 

Note - make sure you include the jquery library inside the head section 

<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
</head>

Example  1 -  Simple Hide and show Button.

  • Create a div tag 
  • Add attribute id 
  • Write some content inside a div tag
  • Create a Button for hiding and showing your content
  • For showing the content Add a class in your input button 
  • For hiding the content Add a class in your input button

<div id="div_content">

  

 hi, welcome to shot tutorials.


</div>


<input type = "button" class ="show" value="show">

<input type = "button" class ="hide" value="hide">

  • Now we will write some code for hiding and show.
Jquery:-

<script>


$(document).ready(function(){

 

// For Show 


$(".show").on("click", function(){

  

   $("#div_content").show();


});


// For hide


$(".hide").on("click", function(){

  

   $("#div_content").hide();


});


});


</script>


Output - 


Example  2 -  By CSS

  • Create a div tag 
  • Add attribute id 
  • Write some content inside a div tag
  • Create a Button for hiding and showing your content
  • For showing the content Add a class in your input button 
  • For hiding the content Add a class in your input button
  • Write CSS for a hide and show.
  • By default, the content  will be show     (you can do according to your requirements )
  • Write some code for hiding and show

<div id="div_content">

  

 hi, welcome to shot tutorials.


</div>


<input type = "button" class ="show" value="show">

<input type = "button" class ="hide" value="hide">


CSS :

<style>

.div_content_show{       

  display:block;

 }                       

              

.div_content_hide{       

   display:none;       

 }                        

</style> 


JQuery:

<script>


$(document).ready(function(){

 

// For Show 


$(".show").on("click", function(){

  

    $("#div_content").removeClass("div_content_hide");

   $("#div_content").addClass("div_content_show");


});


// For hide


$(".hide").on("click", function(){


   $("#div_content").removeClass("div_content_show");

   $("#div_content").addClass("div_content_hide");


});


});


</script>



Output:


Yeah! You have learned ЁЯШК

I hope you understood and like this article. if you like it so, please give feedback in the comment section.

Post a Comment

Please do not enter any spam link in the comment section.

Previous Post Next Post