Tips for updating the content of a div with the click of another div

Is there a way to dynamically change the content of a div upon clicking on a menu item?

Here is the current layout for reference: https://i.stack.imgur.com/nOnlQ.png

Below is the CSS and HTML code snippet:


    body {
      background-color: #555657;
      margin: 20px;
    }
    
    /* Additional CSS rules here */
  

    <!-- Relevant HTML markup here -->
  

I am looking to switch the displayed div when a menu tab is clicked, but my attempt at using JavaScript has not been successful.

What would be the best approach to achieve this functionality?

Thank you in advance for your assistance and have a great day!

Answer №1

One way to enhance your website without relying on Javascript is by utilizing a pure CSS approach that incorporates the :target pseudo-class.

By structuring your content within the document and utilizing navigation links with fragment identifiers as their href attributes, you can maintain the core functionality of your page even in the absence of Javascript or CSS.

Check out this Codepen demo for reference


Markup Structure

<nav role="complementary">
    <ul role="tablist">
      <li role="tab" aria-controls="cnt1" id="tab1" aria-selected="true">
          <a href="#cnt1">Content 1</a></li>
      <li role="tab" aria-controls="cnt2" id="tab2" aria-selected="false">
          <a href="#cnt2">Content 2</a></li>
      <li role="tab" aria-controls="cnt3" id="tab3" aria-selected="false">
          <a href="#cnt3">Content 3</a></li>
      <li role="tab" aria-controls="cnt4" id="tab4" aria-selected="false">
          <a href="#cnt4">Content 4</a></li>
    </ul>
</nav>

<main>
   <section id="cnt1" aria-hidden="false" role="tabpanel" aria-labelledby="tab1">
     <h2>Content 1</h2> 
     <p>This is a lorem ipsum text.</p>
   </section>
   <section id="cnt2" aria-hidden="true" role="tabpanel" aria-labelledby="tab2">
     <h2>Content 2</h2>   
     <p>I am the content of link #2</p>
   </section>
   <section id="cnt3" aria-hidden="true" role="tabpanel" aria-labelledby="tab3">
     <h2>Content 3</h2>    
     <p>Here's another piece of content.</p>
   </section>
   <section id="cnt4" aria-hidden="true" role="tabpanel" aria-labelledby="tab4">
     <h2>Content 4</h2>    
     <p>And that wraps it up!</p>
   </section>

</main>

CSS Styling (relevant part)

body { display: flex; }

main { 
  flex: 1; 
  align-self: stretch; 
  position: relative; }

ul  { list-style: none; }

nav { align-self: flex-start; }

[role="tabpanel"] {
  position: absolute;
  transition: .25s opacity;
  background: #fff;
  padding: 0 20px;
  left: 0; right: 0; top: 0; bottom: 0;
  opacity: 0; }

[role="tabpanel"]:first-of-type { opacity: .99; }
[role="tabpanel"]:target { opacity: 1; }

Through a straightforward CSS transition, you can seamlessly alter the appearance of your content.

It's worth noting the inclusion of role and aria-* attributes, making this type of navigation closely resemble a tab/tabpanels widget.

Despite the absence of Javascript in this scenario, its implementation could significantly improve the accessibility of your content. For instance, using a transitionend event to detect visible sections based on opacity values and adjusting relevant aria-* attributes can greatly benefit users relying on assistive technology.

Javascript Functionality
(purely for enhancing accessibility)

var _gcs = window.getComputedStyle;
var _sections = document.querySelectorAll('[role="tabpanel"]');
var _tabs = document.querySelectorAll('[role="tab"]');

var _setARIAAttributes = () => {
  var currentHash;

  /* Update aria-hidden attribute for panels */
  [..._sections].forEach( ( s ) => {
        var hidden = +( _gcs( s ).getPropertyValue( 'opacity' ) ) < 1;
        s.setAttribute( 'aria-hidden', hidden);  
        if (!hidden) currentHash = s.id;
  }); 

  /* Update aria-controls attribute for tabs */
  [..._tabs].forEach( ( t ) => {
        var selected = t.getAttribute( 'aria-controls' ) === currentHash;
        t.setAttribute( 'aria-selected', selected );  
  }); 
}

