`Switching between two buttons: A guide`

Here is the codepin: https://jsfiddle.net/magicschoolbusdropout/dwbmo3aj/18/

I currently have a functionality in my code that allows me to toggle between two buttons. When I click on one button, content opens and then closes when clicked again. The same behavior occurs with the second button. However, if I switch from the second button back to the first button, the content appends instead of smoothly transitioning.

What I am aiming for is the ability to seamlessly toggle between the two buttons without the content shifting or appending when switching between them. Any help or guidance on achieving this would be greatly appreciated! Thank you :)

The functions I'm trying to toggle between are:

function currentOrder(){
  var current = document.getElementById("current");
  if (current.style.display === "none") {
    current.style.display = "block";  
  } else {
    current.style.display = "none";
  }
}

function orderHistory(){
  var history = document.getElementById("history");
  if (history.style.display === "none") {
    history.style.display = "block";
  } else {
    history.style.display = "none";
  }
}

<<html>

<head>
  <script src="https://static.freshdev.io/fdk/2.0/assets/fresh_client.js"></script>
  <script src="https://code.jquery.com/jquery-3.6.0.min.js"
    integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" crossorigin="anonymous"></script>
  <link rel="stylesheet" type="text/css" href="style.css" />
  <link rel="stylesheet" type="text/css" href="https://static.freshdev.io/fdk/2.0/assets/freshdesk.css" />
</head>

<body>
<button onclick="currentOrder()">Current Order</button>
<button onclick="orderHistory()">Order History</button>

<div id ="current">
  <div class="">
    <div class="item1-container">
      <div class="container">
        <br>
        <h5 class="text"><span class="key"> Order #: </span><span class="value">121800</span></h5>
        <h5 class="text line"><span class="key"> Name: </span><span id="name" class="value"></span></h5>
        <h5 class="text"><span class="key"> Status Update : </span><span class="value">Pending</span></h5>
        <br>
        <h4 class="text"><span class="key"> <b> Non-Dairy Blue Matcha </b></span></h4>
        <img src="matchadrink.png" ALIGN=left alt="item1 image" class="image">
        <div class="container_text" id="item1_details">
          <p class="text"><span class="key">Price: </span><span class="value">$</span><span class="value"
              id="item-price" style="margin-left:auto">4.44</span></p>
          <p class="text"><span class="key">Quantity: </span><span id="quantity" class="value">0</span></p>
          <div class="quantity-wrapper">
            <div class="value-button" id="increase" onclick="increaseValue()" value="Increase Value"></div>
            <input type="number" id="number" value="0" />
            <div class="value-button" id="decrease" onclick="decreaseValue()" value="Decrease Value"></div>
            <input type="submit" name="save" value="save" id="add_quantity">
          </div>
        </div>
      </div>
    </div>
  </div><br>
  <div class="">
    <div class="item2-container">
      <div class="container">
        <h4 class="text"><span class="key"> <b>S'mores FroYo</b></span></h4>
        <img src="smores.png" ALIGN=left alt="item2 image" class="image">
        <div class="container_text" id="item1_details">
          <p class="text"><span class="key">Price: </span><span class="value">$</span><span class="value"
              id="item-price">5.20</span></p>
          <p class="text"><span class="key">Quantity: </span><span id="quantity1" class="value">0</span></p>
          <div class="quantity-wrapper">
            <div class="value-button" id="decrease" onclick="decreaseValue()" value="Decrease Value"></div>
            <input type="number1" id="number1" value="0" />
            <div class="value-button" id="increase" onclick="increaseValue()" value="Increase Value"></div>
            <input type="submit" name="save" value="save" id="add_quantity1">
          </div>
        </div>
      </div>
    </div>
  </div>
</div>

<div id="history">
  <div class="">
 <h3> Order History</h3> <br>
 <p>
  <h5 class="text"><span class="key"> Order #: </span><span class="value">123456</span></h5>
  <h5 class="text"><span class="key"> Name: </span><span id="name" class="value"></span></h5>
  <h5 class="text line"><span class="key"> Status Update : </span><span class="value">Completed</span></h5>
 </p>
 <p>
  <h5 class="text"><span class="key"> Order #: </span><span class="value">56789</span></h5>
  <h5 class="text"><span class="key"> Name: </span><span id="name" class="value"></span></h5>
  <h5 class="text line"><span class="key"> Status Update : </span><span class="value">Completed</span></h5>
 </p>
 <p>
  <h5 class="text"><span class="key"> Order #: </span><span class="value">10987</span></h5>
  <h5 class="text"><span class="key"> Name: </span><span id="name" class="value"></span></h5>
  <h5 class="text line"><span class="key"> Status Update : </span><span class="value">Completed</span></h5>
 </p>
 <p>
  <h5 class="text"><span class="key"> Order #: </span><span class="value">082402</span></h5>
  <h5 class="text"><span class="key"> Name: </span><span id="name" class="value"></span></h5>
  <h5 class="text line"><span class="key"> Status Update : </span><span class="value">Completed</span></h5>
 </p>
 <p>
  <h5 class="text"><span class="key"> Order #: </span><span class="value">081893</span></h5>
  <h5 class="text"><span class="key"> Name: </span><span id="name" class="value"></span></h5>
  <h5 class="text line"><span class="key"> Status Update : </span><span class="value">Completed</span></h5>
 </p>
  </div>
</div>
</body>
<script src="app.js"></script>

</html>>

Answer №1

To make it more efficient, move the assignments outside of the functions. Here's a revised version:

