Tips for reaching the outer div utilizing the URL

I am working with an HTML script that looks like this:

<html>
     <head></head>
     <body>
        <div id="div1"></div>

        <div id="div2"></div>
     </body>
</html>

Now, I need to be able to access the div elements based on the URL. For example, if the URL is:

example.com#div1

I want to hide div2. On the other hand, if the URL is:

example.com#div2

then I want to hide div1

Is it possible to achieve this using CSS?

Answer №1

Utilizing CSS pseudo selector can achieve this effect

<html>
 <head>
    <style type="text/css>
    .my-div {
        background-color: green;
        display: none;
        height: 100px;
        width: 100px;
    }
    .my-div:target {
        display: block;
    }
    </style>
 </head>
 <body>
    <div id="div1" class="my-div">Div 1</div>
    <div id="div2" class="my-div">Div 2</div>           
 </body></html>

Ensure the URL always has #div1 such as example.com/#div1 or example.com/#div2, otherwise it will display a blank page

Answer №2

Recently, I tried a method that may not be achievable through CSS alone.

This technique ensures the correct div loads when the page is accessed or if the user navigates back in their browser.

<script>
    $(document).ready(function() {
      if (window.location.hash) {
        var hash = window.location.hash.substring(1);
        changeTab(hash);
      }
      else {
        changeTab('div1');
      }
    });

  function changeTab(divNo) {
    $('.divclass').hide();
    $('#' + divNo).show();
    window.location.hash = '#'+divNo;
  }

</script>

If you want to use a button to switch between divs, simply add this line:

onclick="changeTab('div1');"

Remember to assign your div's class attribute as 'divclass'.

Answer №3

How can I style an outer div based on the URL?

If you want to target an outer div based on the URL, you can use the CSS pseudo-class :target. Here's an example:

div {
float:left;
width: 300px;
height: 150px;
}

#div1, #div2 {
display:none;
line-height: 150px;
color: rgb(255,255,255);
font-size: 72px;
text-align: center;
font-weight: bold;
}

#div1 {
background-color: rgb(255,0,0);
}

#div2 {
background-color: rgb(0,0,255);
}

#div1:target, #div2:target {
display:block;
}
<div>
<p><a href="#div1">Display Div1 (but not Div 2)</a></p>
<p><a href="#div2">Display Div2 (but not Div 1)</a></p>
</div>

<div id="div1">Div 1</div>
<div id="div2">Div 2</div>

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

Anchor from HTML/Javascript to different section is not functioning as expected

I am having trouble with creating a 'scroll down' link on my webpage. I cannot seem to find a solution specific to my issue. My code looks like this: <a href="#apply-profile">scroll down</a> When clicked, this link should take users ...

How can you convert label text to capitalize if the original text is in uppercase letters?

Is there a way to change a label text to capitalize if the label text itself is in uppercase? I attempted the following: <p class="capitalize">THIS IS SOME TEXT.</p> In addition, I added: p.capitalize { text-transform: capitalize; } Howeve ...

Image spotlight effect using HTML canvas

I am currently seeking a solution to create a spotlight effect on an HTML canvas while drawing an image. To darken the entire image, I used the following code: context.globalAlpha = 0.3; context.fillStyle = 'black'; context.fillRect(0, 0, image. ...

Issue with Enter key not working on an individual textbox within Javascript/PHP chat functionality

Recently, I created a chat feature with text boxes that send messages when the ENTER key is pressed. However, I encountered an issue with it not working for the "Warning" functionality. Whenever I press Enter in this context, nothing happens. Can anyone pr ...

customized checkbox in Bootstrap 4

I'm facing an alignment issue with my custom ASP.NET Bootstrap 4 checkbox. I can't seem to get it to align properly within the form group row as shown in the picture – Issue with checkbox. The code for the form group row is as follows: <di ...

Initiate an animation in Wordpress once the entire page has finished loading

Recently, I incorporated some "raw html" elements with animations into my WordPress site. However, the issue I'm facing is that these animations kick off as soon as the page loads, without waiting for the preloader to complete and display the actual c ...

Achieving a responsive card layout in Reactjs with Bootstrap by displaying four cards in a single row

const DisplayCategory = () => { const history = useHistory(); useEffect(() => { axios.get('http://localhost:8080/products', { headers: { Authorization: "Bearer " + localStorage.getItem("token&q ...

Tips for positioning a highcharts pie chart and legend in the middle of a page

I'm struggling to center my highchart data in a node/react single page application. Currently, it appears off-center like this: https://i.stack.imgur.com/ccR6N.png The chart is floating to the left and I would like to have everything centered within ...

D3 bar chart displaying identical values but with varying data sets

<!DOCTYPE html> <html lang='en'> <head> <meta charset="UTF-8"/> <title>Interactive Bar Chart using D3</title> <script src="https://d3js.org/d3.v4.min.js"></script> </head> <b ...

The empty string is not getting recognized as part of an array

Currently, I have a textarea field where pressing enter submits and creates a new item in the array. Pressing shift + enter creates a new line in the textarea input field. But when trying to submit by pressing shift and enter after creating a new line, it ...

Using Express, Node, and JQuery to handle form submissions

I am struggling with form submissions while working on a web app using HTML, Express, and Node.js. Despite being new to these technologies, I have created a script that generates a dynamic form based on certain factors: $FormContainer.html(''); ...

Eliminating a decimal point from the Document Object Model

I've got some HTML code that's being generated through PHP. It includes a number with two decimal places within a span element that has the class "amount": <span class="amount">200.00</span> My goal is to find a way to use a client- ...

Tips for implementing page-break-after:always within a bootstrap row?

I have a bootstrap row with a set of divs inside like this: @media print { p { page-break-after : always } } <div class = "row"> <div> data1 </div> <p> break page here </p> <div> data2 </div> <div> ...

Issue with Flask app's template rendering when trying to search for a book

Currently, I am working on a Flask web application that has the functionality for users to search for books and view detailed information about them. However, an obstacle I am encountering is that the form does not get sent to the specified URL. Below is ...

How can you ensure that it selects a random number to retrieve items from an array?

I am experiencing an issue with some code I wrote. Instead of displaying a random object from the array as intended, it is showing the random number used to try and display an object. <html> <body> <h1>HTML random objects< ...

There seems to be an issue with the location.href function in the server-side code of

I'm encountering an issue in the code below where I am attempting to redirect to the login page, but it seems to not be functioning as expected. app.get('/current-pass', (req, res) => { res.sendFile(path.join(staticPath, "currentPass ...

jQuery Toggle and Change Image Src Attribute Issue

After researching and modifying a show/hide jQuery code I discovered, everything is functioning correctly except for the HTML img attribute not being replaced when clicked on. The jQuery code I am using: <script> $(document).ready(function() { ...

Text animation that rises smoothly within a concealed overflow region

I'm currently trying to replicate the effect seen in this example: Specifically, I am referring to the text that reads "CREATIVE AGENCY FOR DARING BRANDS" Although it appears simple, I am having trouble figuring out how to achieve it. I primarily wo ...

Selecting HTML5 data attributes using jQuery

There is a button on my page with multiple data attributes, and I am trying to hide it by selecting it based on its class and two specific data attributes. <a href='#' class='wishlist-icon' data-wish-name='product' data-wi ...

Position the div elements at the center

I am facing an issue with aligning elements inside a div both vertically and horizontally. I have tried various CSS methods like margin auto, but none seem to work. If you could provide a solution and explain how it works, it would be greatly appreciated. ...