Change display property with jQuery

Asked

Viewed 2,131 times

1

I want to change the display of div content block, as it is clicking and hiding the one that was previously clicked.

How could I do that to jQuery?

.conteudo_1 {
  display: none
}

.conteudo_2 {
  display: none
}

.conteudo_3 {
  display: none
}
<ul>

  <li><a href="">Conteudo 1</a></li>
  <li><a href="">Conteudo 2</a></li>
  <li><a href="">Conteudo 3</a></li>

</ul>

<div class="conteudo_1">
  <p>
    texto conteudo 1
  </p>
</div>

<div class="conteudo_2">
  <p>
    texto conteudo 1
  </p>
</div>

<div class="conteudo_3">
  <p>
    texto conteudo 1
  </p>
</div>

  • 1

    You want to change the display or hide and show widget ? Hide and show is just use show/hide or toggle.

  • I want to change the display of div to block, as long as it is clicking and hiding the one that was previously clicked

  • 1

    Behold this question that the goal is quite similar to your

2 answers

1


Something like that?

function toggleDiv(conteudo){
  $('div.conteudo').removeClass('active');
  if(conteudo == 1){
    $('div.conteudo_1').addClass('active');
  }else if(conteudo == 2){
    $('div.conteudo_2').addClass('active');
  }else if(conteudo == 3){
    $('div.conteudo_3').addClass('active');
  } 
}
.conteudo_1{
  display:none
}
.conteudo_2{
  display:none
}
.conteudo_3{
  display:none
}

.active{
  display:block!important;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<ul>

<li><a href="#" onclick="toggleDiv(1)">Conteudo 1</a></li>
<li><a href="#" onclick="toggleDiv(2)">Conteudo 2</a></li>
<li><a href="#" onclick="toggleDiv(3)">Conteudo 3</a></li>

</ul>

<div class="conteudo conteudo_1">
<p>
texto conteudo 1
</p>
</div>

<div class="conteudo conteudo_2">
<p>
texto conteudo 2
</p>
</div>

<div class="conteudo conteudo_3">
<p>
texto conteudo 3
</p>
</div>

I just created a function that hides all Divs with the class .conteudo and I display the one that was clicked.

1

I think you can simplify the code, and still reuse easily

function toggleDiv(conteudo){
  $('.conteudo').hide();
  if(conteudo == 1) {
    $('.conteudo_1').show();
  } else if(conteudo == 2) {
    $('.conteudo_2').show();
  } else if(conteudo == 3) {
    $('.conteudo_3').show();
  } 
}
.conteudo{
  display:none
}   
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<ul>
<li><a href="#" onclick="toggleDiv(1)">Conteudo 1</a></li>
<li><a href="#" onclick="toggleDiv(2)">Conteudo 2</a></li>
<li><a href="#" onclick="toggleDiv(3)">Conteudo 3</a></li>
</ul>

<div class="conteudo conteudo_1">
<p>texto conteudo 1</p>
</div>

<div class="conteudo conteudo_2">
<p>texto conteudo 2</p>
</div>

<div class="conteudo conteudo_3">
<p>texto conteudo 3</p>
</div>

  • Good, you’ve improved too :D

Browser other questions tagged

You are not signed in. Login or sign up in order to post.