if (!!location.hash) { _setARIAAttributes() }
window.addEventListener('transitionend', () => { _setARIAAttributes(); });

Answer №2

 <p>This is a unique HTML code that showcases a portfolio for FIEVEZ Clément.</p>
    <!DOCTYPE html>
        <html lang="fr">

        <head>
        <meta charset="utf-8" />
        <title>portfolio FIEVEZ Clément</title>
        <link type="text/css" rel="stylesheet" href="boostrap/css/bootstrap.min.css">
        <link rel="stylesheet" href="css/styles.css"/>
            <style>
    body{
    background-color: #555657;
    margin: 20px;
    }

    /* CADRE PARENT */
    #global{

    }
    /* CADRE 1 */
    #cadre1{
    float: left;
    width: 250px;
    }
    #cadre1 span{
    color : #33A7FF;
    }

    /* CADRE 2 */
    #cadre2{
    color : #2370AB;
    }
    #menu, #menu ul{
    padding:0;
    margin:0;
    list-style:none;
    text-align:center;
    }
    #menu li{
    display:block;
    position:relative;
    background-color: #2370AB;
    }
    #menu li ul li{
    background-color: white;
    text-align:center;
    }
    #menu ul li{
    display:inherit;
    border-radius:0;
    }
    #menu ul li:hover{
    border-radius:0;
    }
    #menu ul li:last-child{
    border-radius:0 0 8px 8px;
    }
    #menu ul{
    position:absolute;
    z-index: 1000;
    max-height:0;
    left: 0;
    right: 0;
    overflow:hidden;
    -moz-transition: .8s all .3s;
    -webkit-transition: .8s all .3s;
    transition: .8s all .3s;
    }
    #menu li:hover ul{
    max-height:15em;
    }
    #menu a{
    display:block;
    padding:8px 32px;
    color:#fff;
    }
    #menu ul a{
    padding:8px 0;
    }
    #menu li:hover a, #menu li li:hover a{
    color:#000;
    }


    /* CADRE 3 */
    #div_profil{
    display: block;
    height: 625px;
    background-color : white;
    overflow: auto;
    }

    #div_experience{
    display: none;
    height: 625px;
    background-color : white;
    overflow: auto;
    }

    #div_projet{
    display: none;
    height: 625px;
    background-color : white;
    overflow: auto;
    }

    #div_contact{
    display: none;
    height: 625px;
    background-color : white;
    overflow: auto;
    }

    /* FOOTER */
    #footer{
    position: fixed;
    bottom: 20px;
    background-color: #2370AB;
    text-align: center;
    }
</style>
        </head>

        <body>
        <!--CADRE PRINCIPAL-->
        <div class="row"  id="global">

        <!--INFO BASIQUE-->
        <div class="col-sm-3" id="cadre1">
        <img src="images/myAvatar.png" alt="avatar" id="avatar"/>
            <p><span>Nom :</span> FIEVEZ</p>
            <p><span>Prénom :</span> Clément (René)</p>
            <p><span>Date de naissance / Age :</span> né le 22 janvier 1996, 22ans</p>
            <p><span>Lieu de naissance :</span> DENAIN (059)</p>
            <p><span>Adresse :</span> 85 rue magenta, 53000 LAVAL</p>
        </div>
        
         <!--MENU-->
        <div class="col-sm-3" id="cadre2">
        <ul id="menu">
        <li><a href="#Profil" onclick="div2('div_profil')">Profil</a>
        </li>
        <li><a id="btn_experience" href="#Experience" onclick="div2('div_experience')">Expérience</a>
        </li>
        <li><a href="#Projets" onclick="div2('div_projet')">Projets</a>
        <ul>
        <li><a href="#Projet1">Projet 1</a></li>
        <li><a href="#Projet2">Projet 2</a></li>
        <li><a href="#Projet3">Projet 3</a></li>
        <li><a href="#Projet4">projet 4</a></li>
        </ul>
        </li>
        <li><a href="#Contact" onclick="div2('div_contact')">Contact</a>
        </li>
        </ul>
        </div>
        
        <!--CADRE CHANGEANT-->
        <div class="col-sm-5" id="div_profil" >
        <p>Et Epigonus quidem amictu tenus philosophus, ut apparuit, prece frustra temptata, sulcatis lateribus mortisque metu admoto turpi confessione cogitatorum socium, quae nulla erant, fuisse firmavit cum nec vidisset quicquam nec audisset penitus expers forensium rerum; Eusebius vero obiecta fidentius negans, suspensus in eodem gradu constantiae stetit latrocinium illud esse, non iudicium clamans.
        </p>
        </div>

        <div class="col-sm-5" id="div_experience">
        <p>div experience</p>
        </div>

        <div class="col-sm-5" id="div_projet">
        <p>div projet</p>
        </div>

        <div class="col-sm-5" id="div_contact">
        <p>div contact</p>
        </div>
        
        </div>
        
        <footer class="col-sm-12" id="footer">
        <div>
        <p class="copyright">Tout droit reservé. FIEVEZ Corps.</p>
        </div>
        </footer>

        <script>
                function div2(name)
                {
                document.getElementById("div_profil").style.display="none";
                document.getElementById("div_experience").style.display="none";
                document.getElementById("div_projet").style.display="none";
                document.getElementById("div_contact").style.display="none";

                document.getElementById(name).style.display="block";
                }
                </script>
          </body>
        </html>

Answer №3

Here is a creative solution that I came up with... codepen

HTML

    <a id='1' onclick='myFunction("1");'>Click me 1</a><br/>
    <a id='2' onclick='myFunction("2");'>Click me 2</a><br/>
    <a id='3' onclick='myFunction("3");'>Click me 3</a><br/>
    <a id='4' onclick='myFunction("4");'>Click me 4</a><br/>
    <div id='addText'>
    </div>

Javascript

<script>
function myFunction(id){
  x = document.getElementById("addText");
  if(id == 1){
    x.innerHTML = 'Greetings'
    x.style.color = "blue";
  } else if(id == 2){
    x.innerHTML = 'Hey there'
    x.style.color = "blue";
  } else if(id ==3){
    x.innerHTML = 'Option 3 text'
    x.style.color = "blue";
  }else{
    x.innerHTML = 'Farewell'
    x.style.color = "blue";
  }
}

</script>

All the design work is left to your creativity, feel free to adjust this solution according to your specific needs.

Answer №4

Just a little further, now you just need to incorporate some flag related to any container div along with a link that corresponds to the specific div, for example:

// if your HTML markup has multiple links, give this a try

<ul>
<li><a href="#whatever" data-url="div_profile">My Profile</a></li>
<li><a href="#whatever2" data-url="div_experience">My Experience</a></li>
</ul>

<div>
<div class="content active" id="div_profile">Display your profile content here</div>
<div class="content" id="div_experience">Show your experience content here</div>
</div>

After that, you'll need to add some JavaScript code to make it work:

// Grab all the links within the menu div
var links = document.getElementById('menu').getElementsByTagName('a');

// Get the last shown div
var lastShownDiv = getActiveDiv();
for(var i = 0; i < links.length; i++) {
var currentLink = links[i];
currentLink.addEventListener('click', function(event){
var link = this;
var targetDiv = link.getAttribute('data-url');

if (lastShownDiv) {
removeClassName(lastShownDiv, 'active');
}

lastShownDiv = document.getElementById(targetDiv);
addClassName(lastShownDiv, 'active');
}, false);
}

function addClassName(element, classname) {
if (!element) {
return;
}

var classlists = element.className.split(' ');
classlists.push(classname);
element.className = classlists.join(' ');
}

function removeClassName(element, classname) {
if (!element) {
return;
}
var classlists = element.className.split(' ');
var indexOfClassName = classlists.indexOf(classname);
if (indexOfClassName > -1) {
classlists.splice(indexOfClassName, 1);
}
element.className = classlists.join(' ');
}

function getActiveDiv() {
var actives = document.getElementsByClassName('active');
for(var i = 0; i < actives.length; i++) {
return actives[i];
}
}
// CSS styles have been modified and updated as well 
body {
      background-color: #555657;
      margin: 20px;
    }

    // Styles for different sections of the webpage

.content {
display: none;
}

