What is the best way to show only one div at a time when selecting from navbar buttons?

To only display the appropriate div when clicking a button on the left navbar and hide all others, you can use this code:

For example:

  • If "Profile" is clicked in the left navbar, the My Profile Form div will be displayed (and all others will remain hidden).
  • If "My Properties" is clicked in the left navbar, the My Properties div will be displayed (and all others will remain hidden).
  • And so on for the rest of the buttons.

To accomplish this, you can utilize the following JavaScript:


const ProfileForm = document.getElementById('profile_container');
const ProfileButton = document.getElementById('profile_id');
const PropertiesForm = document.getElementById('my_properties_container');
const BidsForm = document.getElementById('my_bids');
const UtilitiesForm = document.getElementById('my_utilities');
const FavouritesForm = document.getElementById('my_favourites');
const MessagesForm = document.getElementById('my_messages');
const SettingsForm = document.getElementById('my_settings');

document.body.addEventListener('click', e => {
  if (e.target == ProfileButton) {
    ProfileForm.style.display = 'block'
  } else { /*ProfileForm.style.display='none'*/ }
})

In order to style your elements appropriately, here's an example snippet of CSS:


@import url('https://fonts.googleapis.com/css2?family=Roboto&display=swap');
/* Your CSS styles here */

Make sure to include these scripts and stylesheet links in the head section of your HTML file:


<script src="https://kit.fontawesome.com/99c0db90d1.js" crossorigin="anonymous"></script>
<link rel="shortcut icon" type="image/jpg" href="images/33.png" />
<meta charset="UTF-8">
<link rel="stylesheet" href="styles.css">
<link href="/css/all.css" rel="stylesheet">

Answer №1

If you want to enhance your dashboard_buttons, I recommend utilizing the dataset property for each button. For example, for the first button linked to the profile container, you could include a property like this:

<li class="dashboard_buttons" id="profile_id" data-id="profile_container"

Here, the data-id attribute represents the id of the element you wish to display.

By using this approach, your event listener will transform into:

document.body.addEventListener('click', function (e) {
    var eleToDislay = '#' + e.target.dataset.id; // get id of element to display
    $('.right_content .profile_container').hide();  // hide all previous elements...
    $(eleToDislay).show();  // show correct element....
})

You might also want to explore incorporating a full jQuery event listener instead of:

