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

Automatically selecting the country phone code based on the country dropdown selection

When the country dropdown is changed, I want the corresponding phone code dropdown to be dynamically loaded. <div class="row"> <div class="col-sm-8 col-md-7 col-lg-6 col-xl-5 pr-0"> <div class="form-group py-2"> <l ...

Unlocking the secret to transferring information from POJO and Controller to Ajax

I have a situation where I am sending data from my controller as Json using the @ResponseBody annotation. Unfortunately, I am facing an issue where ajax is unable to recognize the data sent from my controller. When I check the typeof data in ajax, it shows ...

Inject a <div> element into a table row upon clicking a button using jQuery and PHP

I am faced with an issue regarding displaying pdf reports within specific table rows. The scenario involves a table containing folder paths and buttons in each row. Upon clicking the button, the path is sent to a sequence of PHP files (ajax.php, ajax2.php, ...

JQuery/JS function not functioning as expected

Creating HTML with jQuery to retrieve data from a web API. At the start of my script, I defined a function that checks the selected value of a dropdown and assigns it to a global variable. var $seldom; $(document).ready(function () { function chkdom() ...

What is the best way to adjust the width of a textarea based on its content

How can I dynamically set the width of a React Semantic UI textarea based on its content? Setting min-width doesn't seem to be working. Any suggestions? <Textarea key={idx} defaultValue={formattedText} className="customInpu ...

Automatic Numeration in Jquery with Ordered Lists

I am in the process of using JQuery to automatically number an OL list. My goal is to create a list that looks like this: apple 1.1 green apple 1.2 red apple 1.3 red apple orange 2.1 orange juice 2.2 etc Please assist me in achieving this. $(&a ...

The angular 5 application encountered an issue where it was unable to access the property 'singlePost' due to a null value, resulting

When using the once method to fetch data from the Firebase database, everything works correctly. However, when I try to use the on method, I encounter an error that says: ERROR TypeError: Cannot read property 'singlePost' of null. How can I prope ...

I'm facing some difficulties in sourcing my header into a component and encountering errors. Can anyone advise me on how to properly outsource my header?

Looking to streamline my headers in my Ionic 4 project by creating a separate reusable component for them. Here's how I set up my dashboard page with the header component: <ion-header> <app-header title="Dashboard"></app-he ...

Tips for effectively utilizing typescript interface with the OR operator

I'm a beginner when it comes to TypeScript. I have the following code snippet that I am working on: interface InitialData { active: boolean; status: boolean; } interface Item { id: number; name: string; Data: InitialData; } interface Main ...

"Angular-chart is throwing an error with an undefined $scope.chart

I am having trouble creating a chart with an onClick event that can retrieve the label that was clicked. After searching, I found and modified a solution. Here is my code snippet: $scope.chart; $scope.onClick = function (points, evt) { console.log(po ...

What is the best way to create a loop within a JavaScript function?

I'm having some trouble with looping inside a function. It seems like my looping is not working properly and I need help fixing it, along with suggestions for the problem. :) Here's what I've tried: <script> function getImage1( ...

What steps do I need to take to retrieve the passed slug in my API (slug=${params.slug})?

Is there a way for me to retrieve the passed slug in my API (slug=${params.slug}) while using the vercel AI SDK? const { messages, input, handleInputChange, handleSubmit, isLoading, error } = useChat({ api: `/api/conversation?slug=${params.slug ...

Is there a way to modify AJAX response HTML and seamlessly proceed with replacement using jQuery?

I am working on an AJAX function that retrieves new HTML content and updates the form data in response.html. However, there is a specific attribute that needs to be modified before the replacement can occur. Despite my best efforts, I have been struggling ...

Why am I getting the error in react-dom.development.js related to my index.js file?

Upon checking the console, the following message is displayed: react-dom.development.js:86 Warning: ReactDOM.render is no longer supported in React 18. Please use createRoot instead. Until you transition to the new API, your application will behave as if i ...

What steps should be followed to display an HTML page within an HTML div?

The question I have is a bit misleading, as I'm not looking for guidance on how to open an HTML document in a div. Rather, I am currently facing an issue where I am unable to replace the HTML file that I have already placed in a div. Initially, I pla ...

The XHR Get request fails to load the HTML content sent from the Express application

As I embark on building my inaugural express app, I have encountered a shift in sending requests from the front-end. Previously, all requests were initiated by anchor elements for GET requests and form elements for POST requests, with server responses hand ...

Building a like/dislike feature in Angular

Here is a snippet of code I have that includes like and dislike buttons with font-awesome icons: <ng-container *ngFor="let answer of question.answers"> <p class="answers">{{answer.text}} <i class="fa fa-hand-o-le ...

I encountered a SyntaxError that reads "Unexpected token instanceof" while using the Chrome Javascript console

I find it quite surprising that the code below, when entered into the Chrome JavaScript console: {} instanceof Object leads to the error message displayed below: Uncaught SyntaxError: Unexpected token instanceof Could someone kindly explain why this ...

Having Rails iterate through an element to display each item in my database table

In the process of creating a Rails app, I decided to utilize a hexagonal grid to display links to blog posts as image hexagons. Here is an example showcasing static posts: <ul id="hexGrid"> <li class="hex"> ...

The Joi validate() function will return a Promise instead of a value when used within an asynchronous function

Trying to understand how async functions and the Joi.validate() function behave. Below is a function used for validating user input. const Joi = require("joi"); const inputJoiSchema= Joi.object().keys({ name: Joi.string(), email: Joi.string().require ...