.content.active {
display: block;
}

    // Specific styles for various content sections
    #div_profil {
      height: 625px;
      background-color: white;
      overflow: auto;
    }

    #div_experience {
      height: 625px;
      background-color: white;
      overflow: auto;
    }

    #div_projet {
      height: 625px;
      background-color: white;
      overflow: auto;
    }

    #div_contact {
      height: 625px;
      background-color: white;
      overflow: auto;
    }


    // Footer styles

    #footer {
      position: fixed;
      bottom: 20px;
      background-color: #2370AB;
      text-align: center;
    }
<!DOCTYPE html>
    <html lang="fr">

    <head>
      <meta charset="utf-8" />
      <title>portfolio FIEVEZ Clément</title>
      <link type="text/css" rel="stylesheet" href="boostrap/css/bootstrap.min.css">
      <link rel="stylesheet" href="css/styles.css" />
    </head>

    <body>
      <!--MAIN FRAME-->
      <div class="row" id="global">

        <!--BASIC INFO-->
        <div class="col-sm-3" id="cadre1">
          <img src="images/myAvatar.png" alt="avatar" id="avatar" />
          <p><span>Name:</span> FIEVEZ</p>
          <p><span>First Name:</span> Clément (René)</p>
          <p><span>Date of Birth/Age:</span> born on January 22, 1996, 22 years old</p>
          <p><span>Place of Birth:</span> DENAIN (059)</p>
          <p><span>Address:</span> 85 rue magenta, 53000 LAVAL</p>
        </div>

        <!--MENU-->
        <div class="col-sm-3" id="cadre2">
          <ul id="menu">
            <li><a href="#Profil" data-url="div_profil">Profile</a>
            </li>
            <li><a id="btn_experience" href="#Experience" data-url="div_experience">Experience</a>
            </li>
            <li><a href="#Projects" data-url="div_projet">Projects</a>
              <ul>
                <li><a href="#Project1">Project 1</a></li>
                <li><a href="#Project2">Project 2</a></li>
                <li><a href="#Project3">Project 3</a></li>
                <li><a href="#Project4">project 4</a></li>
              </ul>
            </li>
            <li><a href="#Contact" data-url="div_contact">Contact</a>
            </li>
          </ul>
        </div>

        <!--CHANGING CONTENT-->
        <div class="col-sm-5 content active" id="div_profil">
          <p>And Epigonus indeed was in appearance a philosopher even to old age openly pleading with reason not the obscurity of his initiation but defending by argument what he thought true, while disguised under a tawdry paraphernalia cords of baldric only serve through
            terror strictly applied to outface every one, nor had Eusebius other ground whereon to deny these charges against him.</p>
        </div>

        <div class="col-sm-5 content" id="div_experience">
          <p>div experience</p>
        </div>

        <div class="col-sm-5 content" id="div_projet">
          <p>div project</p>
        </div>

        <div class="col-sm-5 content" id="div_contact">
          <p>div contact</p>
        </div>

      </div>

      <footer class="col-sm-12 content" id="footer">
        <div>
          <p class="copyright">All Rights Reserved. FIEVEZ Company.</p>
        </div>
      </footer>

    </body>

    </html>

The above code has been enhanced with updates to assist you in resolving your issue effectively.

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

Generate a fresh object if the values within the TypeScript object are identical

How can I filter an object to return a new object containing elements with the same values? For example: allValues = {"id1": 3, "id2": 4, "id3": 3} The desired output is: filteredValues = {"id1": 3, "id3": 3} This is because the keys "id1" and "id3" hav ...

What is the best way to include an object within an array that is a property of another object in React.js?

Greetings, I apologize for the somewhat ambiguous title. It was a challenge to find a clearer way to express my thoughts. Currently, I am engrossed in my personal project and have encountered a particular issue. I would greatly appreciate any advice or gu ...

Saving vast array in MongoDB

I am currently working on a personal project that involves implementing a search feature. My setup includes using typeahead.js with a REST api created in expressJS and mongoDB. I could use some guidance on two particular challenges I am facing. While my ba ...

Utilizing AngularJS, implement ng-form and ng-repeat to seamlessly handle input validation and submission actions

