Expand the accordion and incorporate both a hyperlink and an anchor tag within the content

My go-to source for codes is usually https://www.w3schools.com. They also provide an accordion feature along with the code;

However, I've encountered an issue where when a link is used -> to The accordion doesn't open but remains closed. Does anyone know how to make the accordion open when linking to content inside it?

Thank you.

var acc = document.getElementsByClassName("accordion");
var i;

for (i = 0; i < acc.length; i++) {
  acc[i].onclick = function() {
    this.classList.toggle("active");
    var panel = this.nextElementSibling;
    if (panel.style.maxHeight){
      panel.style.maxHeight = null;
    } else {
      panel.style.maxHeight = panel.scrollHeight + "px";
    }
  }
}
@charset "utf-8";
/* CSS Document */

 /* Style the buttons that are used to open and close the accordion panel */
button.accordion {
    background-color: #530010;
    color: #FFF;
font-weight: bolder;
    cursor: pointer;
    padding: 10px;
    width: 100%;
    text-align: left;
    border: none;
    outline: none;
    transition: 0.4s;
border-radius: 5px;
}

/* Add a background color to the button if it is clicked on (add the .active class with JS), and when you move the mouse over it (hover) */
button.accordion.active, button.accordion:hover {
    background-color: #a20121;
}

/* Style the accordion panel. Note: hidden by default */
div.panel {
    padding: 0px 5px;    
margin-bottom: 5px;
background-color: #none;
    max-height: 0px;
    overflow: hidden;
    transition: max-height 0.2s ease-out;
}

button.accordion:after {
    content: '\02795'; /* Unicode character for "plus" sign (+) */
    font-size: 13px;
    color: #FFF;
font-weight: bolder;
    float: right;
    margin-left: 5px;
}

button.accordion.active:after {
    content: "\2796"; /* Unicode character for "minus" sign (-) */
}
<a href="schedule.html#0906">2018.09.06</a>(木) 今池GROW<br><br>

<button class="accordion"><a name="0906">■</a>2018/09/06(木)今池GROW </button>
<div class="panel">
<p>
Testing
</p>
</div>

Answer №1

Initially, I was a bit confused about your question, but I decided to give it a shot anyway!

I made some adjustments by adding IDs to the .accordion buttons and introducing the .accordion-link class for your text links. Now, when the accordion-links are clicked, the hash is isolated and used to trigger a click event on the corresponding accordion button with the same ID.

Check out the updated version on Fiddle: https://jsfiddle.net/ya6vtosc/25/

Here's the JavaScript code:

var acc = document.getElementsByClassName("accordion");
var i;

for (i = 0; i < acc.length; i++) {
  acc[i].onclick = function() {
    this.classList.toggle("active");
    var panel = this.nextElementSibling;
    if (panel.style.maxHeight){
      panel.style.maxHeight = null;
    } else {
      panel.style.maxHeight = panel.scrollHeight + "px";
    }
  }
}

// Get list of links by class
var links = document.getElementsByClassName("accordion-link");

