I have made my own accordion in elementor using CSS and Javascript. If works fine, except for one problem: they stay open when other tabs are opened. How should I modify the code, so that the other tabs collapse when one tab is opened.
Here is the CSS code.
body:not(.elementor-editor-active) .toggle-content{
display: none;
}
.toggle-trigger {
cursor: pointer;
}
.arrow i{
transition-duration: 0.5s;
}
.tab_active .arrow i{
transition-property: transform;
-ms-transform:rotate(45deg) !important; /* IE 9*/
transform: rotate(45deg) !important;
transition-duration: 0.5s;
}
And here is the JavaScript.
jQuery(document).ready(function($){
jQuery(".toggle-trigger").on("click", function(){
let $this = $(this);
if($this.hasClass('tab_active')){
$this.removeClass('tab_active');
$this.next(".toggle-content").slideUp(200);
} else {
$this.toggleClass('tab_active');
$this.next(".toggle-content").slideDown(200)
}
})
});
The class .toggle-trigger is applied to the inner-section which is to be used a the title-tab and .toggle-content is applied to the inner-section which slides down on click.
The class .arrow is for the icon to change its orientation on click.
Also, when the accordion is opened, the position of the tab moves a bit up and the content slides down, how should I change it so that the position of the tab is fixed and only the content slides down?
I have tried using addClass instead of toggle class and removing the tab-active class using jQuery(‘.toggle-trigger).removeClass(‘tab-active’) but it didn’t work. Also, according to suggestions to this question on StackOverflow I also tried to remove class from other tabs using not($this). I am new to JavaScript and would appreciate any help.
2
Answers
Try this
You need to clear the active first, then add active class on the current tab.
You can try closing all open tabs before opening the selected tab
You could try adding a CSS
position: relative
to the parent element of the tab. This will fix the position of the tab relative to its parent while the content slides down below it