Hide/Show Element with jQuery

The name of the pictureThe name of the pictureThe name of the pictureClash Royale CLAN TAG#URR8PPP


Hide/Show Element with jQuery



I'm trying to learn jQuery and Javascript. I want to hide and show a Div Element (div2) with a button on a webpage using a button I have placed on the page. However, I want the jQuery code to be placed in a separate file referenced later on (like a custom .css file). Here's my basic code:




#div1{
background-color: aquamarine;
}

#div2{
background-color: firebrick;
}

#hide_show{

background-color: cornflowerblue;

}


<html>

<head>


<link href="special.css" rel="stylesheet" type="text/css">

</head>

<body>

<div id ="div1">

this is a container

</div>

<div id = "div2">

This is another div.

</div>

<button type="button" id ="hide_show">Click Me!</button>


</body>

</html>



Referencing the file isn't an issue. However, how do I go ahead with writing the Javascript file? Also, does the text editor of your choice affect how Javascript is executed on the website? I'm currently using codeblocks.



Thanks.





head tag should be out of body tag
– Zakaria Acharki
19 mins ago




head


body





html syntax is invalid . You need to fix that first . use website fixmyhtml.com . Then you can use id as selector to hide and show . $('#div2').hide()
– Abhishek SInha
13 mins ago







Oh didn't see that. Thanks for the heads up.
– Hamza
13 mins ago





No, CodeBlocks won't affect your file.
– Victoria Ruiz
10 mins ago




4 Answers
4



Hi so your html file should first reference Jquery then in your JS file you can do:


$('#hide_show').on('click', function(event){
$('#div2').hide();
});


$('#hide_show').click(()=>{ // subscribe to button click event
$('#div2').fadeToggle(); // animate show hide toggle
// $('#div2').toggle(); // without animation effect
});



Methods .fadeToggle() or .toggle() might help.



html syntax is invalid . You need to fix that first . use website http://fixmyhtml.com
then use you can write jquery


$('#hide_show').click(function(){
$('#div2').toggle();
});



For questions like these, I would recommend you the website https://w3schools.com.



It will tell you how to properly include the JQuery library and and is a good reference site for programming syntax.






By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Popular posts from this blog

Makefile test if variable is not empty

Will Oldham

'Series' object is not callable Error / Statsmodels illegal variable name