var linksLength = links.length;
for(var i=0; i < linksLength; i++){
  links[i].onclick = function(e){
    // Prevent default action
    e.preventDefault();

    // Isolate the hash
    var hash = e.path[0].hash;

    // Remove # from hash
    hash = hash.substring(1);

    // Select element by ID using hash
    document.getElementById(hash).click();
  }

And here's the corresponding HTML code:

<a href="schedule.html#0906" class="accordion-link">2018.09.06</a>(木) 今池GROW<br><br;


<button class="accordion" id="0906">2018/09/06(木)今池GROW </button>
<div class="panel">
<p>
Testing
</p>
</div>

Additionally, I removed the link tag from your button as I wasn't sure if anchor tags are allowed inside buttons or not. It didn't seem right to me, so I decided to remove them.

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

The importance of white space within email design utilizing table tags in HTML

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html style="opacity: 1;" xmlns="http://www.w3.org/1999/xhtml"> <head> <meta content="text/html; charset=utf-8" http-equiv ...

Display a popup notification when clicking in Angular 2

Can anyone help me with displaying a popup message when I click on the select button that says "you have selected this event"? I am using Angular 2. <button type="button" class="button event-buttons" [disabled]="!owned" style=""(click)="eventSet()"&g ...

What is the best way to add data to a URL in an ActionResult Method using window.location.href?

I am having trouble understanding how to retrieve data using window.location.href = '/Product/Success/'+data.OrderTrackNo+'';. I am able to get data using ajax, but it seems different when retrieving data with window.location.href, whic ...

"Discover the process of utilizing jQuery to trigger an action when scrolling past a

I'm currently working with this code snippet: #main { max-width: 500px; height: 900px; margin: auto; background: green } .menu1 { height: 30px; background: red } .menu2 { display: none; } <div id="main"> <div class="menu1"& ...

Guide on displaying API data within nested fields in ReactJS

import axios from 'axios' import { CART_ADD_ITEM } from '../constants/cartConstants' export const addToCart = (uid, qty) => async (dispatch, getState) => { const { data } = await axios.get(`/api/v1/`) dispatch({ ...

AngularJS Assessing an Attribute directive following an Element directive

Currently, I am utilizing an angular plugin that can be found at the following link: https://github.com/angular-slider/angularjs-slider The objective is to customize the "legends" produced by the directive. In order to achieve this customization, the dire ...

Optimal approach for handling large JSON files

I am in possession of a JSON file containing approximately 500 lines. I am hesitant to simply dump this JSON data into the end of my Node.JS file as it doesn't seem like the most efficient approach. What alternatives or best practices can be recommend ...

Past methods: Obsolescence alert and caution

Trying to grasp the concepts of PHP & MYSQL, I have written this code which seems to be functioning properly. However, there are several "warnings" that I am unsure about. Nonetheless, PHP successfully connects to the database. Below are the relevant codes ...

Switch between two button designs in a React JS application

Is it possible to have the style of a button change when clicked? Specifically, I would like the option 1 button to be selected and have its background color changed by default. If I click on the option 2 button, I want only that button to change while lea ...

The custom confirmation popup is experiencing technical issues

Currently, I am utilizing a plugin to modify the appearance of the confirm popup. Although I have successfully customized the confirm popup, I am encountering an issue where upon clicking the delete icon, the custom confirm popup appears momentarily before ...

My local requests are being blocked by both Chrome and Firefox

Recently, I've been experimenting with local flash development and trying to inject my swf file into a website served by my test server. To enable loading of local resources in Chrome, I set --disable-web-security. In FireFox, I made the following a ...

What is the best way to implement a composite primary key in DocumentClient.batchWrite()?

I am attempting to conduct a batch delete process based on the instructions provided in this documentation. The example given is as follows: var params = { RequestItems: { /* required */ '<TableName>': [ { DeleteRequest: ...

Tips for updating parameters that are defined in a controller within a promise

Currently, I am developing a single page application using Angular and TypeScript. I am facing an issue with updating the parameter value (_isShowFirst) of the controller inside a promise function. It seems like nothing is recognized within the promise blo ...

What is the best method for eliminating duplicate objects in an array using 2 specific properties?

I am currently dealing with an array of room objects and my task involves removing duplicate objects based on their room_rate_type_id property: const rooms = [{ room_rate_type_id: 202, price: 200 }, { room_rate_type_id: 202, price: 2 ...

What is the reason behind the inconsistency of calling a function on click not always functioning properly in Chrome and FF, while working seamlessly in IE?

Consider a scenario where the code below is being used: <HTML> <HEAD> <SCRIPT> function myFunction(atlasTrackingURL) { var atlasURL = atlasTrackingURL; if (!atlasURL) return; //Creating a cache busting mechanism ...

Escaping Special Characters in JavaScript

My form is quite simple with two textboxes. When I click a button, I combine the contents of the textboxes using a delimiter. Is there a hidden delimiter that cannot be typed into an HTML textbox, even when using the &#xxx; syntax? ...

Changing the font family for Bootstrap Glyphicons on a button

I have recently started using Bootstraps Glyphicons and encountered an issue while trying to insert text inside a button with a glyphicon icon: <button type="button" class="btn btn-default pull-left" data-toggle="collapse" data-bind="attr:{'href&a ...

Preparing the format/serialization of a JQuery JSON array prior to submitting it

Looking at the JSON structure I have: { "firstArrayOfJSON": [ { "something" : "something" }, { "another" : "another" }, { "secondArrayOfJson" : [ ...

Creating a three-column layout with position fixed in the center

I'm struggling with achieving a maximum width of 400px for the entire set of three columns and centering them. ---------------------------------------------------- | | | |----------------------------- ...

MongoDB: Issue updating the 'role' field of a document

Recently, I've run into an issue where I am unable to update the 'role' of a specific document. The document in question is a 'user' object within the MEANjs User schema, and it has a pre-defined property for roles. Here is the sec ...