Switching content areas without changing the page is a feature that is appearing more and more in modern web design. On some websites, this is used as the main focal point of the user interface, and on other sites, it helps to minimize the amount of area that is taken up by info and consolidates multiple areas of information into one location enhancing the user experience. This is achievable many different ways, one of the simplest ways using jQuery.
There is a working demo available here. (JSfiddle)
In order to accomplish this task, We must include our jQuery file in between the head tags:
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
</head>
or at the bottom of your body:
<body>
...BODY CONTENT
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
</body>
as shown above.
Then we can begin coding the jQuery that will switch between our divs fading them in and out on the button click.
<script type="text/javascript"> $(document).ready(function () { $('.BTN').click(function () { $('.div').fadeOut('slow', function () { $('.div2').fadeIn('slow'); });
$('.BTN2').click(function () {
$('.div2').fadeOut('slow', function () {
$('.div').fadeIn('slow');
}); });
});
});
</script>
At first glance, the above script may appear confusing but when broken down it is actually very simple. We call up the jQuery file:
$(document).ready(function () {
Then we focus on our first button, give the button a function (click();) then tell the function to fade the section with a class of .div out and the section with a class of .div2 in.
$('.BTN').click(function () {
$('.div').fadeOut('slow', function () {
$('.div2').fadeIn('slow');
});
After that, we focus on the second button, give the button the click(); function, and tell the function to fade the section with a class of .div2 out and the section with a class of .div1 in.
$('.BTN2').click(function () {
$('.div2').fadeOut('slow', function () {
$('.div').fadeIn('slow');
}); });
Once this is complete, we have created our fading divs that switch when a button is clicked. Now just style your page and you’ve created two sections that switch back and forth between eachother.
I hope you found this post helpful! Good luck coding the web!