let current = document.getElementById("current");
let history = document.getElementById("history");

function displayCurrentOrder(){
    current.style.display = "block";
    history.style.display = "none"
}

function displayOrderHistory(){
    current.style.display = "none";
    history.style.display = "block"
}

No need to check the current state, simply switch the styles for simplicity (KISS principle).

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

PHP AJAX Request Failing to Transfer Files

I am having trouble with sending files in a PHP AJAX Request: Here is the form code: <form class="frmContact" action="#" method="post"> <div class="col-md-6"> <input type="hidden" name="emailTo" id= ...

A guide to extracting data from HTML tables using Python for web scraping and exporting the results to

My Python skills are still pretty basic, but I'm working on creating a web scraping tool to extract data from an HTML table online and save it into a CSV file with the same structure. Here's an example of the HTML table (I'll show just a fe ...

Make sure the header spans the full width of the body

I am trying to create a header that spans the entire width of the body, but I am encountering some issues with white space on both sides. I initially attempted to set the width to 100% on the header div, but this did not eliminate the white space. I then e ...

Guide on deleting an item from an object array in AngularJS

I have an array of objects and need to delete a specific object from it: var objectArray = [{"id":"John Doe","label":"John Doe","shape":"image","image":"app/data/img/user_icon.png","color":{"background":"#db630d","border":"#7c3400"},"level":0},{"id":"Java ...

Is it possible to directly update the label text in AngularJS from the view itself?

I found the following code snippet in my HTML <span ng-class="newProvider ? 'newProvider' : ''" class="help-block"> {{ 'new-product.provider.helper' | locate }} </span> Whenever newProvider is se ...

What is the best way to retrieve localstorage information within the getStaticProps function in next.js?

Having trouble retrieving local storage data with the following code. localData = { id: localStorage.getItem("id"), token: localStorage.getItem("token"), }; This snippet is housed within a function called getStaticProps ...

What is the reason behind jQuery onePageNav adding the 'current' class to each 'li' element?

When the jQuery function is applied to the .navbar.navbar-fixed-top .navbar-nav, it triggers an event that changes the current class to 'active', disables hash change, sets scroll speed to 400 and applies a filter excluding elements with the &apo ...

Loading a local FBX file in Three.js without the need to upload it

When attempting to load files selected by users in an HTML input, I encountered a problem with the loader expecting a URL in Linux style. I have tried various methods such as using a blob as a URL object, providing raw data to the FBX loader, and even usin ...

Responsive left and right image styling in CSS and HTML

I have designed a landing page with fixed left and right images and content in the middle. It looks fine on desktop view, but on mobile view, the images are overlapping the content. How can I resolve this issue? <div class=" ...

ReactJS: Trouble encountered while parsing information from JSON data

Currently, I am facing an issue while trying to pass data from my JSON file to my ReactJS application. The error message that I am encountering is as follows: TypeError: Cannot read property 'mainPage' of undefined Upon console.logging siteDa ...

React - warning - Avoid using <Link> outside of a <Router> context

Warning: Invariant failed: It is not recommended to use <Link> outside of a <Router> Encountering this while attempting to write a test for a component where test("renders post list div ", () => { const posts = [ { created: ...

Unusual "visual" phenomenon with autocomplete feature in VUE.js

Can someone review this code snippet? Check out the code here This is a peculiar example of a custom autocomplete VUE component. If you enter a value in one of the fields in Section 1 (like 'Apple'), then click on the Next button, you'll ...

Swap out the variables in your function with the values selected from the dropdown menu

I've recently started delving into writing JS functions and I'm facing a challenge with the following scenario: On an HTML page, I want to change a variable within a lodash function based on the value of a dropdown and display the result in a HT ...

Guide to directing a user through an Ajax call to a particular Controller and action

Here is a custom JavaScript function that updates data when the Update button is clicked. function UpdateData() { var obj = { "testData": $("#hdn_EditdsVal").val(), "feature": $("#hdn_EditdsVal").val() }; $.ajax({ url: ...

I can't seem to figure out why this isn't functioning properly

Upon examining the script, you'll notice the interval() function at the very bottom. The issue arises from bc-(AEfficiency*100)/5; monz+((AEfficiency*100)/5)((AFluencyAProduct)/100); For some reason, "bc" and "monz" remain unchanged. Why is that so? T ...

Optimizing Variable Destructuring Efficiency

Is there a difference in performance when assigning variables like const color = props.color; compared to destructuring like this const { color } = props; Furthermore, does destructuring within the parameters affect performance positively or negatively ...

Encountering a "Vue is not defined" error in Laravel 5.8 while constructing a comment system using Vue.js

I'm struggling to implement a comment system using Vue.js in my Laravel project. Despite my efforts, I keep encountering a "Vue not defined" error in the console. Can anyone shed some light on why this might be happening? Below is the code snippet I&a ...

What is the importance of having Express in the frontend?

As someone who is relatively new to the world of JavaScript and web applications, I recently came across an Express web application project that contained a public directory, client directory, and server directory. This has raised some questions for me. I ...

Code snippet for calculating the size of an HTML page using JavaScript/jQuery

Does anyone know of a way to calculate and display the size/weight (in KB) of an HTML page, similar to what is done here: Page size: 403.86KB This would include all resources such as text, images, and scripts. I came across a Pelican plugin that does th ...

Customizing the `toString()` method in Node.js exports

I'm having trouble overriding a toString() method in my code. I've already checked here and here, but haven't been able to solve the issue. This is what my code looks like: var Foo = function(arg) { // some code here... return fun ...