Tips for creating a clickable A href link in the menu bar that triggers an accordion to open in the body when clicked - html

Is there a way to open the first accordion when clicking on the "open 1st accordion" link, and do the same for the second link? The accordions themselves work perfectly fine, I just need a way to trigger them from outside their scope by clicking on links in the menu bar.

$(".expand").on("click", function () {
    $(".right-arrow").text("+");
    $(".detail:visible").slideUp();
    if(!$(this).next().is(":visible")){

        $(this).next().slideDown(200);
        $(this).find(".right-arrow").text("-");
    }
});
/*Tips & Tricks Page*/
*,
*:before,
*:after {
    -webkit-box-sizing: border-box; 
    -moz-box-sizing: border-box; 
    box-sizing: border-box;
}

#trickslist {
    font-family: 'Open Sans', sans-serif;
    width: 80%;
    margin: 0 auto;
    display: table;
}
#trickslist ul {
    padding: 0;
    margin: 20px 0;
    color: #555;
}
#trickslist ul > li {
    list-style: none;
    border-top: 1px solid #ddd;
    display: block;
    padding: 15px;
    overflow: hidden;
    text-align: center;
}
#trickslist ul:last-child {
    border-bottom: 1px solid #ddd;
}
#trickslist ul > li:hover {
    background: #efefef;
}
.expand {
    display: block;
    text-decoration: none;
    color: #555;
    cursor: pointer;
}
.tipstricks {
    padding: 5px;
    margin: 0;
    font-size: 17px;
    font-weight: 400;
}

span {
    font-size: 12.5px;
}
#left,#right{
    display: table;
}

.detail a {
    text-decoration: none;
    color: #C0392B;
    border: 1px solid #C0392B;
    padding: 6px 10px 5px;
    font-size: 14px;
}
.detail {
    margin: 10px 0 10px 0px;
    display: none;
    line-height: 22px;
    height: 150px;
}
.detail span{
    margin: 0;
}
.right-arrow {
    padding-top: 0px;
    margin-top: 0px;
    margin-left: 20px;
    width: 10px;
    height: 100%;
    float: right;
    font-weight: bold;
    font-size: 20px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<a href=""> Open 1st accordion </a> <br>
<a href=""> Open 2nd accordion </a>

<div class="container">
    <div class="row" id="accordion1">
        <div id="trickslist">
            <ul>
                <li>
                    <a class="expand" data-parent="#accordion1">
                        <div class="right-arrow">+</div>
                        <div>
                            <h2 class="tipstricks">Exploring your Motivations to Quit Tobacco</h2>
                        </div>
                    </a>
                    <div class="detail">
                    </div>
                </li>
                <li>
                    <a class="expand" data-parent="#accordion1">
                        <div class="right-arrow">+</div>
                        <h2 class="tipstricks">What to expect over time.</h2>
                    </a>
                    <div class="detail">
                    </div>
                </li>
                <li>
                    <a class="expand" data-parent="#accordion1">
                        <div class="right-arrow">+</div>
                        <h2 class="tipstricks">Getting Ready: Strategies to conquer urges & set a quit date</h2>
                    </a>
                    <div class="detail">
                    </div>
                </li>
                <li>
                    <a class="expand" data-parent="#accordion1">
                        <div class="right-arrow">+</div>
                        <h2 class="tipstricks">Quitting tobacco with medications</h2>
                    </a>
                    <div class="detail">
                    </div>
                </li>
                <li>
                    <a class="expand" data-parent="#accordion1">
                        <div class="right-arrow">+</div>
                        <h2 class="tipstricks">Dealing with depression or stress</h2>
                    </a>
                    <div class="detail">
                    </div>
                </li>
                <li>
                    <a class="expand" data-parent="#accordion1">
                        <div class="right-arrow">+</div>
                        <h2 class="tipstricks">Avoiding weight gain or alcohol</h2>
                    </a>
                    <div class="detail">

                    </div>
                </li>
                <li>
                    <a class="expand" data-parent="#accordion1">
                        <div class="right-arrow">+</div>
                        <h2 class="tipstricks">Making your plan stick: relapse prevention</h2>
                    </a>
                    <div class="detail">
                    </div>
                </li>
            </ul>
        </div>
    </div>
</div>

Services.html (each link in this menu should correspond to an accordion section in index.html and open it)

<div class="collapse navbar-collapse" id="navbarResponsive">
<ul class="navbar-nav ml-auto">
<li class="nav-item" >
<a class="nav-link" href="about.html">Who We Are
</a>
</li>
<li class="nav-item">
<a class="accord" href="">Our Services</a>
</li>
<li class="nav-item" id="nav">
<a href="index.html"> <img src="assets/images/name.png"/> </a>  
</li>
<li class="nav-item">
<a class="accord" href="">Our Clients</a>
</li>
<li class="nav-item">
<a class="accord" href="" >Contact Us</a>
</li>
</ul>
</div>

Answer №1

To enhance the top tags a, include a new class:

<a class="accord" href=""> Open 1st accordion </a> <br>
<a class="accord" href=""> Open 2nd accordion </a> 

Subsequently, implement the click event logic on these a tags using the each() method and the index parameter.

Utilize event.preventDefault() to halt the default behavior of the a tag.

Employ the trigger() method to trigger click events on the .expand class with an appropriate eq() index:

$(".expand").eq(index).trigger('click');

Apply the provided code snippet within your main code for this functionality:

$('.accord').each(function(index) {
  $(this).click(function(event) {
    event.preventDefault();
    $(".expand").eq(index).trigger('click');
  });
});

UPDATE:

An updated version of the jquery code considering the use of localStorage().

$(document).ready(function () {
    $(".expand").on("click", function () {
        $(".right-arrow").text("+");
        $(".detail:visible").slideUp();
        if (!$(this).next().is(":visible")) {
            $(this).next().slideDown(200);
            $(this).find(".right-arrow").text("-");
        }
    });

    let click_state = localStorage.getItem("click_state");
    let ind = localStorage.getItem("ind");

    if (click_state == 1) {
        $(".expand").eq(ind).trigger("click");

        localStorage.removeItem("click_state");
        localStorage.removeItem("ind");
    } else {
    }

    $(".accord").each(function (index) {
        $(this).click(function (event) {
            event.preventDefault();

            localStorage.setItem("click_state", 1);
            localStorage.setItem("ind", index);
        });
    });
});
/*Tips & Tricks Page*/
*,
*:before,
*:after {
    -webkit-box-sizing: border-box; 
    -moz-box-sizing: border-box; 
    box-sizing: border-box;
}

#trickslist {
    font-family: 'Open Sans', sans-serif;
    width: 80%;
    margin: 0 auto;
    display: table;
}
#trickslist ul {
    padding: 0;
    margin: 20px 0;
    color: #555;
}
#trickslist ul > li {
    list-style: none;
    border-top: 1px solid #ddd;
    display: block;
    padding: 15px;
    overflow: hidden;
    text-align: center;
}
#trickslist ul:last-child {
    border-bottom: 1px solid #ddd;
}
#trickslist ul > li:hover {
    background: #efefef;
}
.expand {
    display: block;
    text-decoration: none;
    color: #555;
    cursor: pointer;
}
tipstricks {
    padding: 5px;
    margin: 0;
    font-size: 17px;
    font-weight: 400;
}

