I have a problem with my accordion. The first time I click any of the title bars to collapse that item, it has a sharp pop to close it. I'm using slideUp(), but it doesn't appear to be used initially. If I keep clicking the title bar for that item, slideUp()/slideDown() starts to work.
Additionally, my approach is not very efficient for reusability. If you look at the click event, I am creating it for each accordion item. How do I set it so that whether it is 'item1
', 'item2
', 'item3
', and more, the accordion will work for each item without having to create a new click event for each?
I have a jsfiddle posted here: http://jsfiddle.net/Jfd9n/1/
Thank you for your help!
// Accordion Plugin
(function($){
$.fn.scaccordion = function(options){
var defaults = {
// Variables Here
};
var options = $.extend(defaults, options);
$('div.accordionitem').addClass('active');
$('div.accordionitem').slideDown();
console.log('Add class: active to all div.accordionitem elements.')
// Click Event for item1: Open
$(this).find('div.accordionitem.item1').on('click', function (e) {
e.preventDefault();
console.log('Accordion Item 1 Clicked');
if ($('div.accordionitem.item1').hasClass('active')) {
$('div.accordionitem.item1 div.accordion_content').slideUp();
$('div.accordionitem.item1').removeClass('active');
} else {
$('div.accordionitem.item1 div.accordion_content').slideDown();
$('div.accordionitem.item1').addClass('active');
}
});
// Click Event for item2: Open
$(this).children('div.accordionitem.item2').on('click', function (e) {
e.preventDefault();
console.log('Accordion Item 2 Clicked');
if ($('div.accordionitem.item2').hasClass('active')) {
$('div.accordionitem.item2 div.accordion_content').slideUp();
$('div.accordionitem.item2').removeClass('active');
} else {
$('div.accordionitem.item2 div.accordion_content').slideDown();
$('div.accordionitem.item2').addClass('active');
}
});
// Click Event for item1: Open
$(this).children('div.accordionitem.item3').on('click', function (e) {
e.preventDefault();
console.log('Accordion Item 3 Clicked');
if ($('div.accordionitem.item3').hasClass('active')) {
$('div.accordionitem.item3 div.accordion_content').slideUp();
$('div.accordionitem.item3').removeClass('active');
} else {
$('div.accordionitem.item3 div.accordion_content').slideDown();
$('div.accordionitem.item3').addClass('active');
}
});
};
})(jQuery);
$('div.taccholder').scaccordion();
How about this see update jsfiddle
Your code: