Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

159
Visualizações
Show ID onclick JS

Hi sorry in advance if this has already been asked but I can't find the answer.

I have a set of links that trigger certain ids to show onclick, it works but the one link is suppose to trigger 2 ids to show. My javascript knowledge is not great. Thanks for any help.

Here is my codepen https://codepen.io/louise-fourie/pen/abVdwyZ

      
<li>
        <a href="#!"  class="article-btn" onclick="show('el-57d5b6f71db32029');">Fitness & Wellness</a>
      </li>
      <li>
        <a href="#!"  class="article-btn"  onclick="show('el-57d5b6f71db32029');show('el-e881a23a64890108');">Business</a>
      </li>
      
      <li>
        <a href="#!"  class="article-btn" onclick="show('el-65ebd7b2380005a1');">Arts & Entertainment</a>
      </li>
    </ul>

<div class="articles">
  <div id="el-57d5b6f71db32029">fitness</div>
   <div  id="el-e881a23a64890108">business</div>
  <div  id="el-65ebd7b2380005a1">art</div>
</div>
<script>
var divs = ["el-57d5b6f71db32029", "el-e881a23a64890108", "el-65ebd7b2380005a1"];

        var visibleId = null;
        function show(id) {
           for(i = 0; i < divs.length; i++) {
          if(visibleId !== id) {
            
            visibleId = id;
          
          }
           }
          hide();
        }
        function hide() {
          var div, i, id;
          for(i = 0; i < divs.length; i++) {
            id = divs[i];
            div = document.getElementById(id);
            if(visibleId === id) {
              div.style.display = "block";
            } else {
              div.style.display = "none";
            }
          }
        }
</script>
about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

There is something fishy with your show-hide logic.

Check out my suggestion below, where you can pass an array of IDs, which you want to show. All other elements will be hidden.

function onClick(elements) {
  document.querySelectorAll('.articles div').forEach(articleDiv => articleDiv.style.display = 'none');

  elements.forEach(element => {
    const domEl = document.querySelector('#' + element)
    domEl.style.display = 'block';
  })
}
<ul>

  <li>
    <a href="#!" class="article-btn" onclick="onClick(['fitness'])">Fitness & Wellness</a>
  </li>
  <li>
    <a href="#!" class="article-btn" onclick="onClick(['art', 'business'])">Business</a>
  </li>

  <li>
    <a href="#!" class="article-btn" onclick="onClick(['art'])">Arts & Entertainment</a>
  </li>
</ul>

<div class="articles">
  <div id="fitness">fitness</div>
  <div id="business">business</div>
  <div id="art">art</div>
</div>

<script>
</script>

about 4 years ago · Juan Pablo Isaza Relatório

0

Your function seems to be running, but every time you receive an ID in your function, you hide everything else with the "hide" function, so in the end, the last ID sent, is the only one that will show, try this:

Call the function once, but pass the IDs as one string separated by commas

<a href="#!"  class="article-btn"  onclick="show('el-57d5b6f71db32029,el-e881a23a64890108')">Business</a>

Then change your "show" function like this:

    function show(ids) {
      let idArr = ids.split(",");
      divs.forEach( x => {
                   div = document.getElementById(x);
                   div.style.display = (idArr.includes(x) ? "block" : "none");
      });
    }
    

What this does, is that it will create an array of IDs based on the parameter you send, and for each item it will check if the ID was sent and show/hide it.

Please let me know if this helps or if you need more details.

EDIT: Formatting in the JavaScript code and simplifying it. Please also note that here I am not validating if the an element with the ID exists, it is only to show you how it can work. It will need additional validations

about 4 years ago · Juan Pablo Isaza Relatório

0

You can try it

<ul>    
<li>
        <a href="#!"  class="article-btn" data-id="el-57d5b6f71db32029">Fitness & Wellness</a>
      </li>
      <li>
        <a href="#!"  class="article-btn"  data-id="el-57d5b6f71db32029;el-e881a23a64890108">Business</a>
      </li>
      
      <li>
        <a href="#!"  class="article-btn" data-id="el-65ebd7b2380005a1">Arts & Entertainment</a>
      </li>
    </ul>

<div class="articles">
  <div id="el-57d5b6f71db32029" style="display:none;">fitness</div>
   <div id="el-e881a23a64890108" style="display:none;">business</div>
  <div id="el-65ebd7b2380005a1" style="display:none;">art</div>
</div>
<script>
document.querySelectorAll('.article-btn').forEach(item => {
  item.addEventListener('click', event => {
    show((item.getAttribute('data-id')).split(";"));
  })
})

const show = (id) => {
    document.querySelectorAll('.articles>div').forEach(item => {
      if(id.includes(item.getAttribute('id'))){
           item.style["display"] = "block";
      }else{
           item.style["display"] = "none";                    
      } 
    });
}     
</script>
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda