Skip to content

Instantly share code, notes, and snippets.

@landsman
Last active May 8, 2018 09:12
Show Gist options
  • Select an option

  • Save landsman/d52d2b27edc382ea2053eeb1215d4ea1 to your computer and use it in GitHub Desktop.

Select an option

Save landsman/d52d2b27edc382ea2053eeb1215d4ea1 to your computer and use it in GitHub Desktop.
vanilla javascript tabs / switch content visibility
/**
* @todo: remove e argument somehow
* @param e this - context
* @param elementId - target element id
*/
function switchContent(e, elementId)
{
var another_links = e.parentNode.children;
for(var l = 0; l < another_links.length; l++)
{
another_links[l].classList.remove('active');
}
e.classList.add('active');
// content
var target_content = document.getElementById(elementId);
var another_content = target_content.parentNode.children;
for(var c = 0; c < another_content.length; c++)
{
another_content[c].classList.remove('active');
another_content[c].classList.add('hidden');
}
// set active tab
target_content.classList.remove('hidden');
target_content.classList.add('active');
}
<!-- test data array: -->
{%
set product_tabs = [
1 => {title: 't1', content: 'c1'},
2 => {title: 't2', content: 'c2'},
3 => {title: 't3', content: 'c3'}
]
%}
<!-- menu -->
<div class="tabs">
<div class="grid">
{% for key,value in product_tabs %}
<div class="col tab-{{ key }} {% if 1 == key %}active{% endif %}" onclick="switchContent(this, 'tab-{{ key }}');">
<div class="tabs__item"><span>{{ value.title }}</span></div>
</div>
{% endfor %}
</div>
</div>
<!-- content to switch visibility -->
<div class="tabs_content">
{% for key,value in product_tabs %}
<div id="tab-{{ key }}" class="{% if 1 == key %}active{% else %}hidden{% endif %}">
<p>some your content {{ value.content }}</p>
</div>
{% endfor %}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment