How to hide or show content based on links or urls via JavaScript/jQuery

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.

Here is the JavaScript/jQuery code that executes on the linking page:

  1. <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js"></script>
  2. <script type="text/javascript">
  3. $(document).ready(function() {
  4. 	var option = 'coke';
  5. 	var url = window.location.href;
  6. 	option = url.match(/option=(.*)/)[1];
  7. 	showDiv(option);
  8. });
  9. function showDiv(option) {
  10. 	$('.boxes').hide();
  11. 	$('#' + option).show();
  12. }
  13. </script>

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 coke.

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 boxes class.

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 .show() method.

Here is the HTML code for the second page with our dynamic displayed content:

  1. <div class="boxes" id="coke">Coke is awesome!</div>
    
  2. <div class="boxes" id="bubble-tea">Bubble tea is da bomb!</div>
    
  3. <div class="boxes" id="milk">Milk is healthy!</div>
    
  4. <p>
    
  5. 	I change my mind:
    
  6. 	<ul>
    
  7. 		<li><a href="javascript:showDiv('coke')">Coke</a></li>
    
  8. 		<li><a href="javascript:showDiv('bubble-tea')">Bubble Tea</a></li>
    
  9. 		<li><a href="javascript:showDiv('milk')">Milk</a></li>
    
  10. 	</ul>
    
  11. </p>
    
  12. <a href="/demo/demo.html">Back to main page</a>

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.





Published by

Allen Liu

Building websites is a passion of mine. During the course of my work, I have created some snippets of code that I hope will prove useful to other developers.

26 thoughts on “How to hide or show content based on links or urls via JavaScript/jQuery”

  1. Hi Allen
    An excellent tutorial!
    I’m a little stuck as i’m also using an additional piece of JS which seems to be conflicting. This additional piece works fine but ignores yours. I’m not all that good with JS, so please ignore any bad errors.

    https://jsfiddle.net/#&togetherjs=ODuTb3TAGb

    You’ll notice that the extra JS is

    function(noevents) {
    document.body.innerHTML = document.body.innerHTML.replace(‘There are no records’, ‘There are no upcoming events’);

    This looks for database content on the page (not shown in the JSFIDDLE) that contains the text “There are no records” and replaces it as “There are no upcoming events”.

    I really need to use both.

    Please let me know where I’m going wrong.

    1. Hi Travis,

      I was on vacation so I apologize for the late response. I tried the link to the jsfiddle but it led me to a collaboration with no code. If you are still looking for help, please give me a link to the saved jsfiddle.

      Thanks,

      Allen

      1. Hi Allen

        Thanks for getting back to me!

        Here’s the JSFiddle, but it is a little hard to replicate when the second JS relates to database content. I’ve tried to replicate with plain old html but it doesn’t work.

        https://jsfiddle.net/9pa80x7z/7/

        Effectively, the second script replaces the text “There are no records” with text “There are no upcoming events”. This script prevents your script from working.

        Any help to get them both working at the same time would be appreciated!

        Thanks

        $(document).ready(function() {
        var option = ‘SA’;
        var url = window.location.href;
        option = url.match(/Type=(.*)/)[1];
        showDiv(option);
        }

        function showDiv(option) {
        $(‘.boxes’).hide();
        $(‘#’ + option).show();
        }

        var $j = jQuery.noConflict(); $j(document).ready(function() {
        document.body.innerHTML = document.body.innerHTML.replace(‘There are no records’, ‘There are no upcoming events’);
        });

  2. in the example below
    ————————————————————–

    $(document).ready(function() {
    var option = ‘coke’;
    var url = window.location.href;
    option = url.match(/option=(.*)/)[1];
    showDiv(option);
    });
    function showDiv(option) {
    $(‘.boxes’).hide();
    $(‘#’ + option).show();
    }

    ——————————————————————–
    please explain the part
    “option = url.match(/option=(.*)/)[1];”

    1. Hi,

      That line of code sets the option variable equal to the id of the element you want to show or hide.

      For example, let’s say I have a

      that I want to show/hide so the url can be something like this:

      http://www.my-website.com?option=myDiv

      The line of code will be able to parse out the “option” parameter and grab the value “myDiv” and set that as the value to the “option” variable which will be used later on to manipulate the DOM.

      I hope that helps.

      Allen

  3. hi Allen

    I tried to use your example it did not work.

    Here is my scenario : I have a main menu with buttons mm1, mm2, mm3) and a 3 secondary menus (sm1, sm2, sm3) . Each of the secondary menus have their own set of menus.

    When the page loads I want to show main menu and Secondary sm1. Later on a click on anyone of the main menu buttons should hide all secondary menus and show only the one corresponding to the click. For example, a click on mm2 should hide all secondary menus and display only sm2 menu.

    I tried this using your code but it does not work.

    What am I missing?

    How can I post the files?

  4. Thanks a lot, this is what I needed to be able to hide div in a php site. I decided to pick the variable from php $_GET though, so my code is more like:

    $(document).ready(function() {
    var option = ”;
    showDiv(option);
    });

  5. Hello,

    Thanks for the tutorial, its the one that I was looking for.

    I try to change the link ref into something like this :
    coke

    And change the javascript into something like this : (actually just changing the url variable)

    $(document).ready(function() {
    var option = ‘coke’;
    var url = window.location.pathname;
    option = url[3];
    showDiv(option);
    });
    function showDiv(option) {
    $(‘.boxes’).hide();
    $(‘#’ + option).show(
    );
    }

    No matter what I clicked, all shown like this :

    Coke is awesome!
    Bubble tea is da bomb!
    Milk is healthy!

    I have tried it by using alert message to show whether option variable will catch the right variable. And it did whon the right variable. But why the showDiv function does not work? It suppose to be working just like your code.

    Would you please tell me what is the problem? I’m still new with javascript.

    Thanks in advance

  6. Hi,

    Many thanks for this post, it’s very interesting and useful.

    I would like to ask you something, I would like to change the color of the selected menu. So the one that is showing the displayed information became on a different color, and go back to the current one when hidden.

    Hope you can help,

    Many thanks

    1. You can dynamically add a class to the div =)

      1.  
      2.  
      3. $(document).ready(function() {
      4. 	var option = 'coke';
      5. 	var url = window.location.href;
      6. 	option = url.match(/option=(.*)/)[1];
      7. 	showDiv(option);
      8. });
      9. function showDiv(option) {
      10. 	$('.boxes').hide();
      11. 	$('#' + option).addClass("yourClass").show();
      12. }

      In line 11, you can see the change where we are adding the yourClass class to the div before we show it.

      You can then add the necessary CSS styling information for the yourClass class.

      .yourClass {
           color: red;
           border: 1px solid green;
      }
      

      I hope this helps.

      Allen

Leave a Reply

Your email address will not be published. Required fields are marked *