I'm quite new to javaScript and jQuery and wrote the following function to creat some dynamic tabs. I'd be very interested to know how professional programmers would improve this code.
JavaScript
$(document).ready(function(){
function createVerticalTabs(options){
var container = options["container"];
var parentElement = options["parentElement"];
var childElement = options["childElement"];
var firstElement = options["firstElement"];
var tabClass = options["tabClass"];
var tabClassActive = options["tabClassActive"];
var closeOtherElements = options["closeOtherElements"]
var preventEvent = options["preventEvent"];
if(firstElement){
$(container+" "+childElement).not(":first").hide();
classToggle($(container+" "+childElement+":first").prev(parentElement), tabClass, tabClassActive);
}else{
$(container+" "+childElement).hide();
}
/* Click event */
$(container+" > "+parentElement).on("click", function(event){
if(preventEvent == true){
event.preventDefault();
}
/* Check if there're other active elements and close them if requested*/
if(closeOtherElements){
var otherActiveElement = $(this).parent().children(childElement);
if($(otherActiveElement).is(":visible")){
$(otherActiveElement).slideUp("slow");
classToggle($(otherActiveElement).prev(parentElement), tabClassActive, tabClass);
}
}
/* Show requested element */
var details = $(this).next(childElement);
if($(details).is(":visible")){
classToggle($(this), tabClassActive, tabClass);
$(details).slideUp("slow");
}else{
classToggle($(this), tabClass, tabClassActive);
$(details).slideDown("slow");
}
});
function classToggle(obj, remove, add){
return obj.removeClass(remove).addClass(add);
}
}
var options = {
container: ".testBox",
parentElement: "a",
childElement: "p",
tabClass: "title",
tabClassActive: "active",
firstElement: true,
closeOtherElements: true,
preventEvent: true
};
var options2 = {
container: ".testBox2",
parentElement: "h3",
childElement: "p",
tabClass: "title",
tabClassActive: "active",
firstElement: false,
closeOtherElements: false,
preventEvent: true
};
createVerticalTabs(options);
createVerticalTabs(options2);
});
HTML
<div class="testBox">
<a href="#">Anchor 1</a><p>Details of Anchor 1</p>
<a href="#">Anchor 2</a><p>Details of Anchor 2</p>
<a href="#">Anchor 3</a><p>Details of Anchor 3</p>
<a href="#">Anchor 4</a><p>Details of Anchor 4</p>
</div>
<div class="testBox2">
<h3>Anchor 1</h3><p>Details of Anchor 1</p>
<h3>Anchor 2</h3><p>Details of Anchor 2</p>
<h3>Anchor 3</h3><p>Details of Anchor 3</p>
<h3>Anchor 4</h3><p>Details of Anchor 4</p>
</div>
<div style="clear:both"></div>
CSS
.testBox, .testBox2{ float:left; height:500px; margin:10px; }
.testBox a{ display:block; }
.testBox2 h3{ margin:0; padding:0; }
.title{ font-weight:bold; }
.active{ background:#333; border:#000 1px solid; color:#fff; }
== true
, it’s not a useful comparison. \$\endgroup\$options.tabClass
in your code \$\endgroup\$