'Linking multiple hrefs to accordion and opening the corresponding section - Jquery
I have multiple hrefs that need to link to the proper accordion at the bottom of the page. The code I have now works, however I'm trying to minimize the amount of times I repeat functions as a coworker of mine points out that they are impractical. I have tried the location.hash solution, but it doesnt work for me. Any ideas would be appreciated.
window.contentAssetInitFunctions.push(function() {
$(document).ready(function() {
$("#start").click(function() {
$('#startExchange, #startHeader').addClass('active');
$('#packingSlip, #packingHeader').removeClass('active');
});
$("#pack").click(function() {
$('#packingSlip, #packingHeader').addClass('active');
$('#startExchange, #startHeader').removeClass('active');
});
});
});
<a href="#startHeader" id="start" class="text-link">Learn How</a>
<a href="#packingHeader" id="pack" class="text-link">Learn How</a>
<a class="question" id="startHeader"> EXCHANGE</a>
<div class="answer" id="startExchange">
content
</div>
<a class="question" id="packingHeader">HOW TO START AN EXCHANGE WITH A PACKING SLIP</a>
<div class="answer" id="packingSlip">
content
</div>
Solution 1:[1]
If you wrap each question/answer with a container tag (like an article
or div
), then you can target the whole section instead of having to pick out the question and answer with their custom ids.
Below you'll see I added a wrapper article
tag with an id that describes the section. Then the javascript removes all active tags, and then grabs the id
from the href
, finds that article
and adds an active tag to that one.
Something like this:
$(document).ready(function () {
$(".text-link").click(function () {
let section = $(this).attr('href').substr(1);
$('article .question, article .answer').removeClass('active')
$(`#${section} .question, #${section} .answer`).addClass('active')
});
});
<a href="#start" class="text-link">Learn How</a>
<a href="#packing" class="text-link">Learn How</a>
<article id="start">
<a class="question"> EXCHANGE</a>
<div class="answer">
content
</div>
</article>
<article id="packing">
<a class="question">HOW TO START AN EXCHANGE WITH A PACKING SLIP</a>
<div class="answer">
content
</div>
</article>
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 |