Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jquery On Click, Hide and Show div Multi Items

Can someone help me?

I want to hide div when clicking, but other div is still active, this code actually works fine but this code is less effective and time consuming, is there a way to make it easier or is there a similar way, this I will not only input 3 items but more than 10 item

$(function() {
  $(document).on("click", "div.myDiv", function(e) {
    $('.goo').css('display', 'none');
    $('.goo2').css('display', 'block');
    $('.goo3').css('display', 'block');
  });
})

$(function() {
  $(document).on("click", "div.myDiv2", function(e) {
    $('.goo').css('display', 'block');
    $('.goo2').css('display', 'none');
    $('.goo3').css('display', 'block');
  });
})

$(function() {
  $(document).on("click", "div.myDiv3", function(e) {
    $('.goo').css('display', 'block');
    $('.goo2').css('display', 'block');
    $('.goo3').css('display', 'none');
  });
})
.myDiv {
  border: 1px solid gray;
  margin: 10px;
}

.myDiv2 {
  border: 1px solid gray;
  margin: 10px;
}

.myDiv3 {
  border: 1px solid gray;
  margin: 10px;
}

.goo {
  position: absolute;
  background: rgba(0, 0, 0, 0.5);
  border-radius: 5px;
  width: 90%;
  height: 20px;
}

.goo2 {
  position: absolute;
  background: rgba(0, 0, 0, 0.5);
  border-radius: 5px;
  width: 90%;
  height: 20px;
}

.goo3 {
  position: absolute;
  background: rgba(0, 0, 0, 0.5);
  border-radius: 5px;
  width: 90%;
  height: 20px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="myDiv">
  <div class="goo"></div>
  Test1
</div>
<div class="myDiv2">
  <div class="goo2"></div>
  Test2
</div>
<div class="myDiv3">
  <div class="goo3"></div>
  Test3
</div>
like image 381
Kawaii Moe Moe Kyun Avatar asked Jan 24 '23 14:01

Kawaii Moe Moe Kyun


1 Answers

The whole point of classes, compared to IDs, is that they don't have to be unique and can be reused, avoiding you to repeat your code.

const $allGoos = $(".goo");

$(".myDiv").click(function() {
  $allGoos.show();
  $(this).find('.goo').hide();
});
.myDiv {
  border: 1px solid gray;
  margin: 10px;
}

.goo {
  position: absolute;
  background: rgba(0, 0, 0, 0.5);
  border-radius: 5px;
  width: 90%;
  height: 20px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="myDiv">
  <div class="goo"></div>
  Test1
</div>
<div class="myDiv">
  <div class="goo"></div>
  Test2
</div>
<div class="myDiv">
  <div class="goo"></div>
  Test3
</div>
<div class="myDiv">
  <div class="goo"></div>
  Test4
</div>
<div class="myDiv">
  <div class="goo"></div>
  Test5
</div>
<div class="myDiv">
  <div class="goo"></div>
  Test6
</div>
<div class="myDiv">
  <div class="goo"></div>
  Test7
</div>
like image 97
Jeremy Thille Avatar answered Jan 30 '23 09:01

Jeremy Thille