Unveiling the hidden div with a direct URL trigger

I am currently working on a small webpage that consists of three sections. Only one section is displayed at a time while the others remain hidden. The welcome section is shown by default when the page loads, and the rest are set to display:none. By clicking the menu buttons for the other sections, the desired section is displayed, and all others are hidden. I have implemented jQuery for this functionality. However, I am facing an issue with creating URLs to navigate to specific sections. Typically, I would create an anchor tag with a unique name and add #XXX at the end of the URL to go to a visible section on a page. But, this method doesn't work on hidden div elements.

Any suggestions on how to achieve this?

Here is the HTML code:

<div id="menu">
    <p><a href="#" id="menu-home">Home</a></p>
    <p><a href="#" id="menu-page1">Page 1</a></p>
    <p><a href="#" id="menu-page2">Page 2</a></p>
</div>

<div id="home">
    <h1>Welcome!</h1>
    <p>This is where all the home page content will be placed.</p>
</div>
<div id="page1">
    <h1>Page 1</h1>
    <p>Content for Page 1 will be displayed here.</p>
</div>
<div id="page2">
    <h1>Page 2</h1>
    <p>Content for Page 2 goes here.</p>
</div>

CSS styles:

#page1 {
    display:none;    
}
#page2 {
    display:none;
}

JavaScript function:

$(document).ready(function(){
    $('#menu-home').click(function(){
        $('#home').show('fast');
        $('#page1').hide('fast');
        $('#page2').hide('fast');
      });
    $('#menu-page1').click(function(){
        $('#page1').show('fast');
        $('#home').hide('fast');
        $('#page2').hide('fast');
      });
    $('#menu-page2').click(function(){
        $('#page2').show('fast');
        $('#home').hide('fast');
        $('#page1').hide('fast');
      });
});

Answer №1

If you want to retrieve a specific part of the URL, consider using window.location.hash*.

To make this work effectively, assign appropriate hash values to your <a> tags:

<p><a href="#page1" id="menu-page1">Page 1</a></p>
<p><a href="#page2" id="menu-page2">Page 2</a></p>

Then, validate whether the extracted string matches a specific page:

$(document).ready(function(){
    // Attaching click events to elements

    var locationHash = window.location.hash.substring(1);
    if(locationHash == 'page1'){
      $('#menu-page1').trigger('click');
    }else if(locationHash == 'page2'){
      $('#menu-page2').trigger('click');
    }
});

In this solution, click events are used for quick functionality and substring is utilized to remove the '#' from location.hash. There's room for improvement, like not hiding page1 or page2 initially if a matching hash is found.

*Refer to the linked document for more details on Location, as window.location represents a Location object containing a hashproperty

Answer №2

To incorporate this feature, include a JavaScript function that automatically scans the URL upon loading for an anchor such as #menu-xy, and displays the related div accordingly.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Insert a parameter or substitute the existing value if detected

Trying to create a JavaScript regex that searches for a parameter in a URL and replaces its value if found. If the parameter is not found, it should be added to the URL. Here are a couple of scenarios: http://www.domain.com/?paramZ=123456 https://www.dom ...

Guide me in changing my Vticker default direction from sliding up to right to left

