skip to Main Content

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')
})

2

Answers


  1. 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')
      });
    }
    
    Login or Signup to reply.
  2. 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 class="btn">One</button>
      <button class="btn">Two</button>
      <button class="btn">Three</button>
    </div>
    
    <div>
      <div class="pop">One</div>
      <div class="pop">Two</div>
      <div class="pop">Three</div>
    </div>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search