Tabs en Javascript

by shakibdshy

HTML

<div class="tab">
  <button data-city="london" class="tablinks">London</button>
  <button data-city="paris" class="tablinks">Paris</button>
  <button data-city="tokyo" class="tablinks">Tokyo</button>
</div>

<div id="london" class="tabcontent">
  <h3>London</h3>
  <p>London is the capital city of England.</p>
</div>

<div id="paris" class="tabcontent">
  <h3>Paris</h3>
  <p>Paris is the capital of France.</p>
</div>

<div id="tokyo" class="tabcontent">
  <h3>Tokyo</h3>
  <p>Tokyo is the capital of Japan.</p>
</div>

 <div class="tab">
  <button data-city="1" class="tablinks">London</button>
  <button data-city="2" class="tablinks">Paris</button>
  <button data-city="3" class="tablinks">Tokyo</button>
</div>

<div id="1" class="tabcontent">
  <h3>London</h3>
  <p>London is the capital city of England.</p>
</div>

<div id="2" class="tabcontent">
  <h3>Paris</h3>
  <p>Paris is the capital of France.</p>
</div>

<div id="3" class="tabcontent">
  <h3>Tokyo</h3>
  <p>Tokyo is the capital of Japan.</p>
</div>

CSS

/* Style the tab */
div.tab {
    overflow: hidden;
    border: 1px solid #ccc;
    background-color: #f1f1f1;
}

/* Style the buttons inside the tab */
div.tab button {
    background-color: inherit;
    float: left;
    border: none;
    outline: none;
    cursor: pointer;
    padding: 14px 16px;
    transition: 0.3s;
}

/* Change background color of buttons on hover */
div.tab button:hover {
    background-color: #ddd;
}

/* Create an active/current tablink class */
div.tab button.active {
    background-color: #ccc;
}

/* Style the tab content */
.tabcontent {
    display: none;
    padding: 6px 12px;
    border: 1px solid #ccc;
    border-top: none;
}

JavaScript

function openTab(evt) {
console.log('salut');
    // Déclarer les variables
    var i, tabcontent, tablinks;
		var cityName = this.dataset.city;
    // Selectionner TOUS les éléments class="tabcontent" puis les cacher
    tabcontent = document.getElementsByClassName("tabcontent");
    for (i = 0; i < tabcontent.length; i++) {
        tabcontent[i].style.display = "none";
    }

    // GSelectionner TOUS les éléments class="tablinks" puis retirer la class "active"
    tablinks = document.getElementsByClassName("tablinks");
    for (i = 0; i < tablinks.length; i++) {
        tablinks[i].className = tablinks[i].className.replace(" active", "");
    }

    // Montrer la tab courante, puis ajouter la class "active" au bouton
    document.getElementById(cityName).style.display = "block";
    evt.currentTarget.className += " active";
}



var tabs = document.querySelectorAll('button.tablinks');
for(var i=0; i<tabs.length; i++) {
	tabs[i].addEventListener('click', openTab);
}