document.body.addEventListener('click', function (e) {

So it becomes:

$(document).on('click', function (e) {

The converted snippet would look like this:

$(document).on('click', function (e) {
    var eleToDislay = '#' + e.target.dataset.id;
    $('.right_content .profile_container').hide();
    $(eleToDislay).show();
})
@import url('https://fonts.googleapis.com/css2?family=Roboto&display=swap');
@import url('https://fonts.googleapis.com/css2?family=Lato&display=swap');

* {
    margin: 0;
    padding: 0;
    /*    border: thick solid blue;*/
    font-family: 'Roboto', sans-serif;
}

html {
    height: 100%;
    /*border: thick solid yellow;*/
}

body {
    height: 100%;
    /*    width: 100%;*/
    display: flex;
    flex-direction: column;
    /*border: thick solid red;*/
    visibility: visible;
    /*background-color: #003580;*/
}

/*BUTTON BACKGROUND COLORS*/

.header_right_container_inner_center_button,
.header_right_container_inner_right_button {
    background-color: #febb02;
}

/*BUTTON HOVER COLORS*/

.header_right_container_inner_right_button:hover,
.header_right_container_inner_center_button:hover {
    background: #003580;
    color: white;
}

/* BUTTON FONT COLORS*/

.header_right_container_inner_center_button,
.header_right_container_inner_right_button {
    color: black;
}

a {
    text-decoration: none;
}

.logo {
    /*border: thick dotted blue;*/
    width: 120px;
    margin-top: -33%;
    margin-bottom: -33%;
    /*border-radius:50%;*/
}

/* HEADER START */

header {
    display: flex;
    /*    border: thick solid red;*/
    justify-content: center;
    border-bottom: thin solid black;
    padding: 9px;
    background-color: #003580;
}

/* HEADER LEFT SIDE */

.header_left_container {
    display: flex;
...
</div>
</div>

Answer №2

Storing the button index and showing corresponding div, while hiding other divs with `display:block`.

This solution is effective and functional.

const ProfileForm = document.getElementsByClassName('profile_container');

const dash = document.getElementsByClassName('dashboard_buttons');
var index;
var array = [];
for (var i = 0; i < dash.length; i++) {

  array.push(dash[i]);

  dash[i].onclick = function() {
    index = array.indexOf(this);

    ProfileForm[index].style.display = "block";

    var check = ProfileForm[index];

    for (var i = 0; i < ProfileForm.length; i++) {
      if (ProfileForm[i].style.display == "block" && ProfileForm[i] != check) {
        ProfileForm[i].style.display = "none";
      }
    }
  }

}
@import url('https://fonts.googleapis.com/css2?family=Roboto&display=swap');
@import url('https://fonts.googleapis.com/css2?family=Lato&display=swap');
* {
  margin: 0;
  padding: 0;
  /*    border: thick solid blue;*/
  font-family: 'Roboto', sans-serif;
}

html {
  height: 100%;
  /*border: thick solid yellow;*/
}

body {
  height: 100%;
  /*    width: 100%;*/
  display: flex;
  flex-direction: column;
  /*border: thick solid red;*/
  visibility: visible;
  /*background-color: #003580;*/
}


/*BUTTON BACKGROUND COLORS*/

.header_right_container_inner_center_button,
.header_right_container_inner_right_button {
  background-color: #febb02;
}


/*BUTTON HOVER COLORS*/

.header_right_container_inner_right_button:hover,
.header_right_container_inner_center_button:hover {
  background: #003580;
  color: white;
}


/* BUTTON FONT COLORS*/

.header_right_container_inner_center_button,
.header_right_container_inner_right_button {
  color: black;
}

a {
  text-decoration: none;
}

.logo {
  /*border: thick dotted blue;*/
  width: 120px;
  margin-top: -33%;
  margin-bottom: -33%;
  /*border-radius:50%;*/
}


/* HEADER START */

header {
  display: flex;
  /*    border: thick solid red;*/
  justify-content: center;
  border-bottom: thin solid black;
  padding: 9px;
  background-color: #003580;
}


/* HEADER LEFT SIDE */

.header_left_container {
  display: flex;
  flex: 1;
  /*    border: thick solid yellow;*/
  justify-content: center;
}

.header_left_container_inner_left {
  /*    border: thick solid green;*/
  display: flex;
  flex: 1;
  align-items: center;
  justify-content: center;
}

.header_left_container_inner_right {
  /*    border: thick solid green;*/
  display: flex;
  flex: 5;
  align-items: center;
  justify-content: flex-start;
}


/* HEADER RIGHT SIDE */

.header_right_container {
  display: flex;
  flex: 3;
  /*    border: thick solid yellow;*/
  justify-content: center;
}

.header_right_container_inner_left {
  display: flex;
  /*    border: thick solid green;*/
  flex: 4;
  justify-content: flex-end;
  align-items: center;
  flex-wrap: nowrap;
}

li {
  /*    display:inline;*/
  padding: 10px;
}

a {
  display: flex;
  flex-wrap: nowrap;
  color: white;
  font-size: 12px;
}

.search_input_input {
  flex: 1;
  color: white;
  background-color: #003580;
  margin: 0;
  border: 0px;
  border-radius: 6px;
  font-size: 15px;
  font-weight: 333;
  height: 45px;
  text-align: center;
  resize: none;
  outline: none;
  cursor: pointer;
  width: 99px;
}

.search_input_widget {
  display: flex;
  flex-wrap: nowrap;
  justify-content: center;
  align-items: center;
  color: white;
  background-color: #003580;
  margin: 0;
  padding-left: 6%;
  border: 0;
  text-align: center;
  cursor: pointer;
  width: 120px;
}

.header_right_container_inner_left_list {
  display: flex;
  flex: 1;
  justify-content: flex-end;
  list-style-type: none;
}

.header_right_container_inner_center {
  display: flex;
  /*    border: thick solid green;*/
  flex: 1;
  justify-content: flex-end;
}

.header_right_container_inner_center_button {
  display: flex;
  align-items: center;
  /*    background-color: #E00000;*/
  border: 1px solid #003580;
  border-radius: 6px;
  padding: 0 25px;
  margin-left: 12px;
  /*    color: white;*/
  font-size: 15px;
  font-weight: 333;
  text-decoration: none;
  cursor: pointer;
  white-space: nowrap;
  resize: none;
  outline: none;
}

.header_right_container_inner_right {
  display: flex;
  /*    border: thick solid green;*/
  flex: 1;
  justify-content: center;
}

.header_right_container_inner_right_button {
  display: flex;
  align-items: center;
  background-color: #febb02;
  border: 1px solid #003580;
  border-radius: 6px;
  padding: 0 25px;
  margin-left: 12px;
  color: black;
  font-size: 15px;
  font-weight: 333;
  text-decoration: none;
  cursor: pointer;
  white-space: nowrap;
  resize: none;
  outline: none;
}

select.select_city_header {
  border: 1px solid #fff;
  /*    background-color: rgba(255,255,255,.5);*/
  padding: 5px;
  margin-left: 15px;
  background-color: #003580;
  color: white;
  font-size: 12px;
}

.main_dashboard_container {
  display: flex;
  flex-wrap: nowrap;
}

.left_navbar {
  height: 90vh;
  flex: 1;
  background-color: #003580;
  border-bottom: 6px solid #003580;
}

.dashboard_buttons {
  font-family: 'Lato', sans-serif;
  padding: 12px 50px;
  font-size: 16px;
  font-weight: 500;
  border-bottom: thin solid black;
  cursor: pointer;
  background-color: #003580;
  color: white;
}

.dashboard_buttons:hover {
  background-color: #39CCCC;
  color: white;
}

.dashboard_right_container_wrap {
  position: absolute;
  /*margin-top: 21%;*/
  overflow: auto;
}

.right_content {
  flex: 4;
  background-color: white;
  display: flex;
  justify-content: center;
  align-items: flex-end;
  /*margin-top: 1467px;*/
}

.profile_container {
  margin-bottom: 18%;
  /*position: absolute;*/
  /*display: flex;*/
  /*flex-direction: column;*/
  /*justify-content: flex-start;*/
  /*align-items: center;*/
}

.profile_title {
  text-align: center;
  font-size: 33px;
  font-weight: 333;
  color: #003580;
  padding: 12px;
}

.profile_form {
.

...
</body>

</html>

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

In search of a comprehensive demonstration of how to use JQuery/Ajax for pinging with success and failure detection

Given that the process is asynchronous with multiple requests happening in parallel, I would like a solution that can handle these requests and identify which success/failure corresponds to each specific request. I am considering utilizing the jqXHR Object ...

What is the process for converting a link into an image for embedding?

Looking to implement a new feature on beta.peaksneak.com that allows users to create journals with multimedia content. The goal is for users to be able to add images, videos, quotes, and links to their journal entries. After some research, I discovered th ...

Unable to display "xyz" using console.log() function upon button click

Why isn't the JavaScript function being executed in this code snippet? <form> <select type="text" name="month" id="month"> <option value="01">January</option> <option value="02">February</option> ...

Struggling with a malfunctioning Bootstrap dropdown that refuses to drop down

I've been working on a VueJS single-page application, but I can't seem to get the dropdown feature to work. I've followed the instructions from the Bootstrap guide and tried everything they recommended, but it just won't cooperate. Can ...

What steps are involved in uploading data to serve as a filter while running a PHP script to retrieve data from an SQL database?

Currently, I am retrieving data from a PHP file using miniAjax. The code snippet below demonstrates how the process begins: microAjax("genjsonphp.php", function(data) { var json = JSON.parse(data); var points = json; //code continues In the c ...

What is the best way to handle responses in axios when dealing with APIs that stream data using Server-Sent Events (S

Environment: web browser, javascript. I am looking to utilize the post method to interact with a Server-Send Events (SSE) API such as: curl https://api.openai.com/v1/completions \ -H "Content-Type: application/json" \ -H ...

Consistent Errors with AJAX POST Requests Despite CORS Enablement

Here is a function I have created for making an ajax post request: function POST(url, data) { $.ajax({ 'type' : "POST", 'url' : url, 'data' : data, headers : { 'Access-Cont ...

Text alignment post-rotation

Whenever I rotate a span, the text inside does not align horizontally. As shown in the example below, we are facing alignment issues with three rotated spans. body{ padding-left:10px; } .bordered{ border-left: 2px solid gray; position: relative ...

Fetching a Wikipedia page using AJAX or the fetch() method

I am currently attempting to dynamically retrieve a Wikipedia webpage within the browser in order to utilize XSLTProcessor for further processing of the XHTML content. Unfortunately, my efforts have been unsuccessful as Wikipedia is not sending the necess ...

modify the inherent CSS property

I am working with a component that I have inherited, including its CSS style, and I need to modify one of its properties. Current CSS: .captcha-main-image { width: 100%; height: auto; } <img class ="captcha-main-image" id="captchaImage" src= ...

Combining an Angular factory with another factory

I'm facing some difficulties with injecting one factory into another. The error message I'm getting is: `ReferenceError: testDataService is not defined` I thought it would be a simple issue to resolve, but it's turning out to be quite c ...

What are the steps to troubleshoot a Vue application?

I've encountered an issue with a code snippet that retrieves JSON data from a RESTful API. The code only displays the .container element and reports that the items array is empty, even though no errors are being shown. I attempted to debug the problem ...

What is the reason behind negative numbers appearing as "5-" rather than "-5" in the basic calculator coded using HTML and JavaScript?

As I am practicing my coding skills, I encountered an interesting issue. Any operation that results in a negative number displays as wrong, but when using console.logs it shows the correct result. Can someone explain why this is happening? <!DOCTYPE h ...

A guide on detecting overflow in a React functional component

I am in search of a way to determine if a div contains overflowing text and display a "show more" link if it does. While researching, I came across an insightful Stack Overflow answer on checking for overflow in a div. The answer suggests implementing a fu ...

Utilizing the keyword 'this' within a function of a JavaScript class that is invoked with the .map method

I am working with the RegisterUser class which contains various methods and properties: class RegisterUser { constructor(username, password, ispublic){ this.username = username; this.password = password; this.ispublic = ispublic; this.id ...

How can I utilize the pick parameter in nuxtjs3 useFetch for selecting arrays or performing a deep pick?

Currently working on my nuxtjs3 project, where I am extracting data from an API. Specifically using jsonPlaceholder for this task. Extracting data from a single object is not a problem: const { data: useFetchOnly } = await useFetch('https://jsonplace ...

Is it Possible to Insert Function from a For... in Loop?

Question: How is a function being attached to a variable's memory space without being explicitly assigned? Situation: I have developed a script to eliminate duplicate objects by comparing the values of object keys. However, after initializing the che ...

What is the best way to spin an element around its center?

I'm faced with a challenge where I have an element that needs to be rotated using JavaScript. The rotation is currently functional, but it's rotating around points other than its center. My goal is to rotate the element around its own center. ...

Refresh the datatable automatically when a field is updated without the need for AJAX requests

I need assistance with sorting a datatable column that contains checkboxes. The issue I'm facing is that the sorting is not working due to me changing the value of the column. Since it's not generated via ajax and I can't use the reload() me ...

Is your URL getting cut off in jQuery?

How can I properly display a URL in an HTML table without it getting truncated? I'm attempting to show it within a table using jQuery, but it seems to be cutting off the URL. Here's a snippet of my code. Any suggestions on how to fix this? <! ...