0

What I want to achieve is a simple tab function.

I have 3 images and a div showTab.

When i click in one of the images, the clicked image should take the active class and show inside showTab div and other image should take inActive class.

I'm totally a newbie in Javascript so forgive me for my ignorance.

For now only the first li inside my ul works. The others do not show when i click on them.

HTML:

<div class="tab-container">
  <div class="showtab active">
  </div>
  <ul class="tabs">
    <li class="tab tab1">
    <img src="https://images.unsplash.com/photo-1550364387-ffbad4f8e9b2?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=634&q=80" alt="foto1" class='img'>
    </li>
    <li class="tab tab2">
     <img src="https://images.unsplash.com/photo-1550368759-0fdb22fe8020?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=634&q=80" alt="foto2" class='img'>
    </li>
    <li class="tab tab3">
      <img src="https://images.unsplash.com/photo-1550371554-387863e7bd38?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=634&q=80" class='img inActive'>
    </li>
  </ul>
</div>

CSS:

*{
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

ul li{
  list-style: none;
}

.showtab{
  width: 200px;
  height: 100px;
  color: red;
  font-weight: bold;
  display: flex;
  margin-bottom: 20px;
}

.showtab img{
  width: 100%;
}

.tabs{
  display: flex;
}

.tabs li{
  display: flex;
  cursor: pointer;
  width: 100px;
  height: 100px;
  margin-right: 10px;
}

.tabs li img{
  width: 100%;
}

.active{
  color: red;
  border: 1px solid red;
  opacity: 1;
}

.inActive{
  color: blue;
   border: 1px solid blue;
  opacity: .3;
}

JS:

var tabs = document.querySelector('.tabs');
var tab = document.querySelector('.tab');
var showTab = document.querySelector('.showtab');


tab.addEventListener('click', function(event){
  event.stopPropagation();
  var content = event.currentTarget.innerHTML;

  tab.classList.add('active');
  showTab.classList.add('active');
  showTab.innerHTML = content;

  console.log(this);
});

Here is the demo in jsFiddle:

VenRus
  • 41
  • 1
  • 9
  • 2
    you need to loop through the results and apply the event listener on each. You probably also want to use `querySelectorAll` - `querySelector` only returns the first matching element – Pete Feb 18 '19 at 13:57
  • 1
    That’s because you selected only the first LI to begin with, because `querySelector` only selects one single element. You want querySelectorAll, and then a loop over the items. – 04FS Feb 18 '19 at 13:57

1 Answers1

1

The .querySelector() function only returns the first matching element. You can use .querySelectorAll() instead and then iterate through the returned list:

var tabs = document.querySelectorAll(".tab");
tabs.forEach(tab => {
  tab.addEventListener( ... );
});
Pointy
  • 405,095
  • 59
  • 585
  • 614