Display specific content according to the hash in the URL

I have a website with a page (/categories.html) that contains around 50 p elements:

<p id='BCI'>Blue_colored_items</p>
<p id='RCI'>Red_colored_items</p>
...

What I want is for the page to only display:

Blue_colored_items

if the requested URL is:

/categories.html#BCI

and so forth for the other items. How can I achieve this? I am open to altering the entire HTML structure if needed.

Answer №1

Discovering this simple CSS trick was a game-changer for me.

<style>
p {display: none}
:target {display: block}
</style>

Shoutout to Rory and Andrei for their help!

Answer №2

document.body.classList.add(window.location.hash.substring(1))

By adding any existing hash as a class to the <body> element, you can easily manipulate it using CSS:

p {display:none;}
.BCI p#BCI {display: inline;}
.RCI p#RCI {display: inline;}
...

Alternatively, you can dynamically display the <p> based on the hash value:

// Setting hash specifically for StackOverflow (relevant only here, on SO):
window.location.hash = '#BCI';

let p = document.getElementById(window.location.hash.substring(1));
if (p) p.style.display = 'inline';
p { display: none; }
<p id='BCI'>Blue_colored_items</p>
<p id='RCI'>Red_colored_items</p>

Answer №3

To access the desired value, simply utilize the window.location.hash property. Following that, you can selectively conceal the necessary content while keeping the specified element visible. Here's an example of how you can achieve this:

var hash = '#BCI'; // window.location.hash;

$('p').not(hash).hide();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p id="BCI">Blue_colored_items</p>
<p id="RCI">Red_colored_items</p>

Keep in mind that in this instance, p serves as a broad selector; it is recommended to employ a more specific selector in your actual code for better accuracy.

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

Retrieving Information from Ajax Call Using Python

I am struggling to figure out how to retrieve data from an Ajax request in my JavaScript code within a Python Flask application. The Ajax request I am working with does not involve jQuery. I have attempted using request.form.get() and request.get_json() i ...

Converting Base64 data from a canvas to a blob and then processing it in PHP

I encountered a problem when trying to send a base64 image from a canvas to PHP using an AJAX POST request. After doing some research on the internet, I discovered that some people suggested increasing the memory_limit in the PHP server settings, possibly ...

The storage capacity of localStorage is insufficient for retaining data

While I was trying to troubleshoot an error, I encountered another issue. var save_button = document.getElementById('overlayBtn'); if(save_button){ save_button.addEventListener('click', updateOutput);} This led to the following ...

Issue with CSS Media Queries: Preventing an Element From Being Affected

As a complete beginner in HTML and CSS, I have a question that may seem silly. Recently, I created this HTML code: * { margin: 0px; padding: 0; box-sizing: border-box; } p { font-size: 14px; font-family: 'Work Sans', 'sans seri ...

Utilize the $setValidity function within ng-repeat to validate input fields

I am facing an issue with my form that is being repeated in an ng-repeat. Below is a snippet of the form. I need to implement custom validation using $setValidity in the controller. However, I am struggling to access input names by index in the controlle ...

Unexpected Django Get request error causing confusion

I am currently working on a basic Django app that enables users to add items to a database. The goal is to have the list of items automatically update whenever a new item is added via the form, displaying both the newly added product and all existing produ ...

Styling with CSS in Play Framework version 2.0.3

Running into issues when using CSS in Play Framework 2.0.3 and could really use some help spotting where I'm going wrong. My view, called siteview.scala.html, is defined as: @(name: String, records: List[Record]) @import helper._ @main(name) { < ...

Alter the value of a parameter within a script tag with JavaScript/jQuery

Looking to dynamically change a parameter value using JavaScript or jQuery. Here is an example URL: www.exampleurl.com/somepage?foo=test I have a function that can extract the value after the 'foo' parameter: function getParameterByName(name, ...

Use jQuery to place the initial 3 elements within a div

Currently, I am dynamically pulling content into li elements using ASP.NET. My goal is to wrap a specific div class around the first 3 li items in the list only. Here is an example: <ul class="wrapper"> <div cl ...

An error occurs when calling useSWR in a function that is neither a React function component nor a custom React Hook function

When using useSWR to fetch data from an endpoint, I encountered the following error (I only want to fetch data onclick) "useSWR is called in function `fetchUsers` that is neither a React function component nor a custom React Hook function" Error ...

I am facing difficulty in loading another page due to AngularJS restrictions

How can I create a link that redirects to another page without any visible effect on the current page? I have tried various methods: <a href="url"> <a href="url" target="_self"> <a ng-click="register()"> The "register" function i ...

SmartEdit functions properly when spartacus is running using yarn start --ssl, but does not work without SSL enabled

I followed the smartedit setup instructions at and everything works well when I start the Spartacus server with yarn start --ssl. However, if I start the server with just yarn start, the storefront does not appear. See image here for reference ...

"Using Java HttpServlet to send data as a Gson string, then retrieving it in JavaScript as

On the server side, I have this Java code snippet: public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException { resp.setContentType("application/json;charset=UTF-8"); resp.setHeader("Cache-Control", "no-cach ...

Guide to creating seamless integration between AngularJS routing and ExpressJS routing when using html5mode

Yesterday, I posted a question on stackoverflow about my webpage's CSS and JavaScript not including after a refresh. I discovered that it was caused by html5mode, but I have been searching for a solution since then with no luck getting an answer. My ...

Countdown Widget - Transform "0 Days" to "Today" with jQuery

I am currently working on a countdown page using the Keith Woods Countdown jQuery plugin which can be found at . Here is the code I have implemented so far: $(document).ready(function () { var segera = new Date(); segera = new Date(segera.getFullYear(), 2 ...

"PHP MySQL news error" - An unexpected error occurred

Just incorporated a news system using MySQL/PHP, it functions flawlessly; however, encounters errors when inserting HTML. For instance, inserting a YouTube video results in the addition of / or \ Can someone advise on what changes need to be made in ...

Guidance on implementing a source map in a Node.js VM

Currently, I am analyzing JavaScript bundled source code in Node.js using the following snippet of code: const javascriptCode = "..." const javascriptSourceMap = "..." const wrapper = NativeModule.wrap(javascriptCode); const script = ne ...

After refreshing the page, RouterLinkActive in Angular 6 fails to work

Scenario In my application, there is a menu with various items. The selected item is distinguished by adding the selected class to it, which changes its appearance. https://i.sstatic.net/JEPHH.png Problem While navigating between routes works smoothly, ...

Guide to extracting a specific segment from req.body in Node.js

I've been attempting to access a specific nested property of req.body, but the output always turns out to be undefined. Here is the code snippet: let dataReceived = JSON.stringify(req.body); console.log(dataReceived); let refCode = ...

Set iframe scroll to match the height of the user's screen resolution

Can the height of an iframe scroll be adjusted to match the size of the screen (browser)? Essentially replacing the default browser scroll with the iframe scroll. Here's what I'm looking to achieve: Currently, my browser scroll is disabled: < ...