Ways to conceal and reveal a different section at the same time (like an accordion)

Looking for guidance on implementing an accordion-style functionality, where clicking a navigation link hides one section and reveals another seamlessly with automatic scrolling to the start of the section (end of the navigation). Any tips or starting points?

JSFiddle


$(function() {
  var shrinkHeader = 50;
  $(window).scroll(function() {
    var scroll = getCurrentScroll();
    if (scroll >= shrinkHeader) {
      $('#navbar').addClass('shrink');
    } else {
      $('#navbar').removeClass('shrink');
    }
  });

  function getCurrentScroll() {
    return window.pageYOffset || document.documentElement.scrollTop;
  }
});

* {
  margin: 0;
  padding: 0;
  font-family: helvetica;
}

  

Answer №1

Hopefully this solution is helpful. It took me quite a few hours to figure it out, even after searching extensively on stackoverflow.

 <!DOCTYPE html>
 <html>
 <title>Creating Menu Animation with JavaScript</title>
 <meta name="viewport" content="width=device-width, initial-scale=1">

 <style>
 #navi{
     position: absolute;
     top: 40px;
     left: 3%;
     width: 25%;
 }

 .menuItem{
     margin-bottom: 5px;
     width: 100%;
 }

 .menuPage{
     border: 1px solid #000000;
     background-color: #dcdcdc;
     text-align: center;
     padding: 2px 4px;
 }
 </style>

 <body>

 <div id="navi">

     <div id="Ldon" class="menuItem" onclick="openCity('London', 'Ldon')"><p class="menuPage">London</p>
         <div id="London" class="city" style="display:none">
             <h2>London</h2>
             <p>London is the capital city of England.</p>
         </div>
     </div>

     <div id="Pris" class="menuItem" onclick="openCity('Paris', 'Pris')"><p class="menuPage">Paris</p>
         <div id="Paris" class="city" style="display:none">
             <h2>Paris</h2>
             <p>Paris is the capital of France.</p> 
         </div>
     </div>

     <div id="Tkyo" class="menuItem" onclick="openCity('Tokyo', 'Tkyo')"><p class="menuPage">Tokyo</p>
         <div id="Tokyo" class="city" style="display:none">
             <h2>Tokyo</h2>
             <p>Tokyo is the capital of Japan.</p>
         </div>
     </div>

 </div>

 <script>
 function openCity(cityName, newPos) {
 var i;
 var y = document.getElementsByClassName("menuItem");
 var x = document.getElementsByClassName("city");
 var movePos = document.getElementById(newPos);

 for (i = 0; i < y.length; i++) {
     y[i].style.position = "";  
     y[i].style.top = ""; 
 }

 for (i = 0; i < x.length; i++) {
     x[i].style.display = "none";  
 }

 document.getElementById(cityName).style.display = "block";  
 movePos.style.position = "absolute";
 movePos.style.top = "80px";
 }
 </script>

 </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

Exclude striped tr elements within a subtable

I have a main table (Maintable) containing information, with each row having a sub-table for additional details that can be collapsed if needed. I am trying to stripe the rows in the Main table but using `tr:nth-child(even)` is not working as it also affec ...

How can I make my div disappear when I click outside of it using jQuery? I am finding the solution on Stack Overflow to be confusing

Utilizing jQuery to conceal a DIV upon clicking outside of it Although I've heard positive feedback about this method, I'm uncertain about its functionality. Can someone provide an explanation? I understand that .has() identifies elements contai ...

How can I convert a string containing integers into an int[] using javascript or jQuery?

I want to create a feature that allows users to input a list of IDs in a textarea, with the option to separate them by either whitespace or commas. After the user inputs the list, I need to convert it into an int[] array but also throw an error if the str ...

Three.js - Controlling Visibility of Text in troika-three-text with Clipping Planes

Has anyone successfully clipped troika-three-text for threejs using clipping planes? I'm having trouble getting it to work. import { Text } from 'troika-three-text' const minClippingPlane = new THREE.Plane(new THREE.Vector3(0, -1, 0), 1) c ...

The Material UI dialog box popped up against an unexpected gray backdrop

