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

Unable to access contextual values in NextJS

When attempting to retrieve values from the context API, I am encountering issues where I receive a default value (without the updates made during the context call) and an undefined value (which should receive a value in the context provider). sortListCont ...

executing jQuery toggle on freshly generated content

I have a webpage that I designed using jQuery. Within this page, there is a table with rows assigned specific color classnames (e.g., tr class="yellowclass"). Users can filter the rows by clicking checkboxes to show/hide tables of different colors. The i ...

Using Jquery's append() method to dynamically alter the HTML content

I am attempting to create a table with rows that are added dynamically. The challenge I am encountering is that each row consists of form elements, including multiple inputs. I have a PHP function that generates the correct row, and I have been able to sen ...

Tips for accessing .js variables in .ejs files

I am facing an issue with my index.js and list.ejs files in Express. Here is the relevant code: index.js: const express = require("express"); const app = express(); app.set("view engine", "ejs"); app.set("views", __dirname + "\\views"); let ...

The functionality of the delete button in Datatables is only operational on the initial page, failing to

My datatable is giving me trouble. The delete button in the action column only works on the first page, but not on the other pages. Here is the code for my delete button: <table id="example" class="table table-striped table-bordered" cellspacing="0" wi ...

Unable to scroll after the webpage redirects

I am currently working on developing a website for uploading images with a comment feature. The comments section is displayed below the image in the 'imagedisplay.php' file. If a user is not logged in, they are redirected to the sign-up page and ...

Create a notification menu in Bootstrap using Bootply, which conveniently displays a numerical badge at the top

I am interested in implementing a bootstrap notification menu similar to the one found at this link: http://www.bootply.com/oasBuRC8Kz# However, I would like to add the number of notifications to the upper right corner of the glyphicon. I have gone throug ...

What is the method for achieving the equivalent effect of "background-size: cover" on an <img>?

I am looking to ensure that an <img> has the smallest possible size without any empty spaces inside a div, while also being perfectly centered both horizontally and vertically. The image size may vary. To better illustrate, here is an example: http: ...

Learn to Generate a Mathematical Quiz with Javascript

For a school project, I am tasked with developing a Math Quiz which showcases questions one at a time. The questions vary in type, including Multiple Choice, Narrative Response, Image Selection, Fill in the blank, and more. I require assistance in creatin ...

The React Router's Switch component fails to update when the route is changed

In my component, I have a list of news categories. The links to these categories are in another component within the Router. However, when I change the link, the content does not update. I suspect this is because my NewsFeed component, where I define the S ...

Utilizing Javascript to load and parse data retrieved from an HTTP request

Within my application, a server with a rest interface is utilized to manage all database entries. Upon user login, the objective is to load and map all user data from database models to usable models. A key distinction between the two is that database mode ...

How to clear input fields in Ant Design ReactJS components

Utilizing the form list component from antd in my react.js project https://ant.design/components/form/#Form.List I have a basic form list set up where I can easily add or remove fields. At times, I need to reset the form and remove any additional items t ...

Adjusting image sizes in WordPress using CSS and HTML

I am currently working on a blog using the Marlene theme on Wordpress. For my posts, the default image resolution is 835x577, which suits my needs perfectly (see example post). However, I also have a "News" page where I want to display a list of all news ...

Acquiring a website's dynamic value using jquery

This question is pretty self-explanatory... I am trying to extract a value from a website's source code, but the value I need is dynamically generated using jQuery. Let's use example.com as an example: <div id="currentTime"></div> ...

How to exclude elements nested inside another element using CSS or XPath techniques

Presented here is a snippet of XML code: <xml> <section> <element>good</element> <section class="ignored"> <element>bad</element> </section> </section> </xml> Identifying a ...

Saving data values for utilization in jQuery

Recently, I've come across a series of links structured like this: <a class="colorBox" href="#" title="#0676B3"></a> <a ... <a ... these links all have color values in the title attribute <a ... What I'm trying to do is uti ...

Trying to configure and use two joysticks at the same time using touch events

I have been grappling with this problem for the past two days. My current project involves using an HTML5/JS game engine called ImpactJS, and I came across a helpful plugin designed to create joystick touch zones for mobile devices. The basic concept is th ...

Create an input field dynamically by utilizing the append method in jQuery

Concern: As part of an edit page, I am working on appending an input field from a modal window to an existing panel while retaining the format of the rest of the fields. The user is currently able to create and add the new field using the code provided in ...

What is the best way to obtain the value of a Promise within a function?

When working with Promises, accessing the value inside the .then method is simple. Take a look at this example: const Promise = require("bluebird"); const fs = Promise.promisifyAll(require('fs')); const mergeValues = require('./helper' ...

How to initiate a refresh in a React.js component?

I created a basic todo app using React, TypeScript, and Node. Below is the main component: import * as React from "react" import {forwardRef, useCallback, useEffect} from "react" import {ITodo} from "../types/type.todo" import ...