$(document).ready(function() { $('#example').vTicker(); $('#example1').vTicker({ speed: 500, pause: 3000, showItems: 3, animation: 'fade', mousePause: false, height: 0, ...

What is the purpose of using double quotes within single quotes in JavaScript?

Could someone clarify the reason behind needing to nest double quotes inside single quotes in my Webpack configuration shown below? What is preventing using just double quotes? module.exports = merge(prodEnv, { NODE_ENV: '"development"', API ...

Angular 6: A guide to dynamically highlighting navbar elements based on scroll position

I am currently building a single page using Angular 6. The page is quite basic, and my goal is to emphasize the navbar based on scrolling. Below is the code snippet I am working with: .sticky { position: sticky; top: 0; } #i ul { list-style-type: ...

Troubleshooting issue with Bootstrap collapse functionality failing with dynamic IDs

Having trouble creating dynamic ids for bootstrap collapsing functionality. I want each topic in an ng-repeat to collapse and display its respective question list when clicked. The issue is that when I click on a second topic, the question list data from ...

How can I extract the id of a clicked item and pass it to a different page with Jquery?

Facing an issue where the attribute value of a clicked href tag is not retained after browser redirection. Initially, when clicking on the href tag, the value is displayed correctly. However, upon being redirected to the peoplegallery_album, the id becomes ...

What is the best way to load an image file using JavaScript and store it in a separate directory?

Is there a way to transfer an image file from one directory to another by clicking a button using Javascript that will work on all browsers (IE, FF, Chrome)? I already have code for this: <input type="button" name="button" value="Move image to another ...

Troubleshooting ng-class functionality in AngularJS

I am attempting to utilize AngularJS in order to change the class name of a div element. Despite following the guidance provided in this answer, I am encountering difficulties as the class name is not updating in my view. Below is the code from my view: ...

Automated playback of integrated Twitter video

Is there a way to make embedded Twitter videos autoplay? The code generates an iframe which is preventing me from using some JavaScript click tricks. Is there a workaround to enable autoplay? Plunker <script>window.twttr = (function(d, s, id) { v ...

Webstorm encounters difficulties compiling Sass

While attempting to utilize Sass in the Webstorm IDE, I noticed that it is defaulting to Ruby 1.8 (OS Default) instead of my preferred RVM Ruby Version (1.9.x). To address this issue, I tried setting the path for Sass in the Watcher-Configuration: PATH=$ ...

Encountered an Unexpected Token on Heroku: ??=

2021-12-02T02:42:45.888858+00:00 app[worker.1]: /app/node_modules/discord.js/src/rest/APIRequest.js:33 2021-12-02T02:42:45.888875+00:00 app[worker.1]: agent ??= new https.Agent({ ...this.client.options.http.agent, keepAlive: true }); 2021-12-02T02:42:4 ...

Is it possible to duplicate inputs using jQuery in multiple forms on a single page?

I've been struggling to make two forms work on the same page. The main issue I'm facing is getting the clone inputs to function properly because of conflicts arising from the div elements. I've been following this tutorial for guidance: He ...

Tips for concealing all items except the currently selected branch when clicking on a menu drop-down

I am seeking a solution to open only one node at a time on click, and remove the 'is-active' class from other items. Currently, there is excessive space taken up after opening multiple menu items. I want to ensure that only one node is open at a ...

how can I retrieve an element using a datetime in JavaScript

I have a list of appointments like the one below: 0: {start: '2022-02-23T09:30:00', end: '2022-02-23T10:00:00',…} 1: {start: '2022-02-23T10:00:00', end: '2022-02-23T10:30:00',…} 2: {start: '2022-02-2 ...

Implementing Asynchronous Custom Validators in Angular 4

I've encountered the following code snippet: HTML: <div [class]="new_workflow_row_class" id="new_workflow_row"> <div class="col-sm-6"> <label class="checkmark-container" i18n>New Workflow <input type="che ...

What is the best way to compare and identify the variances between two JSON documents in Marklogic using JavaScript?

Is there a way to analyze and compare two JSON documents in Marklogic using JavaScript to identify any differences between them? ...

Utilize jQuery.queue() to line up ajax requests in a queue

I'm having trouble understanding how to use jQuery.queue() for the first time. Can someone please help me figure out what I'm doing wrong? When I look in firebug, my POST requests still seem to be firing at the same time. I suspect that I might ...

Issue with displaying Bootstrap Tooltip

Recently, I launched a fresh website (currently residing on a sub-domain). However, I am facing an issue with the tooltip not showing up when hovering over the text Get the FinEco Bookmarklet. <span class="bookmarklet"><span class="fa fa-bookmark ...

Enhance the efficiency of DataTable by optimizing cell class modifications

I have been very pleased with the performance of jquery DataTables, but I have encountered a situation where I need to optimize it further. Specifically, I am updating the class of a cell based on its data. Currently, I am achieving this by using the ren ...

Tips for finishing Vuetify's circular progress bar using a center percentage value

I've been exploring the features of Vuetify's progress circular component lately. This component allows you to specify a value prop, which represents the current progress percentage. The circle completes when the value reaches 100. In my scenar ...