Wednesday, 18 August 2021

jQuery hide ,show and toggle div element on button click

Hi guys, in this post we will see how to hide ,show and toggle div element on button click using jquery.

jQuery hide ,show and toggle div element  on button click

Please follow below steps:-

1)Open your editor.

2)Add one div element and three buttons in web page one for hiding div, one for showing div and one for toggling div elements.

3)Add jquery CDN link in head section.

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

4)Add document ready function in script section. Then add click event handler for three buttons.

            $('#btnHide').click(function(){

$('#div1').hide();

});

$('#btnShow').click(function(){

$('#div1').show();

});

$('#btnToggle').click(function(){

$('#div1').toggle();

});

    i) To hide div element use $('#div1').hide();

    ii) To show div element use $('#div1').show();

    iii) To toggle div element use $('#div1').toggle();

Full Code:-

<html>

<head>

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

<script type="text/javascript">

$(document).ready(function(){

$('#btnHide').click(function(){

$('#div1').hide();

});

$('#btnShow').click(function(){

$('#div1').show();

});

$('#btnToggle').click(function(){

$('#div1').toggle();

});

});

</script>

</head>

<body>

   <div Id="div1"><h1>This is DIV element.</h1></div>

   <button id="btnHide">Hide Div</button>

   <button id="btnShow">Show Div</button>

   <button id="btnToggle">Toggle Div</button>

</body>

</html>



No comments:

Post a Comment