I'm currently developing a website for use at a conference, and I'm seeking assistance in comprehending the implications of two different strategies to achieve a certain effect:
Option 1: Utilizing .toggle()
to show or hide content
I initially opted for this method as it seems natural for users to tap an element and reveal its content. However, I encountered an issue when attempting to restrict only one div to be open at a time.
Summary: I'm facing difficulties in limiting the number of simultaneously opened elements.
Option 2: Implementing an active
class with jQuery
With this approach, I can uncover hidden content by targeting the child element (refer to code snippet below). Nonetheless, users are unable to close the content by tapping on it again. Given that I'm expanding divs horizontally, this presents challenges due to the added scroll space.
Summary: How can the active div be closed on a second click using this method?
View CodePen Demo - Check Staged site
Relevant Code Snippet
This approach involves utilizing CSS to apply the active class. While functional, I'm encountering challenges in removing the active
class from an element upon a subsequent tap. For a demonstration of how the toggle action works on the page, refer to the provided demo links above (uncomment lines 8 and 9).
$(".title").click(function() {
//remove active class from other elements
$('.post').removeClass('active');
// Bind to the div
$post = $(this);
// Apply active class on .post to manage scroll position
$post.parent().toggleClass('active');
// Toggles the hidden .content div
//$post.next().toggle(250);
$('html, body').animate({scrollLeft: $('.active').offset().left},500);
});
The corresponding .active
CSS styling is as follows:
.post .content {
display:none;
}
.active {
margin-top:-120px;
}
/* Displays the content div instead of toggling with jQuery */
.active > .content {
display:block;
}
Is there a way to merge both desired behaviors (tap to open/close, one open div only)? Which technique would be most suitable for achieving this?