I have received many requests for a tutorial that shows how to hide or show content based on links or options that a user picks and reflected on a different page so here it is =)
You can see a working demo here.
Here is the plain HTML:
If you had to choose a drink, what would you choose: <ul> <li><a href="/demo/demo-show-hide-based-on-url.html?option=coke">Coke</a></li> <li><a href="/demo/demo-show-hide-based-on-url.html?option=bubble-tea">Bubble Tea</a></li> <li><a href="/demo/demo-show-hide-based-on-url.html?option=milk">Milk</a></li> </ul>
It is a simple list of options for a user to select and the key is in the linking url. There is an
option parameter where we are passing over the user’s selected option. The
option values (coke, bubble-tea, and milk) will map to their respective div ids on the following page that we will dynamically hide or show.
1 2 3 4 5 6 7 8 9 10 11 12 13
Line 1 imports the jQuery library from Google’s content distribution network (CDN). There are a couple of reasons why you should use CDNs including decreased latency and increased parallelism. If you are interested in reading the details, here is a nice post.
Line 4 assigns the default div id that will be shown which in this case is
Lines 5-6 parses the option value from the url information.
Line 7 calls the
showDiv() function and passes the option value as an argument.
In line 10 of the
showDiv() function, we hide all the divs in case there are any that are opened. We do this using the jQuery class selector where we select all the elements with the
Line 11 will use the id (e.g. #) jQuery selector using the option parameter that was passed over and show the element via the jQuery
Here is the HTML code for the second page with our dynamic displayed content:
1 2 3 4 5 6 7 8 9 10 11 12
We begin with the divs, each with their respective ids (coke, bubble-tea, milk). We then re-list our options on this page as well. The links here do not link to another page though. Instead, they call the
showDiv() function and pass over the selected option.
If you found that my code was helpful in any way, shape, or form and would like to buy me a beer, please use the Donate button below =) Cheers! OR…you can sign up for a free Dropbox account using my referral link =) If you are not aware of what Dropbox is, it is the most awesomest online backup application there and so much more…all for free.