Angular 1.6.2 I am experimenting with iterating over elements of a collection inputted by the user, checking their validity, and enabling the submit action if validation passes. I have tried using ng-form for this purpose and have come up with two differ ...

Making API calls using JavaScript

I'm struggling with understanding how to approach this problem in javascript. Here is the question along with the details. I would appreciate any assistance. QUERY We have a server backend that provides two endpoints: /GetLocalPressReleases and /Get ...

Submitting data twice through AJAX POST requests

Using a PHP file called via AJAX to insert data into MySQL. Prior to the insert statement, the PHP code runs a select query to check for duplicate records and then proceeds with the insert statement. Problem: When calling the PHP file from AJAX, it gets ...

Creating new components within A-frame

I've been attempting to implement the bubble function into my scene to generate a sphere, but unfortunately nothing is showing up. Even when I try creating a sphere without using the bubble function, it still doesn't appear in the scene. func ...

Transforming an HTML jQuery contact form into an ASP.NET solution

I have developed a contact form using HTML5, Bootstrap, and jQuery. The form includes hidden fields that are only displayed when the user selects a radio button. I have implemented validation to ensure that the hidden fields are not required to be filled o ...

Looping through the ajax data to populate ion-item elements

I am currently working on a loop that retrieves user IDs, names, etc. from a JSON file. I am trying to display this data in a list view within an Ionic framework. When I simply use direct alerts in JavaScript, the users are displayed correctly, but when I ...

Solving the default font problem in Laravel

I've been working on a project using Laravel and Bootstrap 4. Recently, I decided to switch from the default Laravel font, Nunito, to Lato. So, I made the necessary changes in my app.css file: @import url(https://fonts.googleapis.com/css?family=Nun ...

Gatsby's build process encounters a stumbling block when webpack fails due to issues

Every time I try to run gatsby build, an error pops up: failed Building static HTML for pages - 10.179s ERROR #95313 Building static HTML failed Refer to our documentation page for more details on this issue: https://gatsby.dev/debug-html 343 | ...

Converting Large XLSX File (over 600MB) to CSV Using Node.js

Currently, I am facing an issue with converting a large XLSX file, which is over 600mb in size, to CSV format. The conversion process works perfectly fine with smaller files that are less than 3MB. However, when it comes to larger files, the program star ...

Learn the art of blurring elements upon clicking in Vue

I've been attempting to trigger the blur event on an element when it is clicked, but I haven't been able to locate any helpful examples online. My initial approach looked like this: <a @click="this.blur">Click Me</a> Unfortunately, ...

What advantages does KnockoutJS offer over AngularJS?

Can KnockoutJS offer a unique feature that rivals or exceeds those of AngularJS? ...

What is the method to include a CoffeeScript file in my project?

Currently, I am attempting to follow the steps outlined in this CoffeScript tutorial. After opening the terminal and navigating to the directory where simpleMath.coffee is located, I proceeded to run node and entered var SimpleMath = require('./simpl ...

Update the value of input within a Struts2 iterator by utilizing JavaScript

As a junior programmer, I am trying to update the value of an input type text within a Struts2 iterator without refreshing the entire page. I believe using JSON could be a solution for this issue. Here is my JSP code: <input type="text" name="cantidad ...

Enhancing the Appearance of HTML Select Dropdowns in JavaFX 2.2 WebEngine

I am currently working on a project that is unable to be updated to Java 1.8 to support the latest JavaFX version. While this may or may not impact the issue I am facing, I have been exploring various solutions from the internet to customize the look and f ...

I'm curious about the process behind this. Can I copy a Figma component from a website and transfer it into my

Check out this site for an example: Interested in how uikit.co/explore functions? By hovering over any file, a copy button will appear allowing you to easily paste it into your Figma artboard. Want to know how this works and how to implement it on your o ...

Tips for changing the dimensions of the canvas?

I'm struggling to display a photo captured from the webcam. The sizes are not matching up, and I can't pinpoint where the size is defined in the code. https://i.stack.imgur.com/Is921.png The camera view is on the left, while the photo should be ...

Combining res.render and redirect in Express.js for efficient rendering and redirection

I am currently developing a web application that involves setting up routes for user authentication. The Challenge: After a successful registration, I want to redirect the user to /login page while also including render options. However, when I use render ...