Becky Becky - 2 years ago 73
Javascript Question

How to show a specific section from a link that is hidden

I have multiple links that go to the same page, however I want different sections of that page to show (preferably at the top of the page). The issue is, those sections are hidden on page load and so is the container they are in. I solved how to get the container to show, but it shows all of the different sections when I only want the one I clicked on, from the link, to show. ie:

I have these links:

<a href="serviceCheck1#service1">Service 1</a>
<a href="serviceCheck1#service2">Service 2</a>
<a href="serviceCheck1#service3">Service 3</a>

Then on the
page I have this HTML:

<div id="service-display-box">
<div id="service-display-box-container">
<div class="service-item-box" id="service1">
<div class="service-item-title">Service 1</div>
<div class="service-item-box" id="service2">
<div class="service-item-title">Service 2</div>
<div class="service-item-box" id="service3">
<div class="service-item-title">Service 3</div>
<div class="service-item-box" id="service4">
<div class="service-item-title">Service 4</div>
<div class="service-item-box" id="service5">
<div class="service-item-title">Service 5</div>
<div class="service-item-box" id="service6">
<div class="service-item-title">Service 6</div>

If I would click on the link that says, Service 2, I would want the
to show and then the
div to show, then all of its siblings to not show.

Here is my javascript:


//get the section name from hash
var sectionName = window.location.hash.slice(1);

//then show the section
//$('#' + sectionName ).show();
$('#service' + sectionName).show().siblings().hide();

/*var index = location.hash.indexOf('#service');
if(index > -1) {
var serviceId = parseInt(location.hash.substring(index));
if(serviceId) {
$('#service' + serviceId).show().siblings().hide();

Answer Source

It appears as though your selector for the section is not formed correctly. Essentially this happens:

  1. You click on <a href="serviceCheck1#service1">Service 1</a>
  2. The serviceCheck1 page loads.
  3. This line runs: var sectionName = window.location.hash.slice(1);
  4. sectionName now contains "service1"
  5. This line runs: $('#service' + sectionName).show().siblings().hide();
  6. This evaluates to $('#serviceservice1').show().siblings().hide();
  7. The browser can't find an element with the id serviceservice1
  8. Nothing happens :)

Instead, since window.location.hash contains #service1 already, just run the following:


Which will find the appropriate element, show it, and hide its siblings.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download