Themer Themer - 15 days ago 6
Javascript Question

Creating Tabs with a function

I am trying to create a function that will create tabs dynamically. Below is how the function will work:

function create_tabs(array_var, target_element){
/* array_var will be separated with comma
/* target_element will be appendning the final data in that elemenet
}


so if I use the above function like below:

create_tabs('First, Second, Third', 'any_element_class');


if should append the element with class "any_element_class" with the following data.

<ul class='tabs'>
<li class='tab-link current' data-tab='first'>First</li>
<li class='tab-link' data-tab='second'>Second</li>
<li class='tab-link' data-tab='third'>Third</li>
</ul>

<div id='first' class='tab-content current'></div>
<div id='second' class='tab-content'></div>
<div id='third' class='tab-content'></div>

Answer

you could pass the first parameter as array:

var array_var = ['first', 'second','third'];
create_tabs(array_var, '#any_element_class');

then loop over it in your function:

function create_tabs(array_var, element){
//...loop over array
$(element).append("<li class='tab-link' data-tab='"+array_var[i]+"'>"+array_var[i]+"</li>")
//
}
Comments