Click on the navigation bar buttons to toggle between different divs and display multiple information boxes simultaneously

Here is the current code snippet...

$("#contact").click(function() {
   if ( $( "#contact_div" ).length ) {
      $("#contact_div").remove();
   } else {
      var html='<div id="contact_div" class="contact-info"><p>Contact info</p></div>';
      $('body').append(html);
   }
   
});
$("#submission").click(function() {
   if ( $( "#submission_div" ).length ) {
      $("#submission_div").remove();
   } else {
      var html='<div id="submission_div" class="submission-methods"><p>submission methods</p></div>';
      $('body').append(html);
   }
});
$("#database").click(function() {
   if ( $( "#database_div" ).length ) {
      $("#database_div").remove();
   } else {
      var html='';
      $('body').append(html);
   }
});
$("#frequent").click(function() {
   if ( $( "#frequent_div" ).length ) {
      $("#frequent_div").remove();
   } else {
      var html='<div id="frequent_div" class="Freqeuent kick-codes"><p>frequent kick codes</p></div>';
      $('body').append(html);
   }
});
@charset "utf-8";
/* CSS Document */

body {
padding: 0px;
margin: 0px;
background-image: url("images/mark-athena-2.png");
background-color: #d4d4d4;

}

a {
text-decoration: none;
font-family: "blessed-facit-semibold", "arial Black", Arial;
color: #999999;
font-size: 12px;
padding: 14px;
}

nav {
background-color: #514a79;
height: 25px;
}

a:hover {
color:#e3e3f2;
}

/* color for link= #e3e3f2 */

div {
height: 100px;
width 150px;
border: solid 1px;
margin: 20px;
overflow: hidden;
background-color: #e6e6e6;

}
<!DOCTYPE html>
<html>
<head>
   <meta charset="utf-8" />
   <title>Accelorator</title>
   <link rel="stylesheet" href="CSS/accel-stylesheet.css">
<script type="text/javascript" src="https://code.jquery.com/jquery-2.2.0.js"></script>
<script type="text/javascript" src="js/cont.js"></script>

</head>

<body>
    <nav>
      <a href="#">Home</a>
      <a id="contact" href="#">Contact info</a>
      <a id="submission" href="#">Submission methods</a>
      <a id="database" href="#">Data base</a>
      <a id="frequent" href="#">Frequent kick codes</a>
    </nav>

    <div id="contact_div" class="contact-info">
       <p>Contact info</p> 
    </div>

    <div id="submission_div" class="submission-methods">
       <p>submission methods</p> 
    </div>

    <div id="frequent_div" class="Freqeuent kick-codes">
       <p>frequent kick codes</p> 
    </div>
</body>

</html>

I want to create a dynamic navigation structure where clicking on specific links toggles the display of corresponding content divs. Each div should stay displayed until toggled off by the same button that activated it.

This is my HTML markup for this project...

<!DOCTYPE html>
<html>
<head>
   <meta charset="utf-8" />
   <title>Accelorator</title>
   <link rel="stylesheet" href="CSS/accel-stylesheet.css">

</head>

<body>

    <nav>
      <a href="#">Home</a>
      <a href="#">Contact info</a>
      <a href="#">Submission methods</a>
      <a href="#">Data base</a>
      <a href="#">Frequent kick codes</a>

    </nav>

    <div class="contact-info">
       <p>Contact info</p> 
    </div>


    <div class="submission-methods">
       <p>submission methods</p> 
    </div>

    <div class="Freqeuent kick-codes">
       <p>frequent kick codes</p> 
    </div>

</body>

</html>

And here is my css

@charset "utf-8";
/* CSS Document */

body {
    padding: 0px;
    margin: 0px;
    background-color: #d4d4d4;
}

a {
    text-decoration: none;
    font-family: "blessed-facit-semibold", "arial Black", Arial;
    color: #999999;
    font-size: 12px;
    padding: 14px;
}

nav {
    background-color: #514a79;
    height: 25px;
}

a:hover {
    color:#e3e3f2;
}

    /* color for link= #e3e3f2 */

div {
    height: 100px;
    width 150px;
    border: solid 1px;
    margin: 20px;
    overflow: hidden;
    background-color: #e6e6e6;

}

Answer №1

To achieve this functionality, you can utilize the jQuery .toggle function. Comprehensive documentation and examples can be found here.

Assign an 'id' to each navigation anchor and implement a click event using jQuery to toggle the desired div. It is recommended to use an id for each anchor, but using a class is also possible.

The code snippet would look something like this:

<body>
    <nav>
      <a href="#">Home</a>
      <a id="contact" href="#">Contact info</a>
      <a id="submission" href="#">Submission methods</a>
      <a id="database" href="#">Data base</a>
      <a id="frequent" href="#">Frequent kick codes</a>
    </nav>

    <div id="contact_div" class="contact-info">
       <p>Contact info</p> 
    </div>

    <div id="submission_div" class="submission-methods">
       <p>Submission methods</p> 
    </div>

    <div id="frequent_div" class="frequent-kick-codes">
       <p>Frequent kick codes</p> 
    </div>
</body>

The corresponding jQuery/javascript code is as follows:

 $("#contact").click(function(){
    $("#contact_div").toggle();
 });
 $("#submission").click(function(){
    $("#submission_div").toggle();
 });
 $("#database").click(function(){
    $("#database_div").toggle();
 });
 $("#frequent").click(function(){
    $("#frequent_div").toggle();
 });

A couple of notes: 1. The original post was missing the database section. 2. It is essential to include jQuery on your page either by loading it from your server or via CDN. For example:

<script src="https://code.jquery.com/jquery-2.2.0.js"></script>

For the second requirement, where code blocks are to be added/removed based on clicks, some adjustments need to be made. The JavaScript method changes, and including jQuery correctly, sourcing the JavaScript code, and having a document.ready handler become crucial for a functional solution. Here is how the updated code looks (CSS remains unchanged):

<!DOCTYPE html>
<html>
<head>
   <meta charset="utf-8" />
   <title>Accelerator</title>
   <link rel="stylesheet" href="CSS/accel-stylesheet.css">
    <script type="text/javascript" src="https://code.jquery.com/jquery-2.2.0.js"></script>
    <script type="text/javascript" src="js/custom.js"></script>
    <script>
            $( document ).ready(function() {
               initialize();
            });
        </script>
</head>

<body>
    <nav>
      <a href="#">Home</a>
      <a id="contact" href="#">Contact info</a>
      <a id="submission" href="#">Submission methods</a>
      <a id="database" href="#">Data base</a>
      <a id="frequent" href="#">Frequent kick codes</a>
    </nav>

    <div id="contact_div" class="contact-info">
       <p>Contact info</p>
    </div>

    <div id="submission_div" class="submission-methods">
       <p>Submission methods</p>
    </div>

    <div id="frequent_div" class="frequent-kick-codes">
       <p>Frequent kick codes</p>
    </div>
</body>
</html>

The content of custom.js:

function initialize() {
    // Handle click events for various sections
    $("#contact").click(function() {
       if ( $( "#contact_div" ).length ) {
          $("#contact_div").remove(); // Remove existing div
       } else {
          var html='<div id="contact_div" class="contact-info"><p>Contact info</p></div>';
          $('body').append(html); // Add new div
       }
    });

    $("#submission").click(function() {
       // Similar logic for other sections
    });

    $("#database").click(function() {
       // Logic for handling database section
    });

    $("#frequent").click(function() {
       // Logic for frequent kick codes section
    });
}

Answer №2

Follow these steps to achieve this:

HTML

<nav>
  <a href="#">Home</a>
  <a href="#" data-container-class="contact-info">Contact info</a>
  <a href="#" data-container-class="submission-methods">Submission methods</a>
  <a href="#">Data base</a>
  <a href="#" data-container-class="frequent-kick-codes">Frequent kick codes</a>

</nav>

<div class="contact-info" data-container>
  <p>Contact info</p>
</div>


<div class="submission-methods" data-container>
  <p>Submission methods</p>
</div>

<div class="frequent-kick-codes" data-container>
  <p>Frequent kick codes</p>
</div>

JQuery

$(document).ready(function() {
  // Initially hide all container elements
  $('*[data-container]').hide();

  // Toggle visibility of the specific container element based on menu item click
  $('*[data-container-class]').click(function(e) {
    var className = $(this).data('container-class');
    $('.' + className).toggle();
  });
});

Check out this JSFiddle example

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

Obtain asynchronous result from updating state in React

I am trying to achieve the following: myFunction = () => { this.setState( state => { const originalBar = state.bar; return { foo: "bar" }; }, () => ({ originalBar, newBar: state.foo }) //return this object ...

Dynamic Checkbox Functionality in REACT

Motivation: My goal is to generate multiple rows with a variable number of checkboxes that will be managed by a useState hook. Challenge: The page freezes or displays constant loading, with no content visible. There are no console logs, and even the debug ...

React-router-sitemap lacks a definition for 'Require'

According to the official documentation here, this is how the sitemap-builder.js file should be structured: require('babel-register'); const router = require('./router').default; const Sitemap = require('../').default; ( ...

Utilize the power of Facebook login in your Parse client side application by integrating it with the user object

Currently, I am in the process of implementing a login system using both the Parse and Facebook Javascript SDK. While I have successfully implemented authentication on the client side, I am now facing the challenge of accessing the user object (generated ...

updating the v-model in Vue.js datepicker retains the previously set value while setting a new date

When using the template, the endDate updates as expected. However, there seems to be an issue when the filtersChanged method is called with the @selected attribute - the updated value is not the new one but rather the previously set value. <template&g ...

Encountering an error message stating that the "@font-face declaration does not adhere to the fontspring bulletproof syntax" while attempting to integrate a custom font

I've been struggling to incorporate a unique font into my website, but I keep encountering the same error every time. Despite my efforts, I haven't found much guidance on how to rectify this issue. Below is the code I'm using: @font-face ...

Ways to merge two arrays into one in React JS

Here are two arrays presented below: const arrayA = { 0: { id: XXXXXXX, name: "test" }, 1: { id: YYYYYYY, name: "example" } } const arrayB = { 0: { id: XXXXXXX, category: "sea", } 1: { id: YYYYY ...

When invoking Javascript, its behavior may vary depending on whether it is being called from a custom

Currently, I am in the process of implementing versioning capabilities to a custom entity called MFAs. However, I have encountered a peculiar issue. The problem arises from having a JavaScript web resource that is being invoked from two different locations ...

What can be done to ensure that two separate react-native Picker components do not interfere with each other's

Encountering an issue with two Pickers in a react-native View. Whenever I select a value in one Picker, it causes the other Picker to revert back to its initial item in the list. It seems like the onValueChange function is being triggered for both Pickers ...

Looking for an alternative to setOnLoadCallback()?

Currently, I'm working on an internal website and facing a challenge where I am unable to access Google's API for the setOnLoadCallback() function. I have tried looking for JQuery alternatives that could work with my locally hosted JQuery without ...

karma - Plugin not located

Attempting to run JS test cases using karma, but consistently receiving a plugin not found error. Oddly enough, the same configuration file works perfectly for one of my co-workers. Below are the logs: $ karma start karma.conf.js 04 10 2016 17:51:24.755 ...

Using Javascript to dynamically add and remove elements on click

Whenever I click on a link, I am able to generate input, label, and text. However, I want to be able to delete these elements with the next click event on the same link: I've tried updating my code like this: var addAnswer = (function() { var la ...

What is the abbreviated term for personalized elements in React Native development?

After discovering that custom components can be created like this: const CustomComp=()=>{ console.log('Created custom comp'); return(<View></View>); } export default function App(){ return(<View style={{flex:1}}> &l ...

The visibility of content that flickers on the webpage should be hidden with the display: none property during loading

Currently working on a new toy website, but encountering some unexpected behavior. On the homepage HTML file, there are two separate sets of <body> tags: <body class = "intro">...</body> <body class = "home">...</body& ...

Utilize the power of jQuery to easily toggle visibility of an overlay

I have successfully implemented JQuery to show and hide my overlay with great success. Now, I am interested in adding animations to enhance the user experience. After reviewing the jq documentation, I found some cool animations that can be easily integrate ...

Display hidden div with Jquery upon successful data retrieval

I am currently dealing with a script that requires the display of a DIV containing a small FORM only when a database query returns a result of 1 or more. The MySQL query responsible for checking data is functioning correctly and populates a variable calle ...

Is it possible to generate an array of strings from the keys of a type or interface?

Imagine a scenario where we have a type or interface defined as NumberLookupCriteria: type NumberLookupCriteria = { dialCode: string; phoneNumber: string; } or interface NumberLookupCriteria { dialCode: string; phoneNumber: string; } Is there a w ...

Select the radio button by hovering the mouse over it

Is there a way to check my radio buttons when hovering over them without having to click? I want to display photos based on the selected radio button. I attempted this using JQuery, but I am still learning and consider myself a beginner. ...

A guide on accessing information from nested arrays in JavaScript

I am having trouble retrieving data from a JavaScript array as it keeps showing undefined. Here is the code snippet: sabhaDetailsArrayTemp.forEach(element => { let arra = []; console.log(element) //return tmp.m_category_name ; arra = this.onSa ...

Heroku hosting a React/Node application that serves up index.html and index.js files, with a server actively running

It seems like the issue I'm facing is related to my start scripts. After researching online, I've come across various start scripts shared by different people. Some suggest using "start": "node index.js" -> (this doesn't start my server and ...