I’ve written a simple code for an FAQ list; each question is opened on click event and must be manually closed. Is there a way re-work this code so that in the event of clicking on a question to open (slidedown), ones that have been previously been open, automatically slideup to close?
{% javascript %}
(function() {
$('body').on('click', '.shopify_explorer_faq__question', function() {
$(this).next('.shopify_explorer_faq__answer').slideToggle(250).toggleClass('active');
$(this).toggleClass('active');
});
$(document).on('shopify:block:select', '#shopify-section-page-shopify_explorer_faq-template', function(event) {
$(event.target).find('.shopify_explorer_faq__answer').slideDown(250);
});
$(document).on('shopify:block:deselect', '#shopify-section-page-shopify_explorer_faq-template', function(event) {
$(event.target).find('.shopify_explorer_faq__answer').slideUp(250);
});
}());
{% endjavascript %}
3
Answers
You can do this keeping track of the current opened FAQ box. Just to fix the idea and make it as simple as possible, let’s say each of the FAQ boxes has an id and the boxes themselves are divs:
You can get the behavior you’re looking for like this:
You can achieve your desired behaviour by simply adding a line at the top of your first function that uses the
.not()
selector:HTML
Assuming the HTML is a alternating pattern of
.question
and.answer
scheme.Narrow down the primary selector to
.faq
.$("body")
and$(document)
should be used for certain events like"key"
or"load"
event types — not common events like"click"
.jQuery
The second parameter
event.data
is used to designatethis
(in this circumstance is alsoevent.target
). In the example below.question
isthis
:Reference
$(this).next('.answer')
with a variable. A variable referencing a jQuery Object is commonly prefixed with a$
(recommended but not required).The desired behavior is that of an accordion:
When an element among multiple alike element siblings is clicked (
.question
that isthis
orevent.target
), will toggle open (and/or its associated element –$answer
) if it was originally closed and vice versa.All sibling elements will close with the exception of
this
(and associated elements if applicable). The exception can be selected by using the.not()
method.'shopify:block:select/deselect'
events are non-standard events that are unique to the Shopify platform. Not 100% sure if the following would work, but if they can be delegated with the.on()
method, then it could probably be triggered with the.trigger()
method.Demo