The most correct way to do this is by using a CSS class.
And in this simple case you do not even need jQuery.
You can iterate through these elements and add them to an event dropper. At the time of iterating the elements it is important to save the index of this element, since each #fonte li
corresponds to a ul.item
. Hence, you have used var index = j;
in the example below. So by creating a new scope, I keep this index for later use.
Changes in 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>
jsFiddle: link