Currently, I am using Material UI in conjunction with React to create a dialog that appears when a button is tapped. This button is located within a table, which is displayed over a Paper component. The problem arises when I utilize the dialog with its def ...

What could be the reason for the lack of definition of the `pieceOfText

My latest project involves a fun guessing game centered around decrypting text, but I've hit a snag with a variable in my JavaScript code. This variable, known as pieceOfText, should be assigned a random piece of text from an array containing 3 encode ...

Is there a way to extract the numerical value from a string within an ID of a div and transform the rest of the string into a variable?

Looking to extract the final id of a div and convert it to a variable. <div class="margin_bot" id="itemRows2"> <p id="rowNum1">...</p> <p id="rowNum2">...</p> <p id="rowNum3">...</p> <p id="rowNum4"> ...

The variable fails to receive a value due to an issue with AJAX functionality

I am struggling to figure out what's causing an issue with my code. I need to store the result of an AJAX request in a variable, specifically an image URL that I want to preload. $.ajax({ type: "POST", url: 'code/submit/submi ...

Images featuring a drop-down menu

I'm having trouble separating the two photos on this page. When I hover over one, the other also fades in. Additionally, the text box is overlapping the first photo. My goal is to have a total of 6 photos on the page, each with a dropdown list contain ...

Repairing a CSS file for Internet Explorer versions 7, 8, and 9

Does anyone have experience with troubleshooting HTML5 CSS3 layouts across different browsers? I recently created a website layout from scratch that looks perfect in Firefox 5, Safari 5.1 and Chrome 12 on Mac. However, when using tools like Adobe BrowserL ...

The image fails to appear while creating a PDF in AngularJS using pdfmake

I recently started using a fantastic pdf printing library called pdfmake in my angularjs SPA to generate PDF files. Everything was going smoothly until I tried to include images in the PDF. Strangely, when I added images, nothing happened - no errors, no e ...

How can you set the dimensions of rows and columns in an HTML table?

I am currently working on setting specific sizes for each data cell in a table. While most cells are supposed to be the same size, I am encountering an issue where cells marked as d, h, l, and p are smaller than the rest even though I have specified their ...

Unable to access npm run build on localhost

I have developed a web application using react and node.js, and now I want to test it with a production build. After running npm run build in the app directory, I successfully created a build folder. However, when trying to run the application using local ...

Efficiently rendering a million elements on an HTML canvas (and replicating the render from the server)

I'm currently working on developing an HTML application using a canvas as the base. The canvas will consist of a large grid, around 1500 x 700 in size, totaling to over 1 million cells. The main concern is how to efficiently render this grid without ...

Showing an image in a Bootstrap Modal using data fetched from an ajax json response

My current issue involves displaying and editing a record from a database using Bootstrap modal. Everything works fine except for the image rendering - it doesn't seem to display the edited image. While an HTML dataType renders the image correctly, I ...

Is there a way to modify the orientation of the bootstrap modal when it opens?

I am trying to modify the way my bootstrap reveal modal opens. I have followed the code instructions provided in this resource, but unfortunately my modal is not opening. I am using angularjs. Can someone assist me with troubleshooting the code? Here is m ...

Differences between typical functions and function variables in JavaScript

Can someone clarify the distinction between function MyFunc() { // code... } and var MyFunc = function() { // code... }; when it comes to JavaScript? ...

What could be causing my application to hang on my local server?

Recently, I developed a NodeJS and Express MVC (or perhaps more accurately VC) app. Initially, everything worked smoothly until I integrated express-validator and included the middleware in the app file. This caused my localhost to freeze, displaying a GET ...

Tips for selecting specific elements from an array with jquery

Is there a way to efficiently fetch specific elements from an array using jQuery? For example, if we have an array like this: var arr = [Obj1, Obj2, Obj3, Obj4, Obj5, Obj6] And we want to select objects with index 3 and 5. Is there a function or method t ...

The dynamic page fails to export with a static export in NextJS, resulting in an output error: "

I'm struggling to export a route in my NextJS 14 project. I've set the output to export and all routes are exporting correctly except for the dynamic ones. The folder for the dynamic route is not showing up in the output folder The version of Ne ...