span {
    font-size: 12.5px;
}
#left,#right{
    display: tabular-column;
}

.detail a {
    text-decoration: none;
    color: #C0392B;
    border: 1px solid #C0392B;
    padding: 6px 10px 5px;
    font-size: 14px;
}
.detail {
    margin: 10px 0 10px 0px;
    display: none;
    line-height: 22px;
    height: 150px;
}
detail span{
    margin: 0;
}
right-arrow {
    padding-top: 0px;
    margin-top: 0px;
    margin-left: 20px;
    width: 10px;
    height: 100%;
    float: right;
    font-weight: bold;
    font-size: 20px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>

<a class="accord" href=""> Open 1st accordion </a> <br>
<a class="accord" href=""> Open 2nd accordion </a>

<div class="container">
    <div class="tabulation-row" id="accordion1">
        <div id="trickslist">
            <ul>
                ... [Content continues]

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

Unpredictable hovering actions when interacting with nested items within the hover layer

Imagine a scenario where we have the following elements: A container that holds everything A baseDiv inside that container // Let's create a base layer var container = document.getElementById('container') var baseDiv = document.createEl ...

What is the best way to send the current ID for data deletion in React?

Here is my current code snippet: var html = []; for (var i = 0, len = this.props.tables.length; i < len; i++) { var id = this.props.tables[i]._id;//._str; html.push( <div key={id} className="col-xs-6 col-md-3"> ...

Executing a JavaScript Function in the Background using Cordova

Despite the numerous questions and plugins available on this topic, finding a solution has proven to be elusive for me. The most highly recommended plugin for this issue can be found here. My goal is to run MyService in the background, subscribe to the ON ...

Is it possible to generate two output JSON Objects for a JavaScript line chart?

How can I display two lines in a Chart.js line chart using data from a JSON file with 2 objects stored in the database? When attempting to show both sets of data simultaneously, I encountered an issue where the output was always undefined. Why is this hap ...

When utilizing Laravel to send a JSON response, a strange issue occurs where an extra single quote (`'`) and double quote (`"`) are included in the output: `'{"status":500,"

Utilizing jQuery's $.ajax function to make ajax requests to my Laravel 5.1 API. I am attempting to display the error response from the server, but facing difficulty in parsing the response due to an unexpected ' at the beginning of the responseT ...

Is there a way for me to identify the scrolling height and dynamically adjust the title using jQuery?

I am in the process of creating a list of shops from different countries for my website. I want to implement a feature that detects when the user has scrolled to a specific area so I can update the title at the top accordingly. My idea is to assign classe ...

MUI options - The specified type 'string' cannot be matched with type '"icon" | "iconOnly" | "text" | "outlined" | "contained" | undefined'

Is it possible to utilize custom variants in MUI v5? I am having trouble using a custom variant according to their documentation: https://mui.com/material-ui/customization/theme-components/#creating-new-component-variants declare module "@mui/material ...

Scope variable changes are not being acknowledged by the directive

Here is a directive I am working with: <span ng-show="{{ save_state == 'saved' }}"> Saved </span> <span ng-show="{{ save_state == 'saving' }}"> Saving </span> <span ng-show="{{ save_state == 'error ...

Multiple instances of Ajax drop-down effects are now available

On my website's staff page, I have implemented a dropdown menu using AJAX to display information about each member of the staff. The issue arises when attempting to open multiple dropdown menus on the same page - the second dropdown that is opened ten ...

Reveal the table only once a search has been completed

Currently, I am in the process of developing a small project and my aim is to have the table with the results appear only upon clicking the button or initiating a search. If you are interested, you can view it at this link: . My objective is to keep the t ...

Enhance your website with a lightbox effect using FancyBox directly in your JavaScript code

I am currently experiencing an issue with implementing fancybox on my website. I have a website that features links to articles, which open in fancybox when clicked. The problem arises when a user tries to access an article directly. In this case, the use ...

What is the process of adding a div to the left side of the parent element in AngularJS

I am trying to append the code on the left side of the click. My current controller code looks like this: demo.$inject = ['$scope']; demo.directive("boxCreator", function($compile){ return{ restrict: 'A', l ...

Executing operations on checkboxes on a webpage without access to model files

I am facing an issue with accessing the models file due to encryption in the software. Currently, my checkboxes are implemented using Ajax within a PHP query. Since it is Ajax-based, I am unable to manipulate actions through the URL. My goal is to extract ...

"Troubleshooting the issue of jQuery addition not functioning correctly within an AJAX

Is there a way to add the result value to an already existing value in a specific textbox? I've noticed that concatenation is working, but addition is not. $.post('includes/ajax_timesheet.php', { 'action': 'add_kitamount&ap ...

Creating an array object in JavaScript is a straightforward process that involves using the array

Looking to achieve the following object list structure: myObj = {"foo":[1,2,3,4], "bar":[3,5,7,8]} Initial attempt was unsuccessful: var myObj = new Object(); myObj["foo"].push(1) myObj["foo"].push(2) #...etc Seeking guidance on the correct m ...

Attempting to retrieve dynamically generated input fields and cross-reference them with structured length .json data

In the process of developing code, I've implemented a for loop to dynamically generate HTML input fields based on the length of some data in a .json file. My goal is to use jQuery to compare the text entered in each input field with the corresponding ...

Is there a way to cross-reference a city obtained from geolocation with the cities stored in my database, and if a match is found, send the corresponding ID

Here's the script I'm currently working with: <script type="text/javascript"> search = new Vue({ el: '#offers', data: { data: [], authType: '{{uid}}', key : '1', wi ...

Data is successfully being stored in an array in AngularJS, however, it is not appearing in the user interface

Having an issue with displaying updated data on my UI. I am successfully pushing data into the database and an array using Angular 2-way binding. The data is being pushed as confirmed by the console, but it's not showing up on the user interface. Con ...

Changing Marker Color in Google Maps API

There are multiple Google Maps Markers colors based on certain conditions being TRUE or not. In addition, these Markers will change color when the mouse hovers over a division (a1,a2..ax). I want the Markers to revert back to their original color when th ...

Ways to showcase tooltip text for an unordered list item?

When creating an unordered list, each element's text corresponds to a chapter name. I also want to include the description of each chapter as tooltip text. The Javascript code I currently have for generating a list item is: var list_item = document.c ...