We'll going to share a very commonly used jquery snippet, but one that newcomers to web design often feel is more difficult than it actually is!
All we’re going to do is set up a simple show/hide toggle effect.
To start with, we’ll need to include jQuery on the page – pop this in your <head> </head> tags:
<script type="text/javascript" src="your/link/to/jquery.min.js"></script>
And then we need to get the page ready for our script. To do this, everything we write will be enclosed within $(document).ready. Everything inside this little function will be loaded soon as the DOM is loaded and before the page contents are loaded.
<script type="text/javascript">
$(document).ready(function() {
});
</script>
Now, first of all we want to hide the content that will be toggled (presumably). To do this we select our element (#showme), and then the function for this is a simple .hide();
Then we just need to set what element will action our toggle. To do this, select your element – in the example below it has an id of toggleBtn:
<script type="text/javascript">
$(document).ready(function() {
$('#showme').hide(); //hide our content first
$('#toggleBtn').click(function() {
//do stuff when #toggleBtn is clicked
});
});
</script>
And then finally, we actually tell jQuery which element is to be toggled (.toggle()) – #showme, and at which speed to do it. The 800 is brackets defines the speed of which the toggle takes place. The higher the number, the faster the transition.
<script type="text/javascript">
$(document).ready(function() {
$('#showme').hide(); //hide our content first
$('#toggleBtn').click(function() {
$('#showme').toggle(800);
return false;
});
});
</script>