Looking to incorporate multiple accordion drop down menus on your website? Utilize a combination of HTML, CSS, and JavaScript to

I am experiencing a challenge with implementing multiple accordion menus on my website. Whenever I attempt to duplicate the code, the new accordion menu appears but clicking on the first bar simply scrolls me back to the top of the webpage.

Below is the HTML code:

<div class="container">
      <h1>Accordion Dropdown</h1>
      <div class="accordion">
        <dl>
          <dt><a class="accordionTitle" href="#">Test Accordion 1</a></dt>
          <dd class="accordionItem accordionItemCollapsed">
            <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Morbi eu interdum diam. </p>
          </dd>
          <dt><a href="#" class="accordionTitle">Test Simple Flat UI CSS Accordion 2</a></dt>
          <dd class="accordionItem accordionItemCollapsed">
            <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit.  </p>
          </dd>
          <dt><a href="#" class="accordionTitle">Test Simple Flat UI CSS Accordion 3</a></dt>
          <dd class="accordionItem accordionItemCollapsed">
            <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Morbi eu interdum diam. </p>
          </dd>
        </dl>
      </div>

The CSS code is provided below:

    @import url(http://fonts.googleapis.com/css?family=Lato:400,700);
* {
  -moz-box-sizing: border-box;
  -webkit-box-sizing: border-box;
  box-sizing: border-box;
}

body {
  font-family: 'Lato';
}

h1 {
  font-size: 2em;
  padding: 2em;
  text-align: center;
}

.accordion dl {
}

.accordion dt > a {
  text-align: center;
  font-weight: 700;
  padding: 2em;
  display: block;
  text-decoration: none;
  color: #fff;
  -webkit-transition: background-color 0.5s ease-in-out;
}
.accordion dd {
  background-color: #1abc9c;
  color:#fafafa;
  font-size: 1em;
  line-height: 1.5em;
}
.accordion dd > p {
  padding: 1em 2em 1em 2em;
}

.accordion {
  position: relative;
  background-color: #16a085;
}

.container {
  max-width: 960px;
  margin: 0 auto;
  padding: 2em 0 2em 0;
}

.accordionTitle {
  background-color: #22313F;
  border-bottom:...

Lastly, here is the JS/jQuery code snippet:

<script>
( function( window ) {
'use strict';
function classReg( className ) {
  return new RegExp("(^|\\s+)" + className + "(\\s+|$)");
}
var hasClass, addClass, removeClass;

if ( 'classList' in document.documentElement ) {
  hasClass = function( elem, c ) {
    return elem.classList.contains( c );
  };
  addClass = function( elem, c ) {
    elem.classList.add( c );
  };
  removeClass = function( elem, c ) {
    elem.classList.remove( c );
  };
}
else {
  hasClass = function( elem, c ) {
    return classReg( c ).test( elem.className );
  };
  addClass = function( elem, c ) {
    if ( !hasClass( elem, c ) ) {
      elem.className = elem.className + ' ' + c;
    }
  };
  removeClass = function( elem, c ) {
    elem.className = elem.className.replace( classReg( c ), ' ' );
  };
}

function toggleClass( elem, c ) {
  var fn = hasClass( elem, c ) ? removeClass : addClass;
  fn( elem, c );
}
var classie = {
  hasClass: hasClass,
  addClass: addClass,
  removeClass: removeClass,
  toggleClass: toggleClass,
  has: hasClass,
  add: addClass,
  remove: removeClass,
  toggle: toggleClass
};
if ( typeof define === 'function' && define.amd ) {
  define( classie );
} else {
  window.classie = classie;
}
})( window );
var $ = function(selector){
  return document.querySelector(selector);
}
var accordion = $('.accordion');
accordion.addEventListener("click",function(e) {
  e.stopPropagation();
  e.preventDefault();
  if(e.target && e.target.nodeName == "A") {
    var classes = e.target.className.split(" ");
    if(classes) {
      for(var x = 0; x < classes.length; x++) {
        if(classes[x] == "accordionTitle") {
          var title = e.target;
          var content = e.target.parentNode.nextElementSibling;
          classie.toggle(title, 'accordionTitleActive');
          if(classie.has(content, 'accordionItemCollapsed')) {
            if(classie.has(content, 'animateOut')){
              classie.remove(content, 'animateOut');
            }
            classie.add(content, 'animateIn');
          }else{
             classie.remove(content, 'animateIn');
             classie.add(content, 'animateOut');
          }
          classie.toggle(content, 'accordionItemCollapsed');      
        }
      }
    }  
  }
});
</script>

Answer №1

It seems like there might be some confusion with your issue, but after making a few adjustments and copying the code to jsfiddle:

`    <div class="wrapper">
    ...
    </div>`

everything appears to be functioning correctly http://jsfiddle.net/abc123/

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

Bootstrap Progress Animation Not Scaling Properly

I am encountering an issue with my Bootstrap 2.3 progress bars. They are supposed to show async file reads and be animated by updating their CSS properties using jQuery. However, the problem I'm facing is that the scale seems to be off - when the prog ...

Problem with Dynamic JqGrid: Paging feature not functioning as expected

I am facing a requirement to populate a grid dynamically based on the selected view. I have referred to the following resources for guidance on populating the grid dynamically. Link to Code Review Problem with jqGrid Dynamic Column Binding This approach ...

Refresh the database records by clicking the submit button

Is there a way to update a database by entering text into a text box and submitting it, with the data being sent to the database with a specific id? The code snippet below outlines what needs to be done, but it seems to trigger a 403 error: Access forbid ...

Jquery fails to function properly unless the page is refreshed

On my MVC page, I have implemented a feature where certain text-boxes are shown or hidden based on the value selected in a drop-down menu using jQuery. The functionality works fine when the page is isolated, but when placed under a menu, it encounters a pr ...

The issue of Django/Python static files not loading is causing disruption

mysite/settings.py """ Configuration settings for the Django project called mysite. This file was generated by 'django-admin startproject' using Django 1.9.5. For more details about this file, visit https://docs.djangoproject.com/en/1.9/topics ...

Utilizing AJAX to dynamically load file references and embed iframes

Is the use of multiple iframes on a website impacting its loading speed? Also, regarding AJAX, let's say I have two JSP pages. The first one contains an AJAX call to the second JSP page. Both pages have JavaScript functions with the same name, let&apo ...

Incorporating a teaser of a webpage into an <a> tag linking directly to the page

I am looking to enhance the <a> tag on my HTML page by including a URL link that directs users to another page, while also displaying a preview of that page. Similar to how Facebook automatically generates a preview when you post a link, I want to ...

Is there a way to display this JSON data using mustache.js without needing to iterate through a

Here is the JSON data: var details = [ { "event": { "name": "txt1", "date": "2011-01-02", "location": "Guangzhou Tianhe Mall" } ...

Flexbox ancestor causing Bootstrap 5 Carousel width to double

A peculiar issue arises with the Bootstrap 5 Carousel placed inside a Flexbox where it unexpectedly expands in width (pushing other flex-items aside) when transitioning between images. This behavior persists even when the immediate container is set to disp ...

The $route object in vue-router appears to be empty when used with single file components

I am facing an issue while using single file components with vue-router and vue-2.0. The problem I can't seem to resolve is that the this.$route object, when called from a component, always returns empty values. For example: Messages.vue <te ...

The tag <li> is not allowing enough room for the content to expand as needed

I am trying to create a list using ul li elements. When the content inside the li exceeds the width, a scrollbar appears. However, I am encountering an issue where the li tag does not cover the entire width and spills outside. .container{ b ...

bespoke theme background hue

I currently have material-ui@next installed and I am attempting to customize the background color of the theme. Here is what I have tried: const customizedTheme = createMuiTheme({ palette: createPalette({ type: 'light', primary: purple ...

Element dynamically targeted

Here is the jQuery code I currently have: $('.class-name').each(function() { $(this).parent().prepend(this); }); While this code successfully targets .class-name elements on page load, I am looking to extend its functionality to also target ...

When the user initiates a fetch request, they will be directed to the POST page as a standard

Whenever I utilize fetch for a post request, I encounter an issue where the user is not redirected to the Post page as they would be with a regular form submission. My goal is to be able to direct the user to a specific location on the server side at app ...

Tips on navigating to a URL with a component in React without losing the passed props

When the onClick event is triggered, I aim to redirect to a new component with props passed to it along with a new URL. My App.js import React from "react"; import Main from "./Components/Main/Main"; import "bootstrap/dist/css/boo ...

An effective way to confirm a notify.js alert using selenium

I am trying to validate the text of a notification message with the following code structure: <div class="notifyjs-corner" style="top: 0px; left: 45%;"> <div class="notifyjs-wrapper notifyjs-hidable"> <div class="notifyjs-arrow" styl ...

Separate JavaScript/ASP statements using commas

I'm having trouble comma-delimiting this line in JavaScript, as I keep encountering errors: <a href="javascript:doSubmit(<%= pound & rs("AdvertiserID")%>, <%=rs("AdvertiserName")%>)"> It's Friday, what can I say... The &l ...

The function screen.getByText is not available in this context

My experience with jest and react-testing-library has been smooth for the most part, but I encountered some challenges when transitioning to the screen > getByText/etc testing method. Test describe('test the dashboard when loaded', () => { ...

Pause file uploads, display modal popup, then resume uploading

Is there a way to pause file uploading in order to display file requirements before proceeding? For example, when a user clicks on "upload file", I would like to show them a modal window with details about the file they need to upload. Once they click ok, ...

Why is it necessary to decode JSON stringified objects in Vue props?

When passing a stringifyed object via props to a component, it seems like there is an issue with the data transformation. <my-component :filter="stringobject" ></my-component> stringobject = "{"search_text":"(ciCl ...