Home > other >  I want to short the given jquery code but I'm new to this so I am asking for seniors
I want to short the given jquery code but I'm new to this so I am asking for seniors

Time:08-16

In this jQuery part there are many repetition and I try using loop but when I try to click a button, it gives all the buttons response at the same time. please help

$('.btn1').mouseenter(function(){
  if($('.pop1').css('opacity') == "0")
    $('.pop1').css('opacity','1')
})

$('.btn2').mouseenter(function(){
  if($('.pop2').css('opacity') == "0")
    $('.pop2').css('opacity','1')
})

$('.btn3').mouseenter(function(){
  if($('.pop3').css('opacity') == "0")
    $('.pop3').css('opacity','1')
})
  

$('.btn1').mouseleave(function(){
  if($('.pop1').css('opacity') == "1")
    $('.pop1').css('opacity','0')
})

$('.btn2').mouseleave(function(){
  if($('.pop2').css('opacity') == "1")
    $('.pop2').css('opacity','0')
})

$('.btn3').mouseleave(function(){
  if($('.pop3').css('opacity') == "1")
    $('.pop3').css('opacity','0')
})

CodePudding user response:

There may be better ways using a single class and DOM navigation relative to $(this). But you can also just use a loop to substitute the loop index into the class names.

for (let i = 1; i <= 3; i  ) {
  $(`.btn${i}`).hover(function() {
    if ($(`.pop2${i}`).css('opacity') == "0")
      $(`.pop2${i}`).css('opacity', '1')
  }, function() {
    if ($(`.pop2${i}`).css('opacity') == "1")
      $(`.pop2${i}`).css('opacity', '0')
  });
}

CodePudding user response:

You need to post the HTML. If you have the buttons and the pops in two different containers you can do this

$('.btn').on("mouseenter mouseleave", function(e) { 
  $('.pop').eq($(this).index()).toggle(e.type === "mouseenter")
})
.pop { display: none;}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<div>
  <button >One</button>
  <button >Two</button>
  <button >Three</button>
</div>

<div>
  <div >One</div>
  <div >Two</div>
  <div >Three</div>
</div>

  • Related