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

utilize dynamic variables in post-css with javascript

Question: Is it possible to dynamically set or change variables from JavaScript in post-css? I have a react component with CSS3 animations, and I want to set dynamic delays for each animation individually within each component. I've found a similar s ...

What is the best way to change the state of an Object?

I need to dynamically adjust the internalstatus based on the values of externalValues. If valueOne is true, then I want statusOne to be true. Similarly, if valueTwo is true, I want statusTwo to be true and statusOne to be false. const externalValues = { v ...

Error message indicating unauthorized access while trying to implement Backbone with Slim framework and Tuupola basic authentication

I've been working on connecting my Backbone app with my server API (using Slim) and have implemented Tuppola / Basic Auth Middleware to handle authentication. The setup is fairly simple, as I'm just trying to make it work. When I access the serv ...

Issues with ontimeupdate event not triggering in Chrome for HTML5 audio files

After creating an HTML5 audio element and setting a listener for when its time updates, I have run into an issue where the ontimeupdate function does not fire in Chrome, including Chrome on Android. The audio plays without any issues in other browsers. va ...

Is it necessary for TypeScript classes that are intended for use by other classes to be explicitly exported and imported?

Is it necessary to explicitly export and import all classes intended for use by other classes? After upgrading my project from Angular 8 to Angular 10, I encountered errors that were not present before. These issues may be attributed to poor design or a m ...

Tips for continuing code execution in an ajax success function following the completion of a nested ajax call within the success block

I am facing an issue with a function that utilizes $.ajax. In the success section of the function, I have three nested functions. The first one executes properly, but the second one contains another $.ajax call. While the internal $.ajax call works fine, t ...

Is it possible to enable auto-completion for IDs in a separate CSS file using WebStorm 7?

I am new to using WebStorm 7 and currently working on building a simple HTML/CSS website. Initially, I included my CSS within the HTML file using the style tag, but now I have decided to move it to a separate file. Auto completion is functioning for all h ...

Breaking down objects and setting default values

In need of assistance with resolving an issue related to default parameters and object destructuring. The 'product' object that I am working with has the following structure: { name: "Slip Dress", priceInCents: 8800, availableSizes ...

Is there a built-in event in Jquery UI tabs for when the tabs are collapsed?

Which event in jquery ui can I utilize to detect when a panel collapse has finished on the browser? I require this information to perform calculations based on the screen layout after the collapse has occurred. If I use the select or show event callbacks, ...

Gradually vanishing words while they glide across the screen

I want to achieve a similar effect seen in the game A Dark Room. The text in the game serves two purposes which I am trying to replicate: The new text is added above the old text instead of below it, pushing the older text down the page as the game progr ...

What is the best method to determine the mean score by utilizing the ID values obtained from API responses?

These are the responses retrieved from the API: const attractions = [ {"id": 1,"name": "drive on avenue"}, {"id": 2, "name": "diving"}, {"id": 3,"name": "visiting ma ...

The table's content extends beyond the confines of the page

I have an HTML page where I am embedding an SSRS report. The report extends beyond the page as shown in the image below: This is the table that is generated: <table cellpadding="0" cellspacing="0" id="ctl00_MainContent_FiveYearReportViewer_fixedTable" ...

Can node JS code be written on the client side in Meteor 1.3?

Is it feasible to write Node.js code on the client side of Meteor 1.3? I tried looking for information but couldn't locate any evidence. Previous inquiries didn't mention its availability, however, I recall reading that it would be possible start ...

What are some techniques for concealing a rendered element retrieved using the fetch API?

Currently, I am grappling with a coding challenge that requires me to extract data from https://jsonplaceholder.typicode.com/users using the fetch API function along with bootstrap and jquery. To display the data in a div element, I utilized the array.map( ...

Having trouble handling file uploads in Laravel via JQuery Ajax requests

When attempting to upload a CSV / Excel file and receiving it through an ajax request, the process is not functioning as anticipated. I employed a formdata object to upload the files in this manner: const formData = new FormData() formDa ...

Modify the readonly property of an input element in ReactJS

I am looking to manipulate attributes on an HTML input element. Here is what I have attempted: constructor(props) { super(props); this.state = {inputState: 'readOnly'}; } And within the render function: <input className="form-contr ...

How can I confirm if a class is an instance of a function-defined class?

I have been attempting to export a class that is defined within a function. In my attempts, I decided to declare the class export in the following way: export declare class GameCameraComponent extends GameObject { isMainCamera: boolean; } export abstra ...

What is causing the geolocation heading to remain "null" on Android devices when using Chrome?

Recently, I developed a compact geolocation watch using the following code snippet: navigator.geolocation.watchPosition( this.updateLocation.bind(this), this.errorLocation.bind(this), {enableHighAccuracy: true} ); The function updateLocation ...

More efficient methods for handling dates in JavaScript

I need help with a form that requires the user to input both a start date and an end date. I then need to calculate the status of these dates for display on the UI: If the dates are in the past, the status should be "DONE" If the dates are in the future, ...

"Learn the process of setting a variable in ng-model within an input field based on a specific condition

I need to dynamically assign an ng-model variable based on a condition. For instance: <input type="text" ng-model="item.model[multilang]" > The $scope.multilang variable can be set to either "ENG", "JP" (languages) or false. So, when multilang = "E ...