The right way to do this is by using a CSS class.
And in this simple case it’s not even necessary jQuery.
You can iterate these elements and add an event receiver to them. When iterating elements it is important to store the index of that element, therefore to each #fonte li
corresponds to a ul.item
. That’s why I used var index = j;
in the example below. So, creating a new scope, I save this index for later use.
Changes in the CSS:
#conteudo ul {
position: absolute; /* opcional */
top: 0px; /* opcional */
transition: opacity .8s;
opacity: 0;
}
.open {
opacity: 1 !important;
}
Javascript:
(function () { // criar um escopo próprio para não exportar variáveis para o espaço global
var fontes = document.querySelectorAll('#fonte .source li');
var conteudos = document.querySelectorAll('ul.item');
for (var j = 0; j < fontes.length; j++) { // percorrer as fontes
(function () { // criar novo escopo para guardar em memória as variáveis declaradas aqui dentro
var index = j; // para saber qual o index do elemento clicado
fontes[j].addEventListener('click', function () {
for (var i = 0; i < conteudos.length; i++) {
conteudos[i].classList.remove('open');
}
conteudos[index].classList.add('open');
});
})();
}
})();
(function () {
var fontes = document.querySelectorAll('#fonte .source li');
var conteudos = document.querySelectorAll('ul.item');
for (var j = 0; j < fontes.length; j++) {
(function () {
var index = j;
fontes[j].addEventListener('click', function () {
for (var i = 0; i < conteudos.length; i++) {
conteudos[i].classList.remove('open');
}
conteudos[index].classList.add('open');
});
})();
}
})()
#fonte {
display: block;
width: 200px;
height: 200px;
outline: dotted;
}
#conteudo {
position: absolute;
top: 15px;
left: 210px;
display: block;
width: 200px;
height: 200px;
outline: dotted;
}
.source li {
display: block;
height: 35px;
outline: dotted;
padding: 5px
}
.item li {
width: 36px;
height: 36px;
display: block;
outline: dotted;
padding: 5px;
float: left;
}
#conteudo ul {
position: absolute;
top: 0px;
transition: opacity .8s;
opacity: 0;
}
.open {
opacity: 1 !important;
}
<div id="fonte">
<ul class="source">
<li>EMPRESA 1</li>
<li>EMPRESA 2</li>
<li>EMPRESA 3</li>
</ul>
</div>
<div id="conteudo">
<ul class="item" id=emp1>
<li>E1, li 1</li>
<li>E1, li 2</li>
<li>E1, li 3</li>
</ul>
<ul class="item" id=emp2>
<li>E2 li 1</li>
<li>E2, li 2</li>
</ul>
<ul class="item" id=emp3>
<li>E3, li 1</li>
<li>E3, li 2</li>
</ul>
</div>
Did you manage to solve this question?
– Sergio