how can i call element by using this in jquery

Viewed 44

how can i call element by using this in jquery im doing loop each loop have div have 2 buttons play and pasue i want to hide play when i press play and show pause

    $("#play").click(function(){
   
    $(this).$("#play").css("display", "none");
    $(this).$("#pause").css("display", "block");
  });

  $("#pause").click(function(){
    $(this).$("#pause").css("display", "none");
    $(this).$("#play").css("display", "block");
    
  });
2 Answers

HTML:

<div>
  <div>1
    <button class="play">play</button>
    <button class="pause">pause</button>
  </div>
  <div>2
    <button class="play">play</button>
    <button class="pause">pause</button>
  </div>
  <div>3
    <button class="play">play</button>
    <button class="pause">pause</button>
  </div>
</div>

JavaScript:

$(".play").click(function(){
  $(this).parent().find('.pause').show();
  $(this).parent().find('.play').hide();
});

$(".pause").click(function(){
  $(this).parent().find('.pause').hide();
  $(this).parent().find('.play').show();
});

You can loop through your buttons and give each button an eventListener by using addEventListener().
When the button gets pressed you apply your toggle functionality to the pressed button by using $(this) and the next() prev() function.This solution assumes the play button is always before the stop button.

const elements = [...$('div > button')]

// initially hide the Pause buttons
const pauseButtons = Array.from($('.pause'));

pauseButtons.forEach((y) => {
y.style.visibility = "hidden";
})


elements.forEach((x) => {

  x.addEventListener('click', function() {
    $(this).css("visibility", "hidden")
    $(this).next().css("visibility", "visible")
  })
  x.addEventListener('click',function() {
    $(this).css("visibility", "hidden")
    $(this).prev().css("visibility", "visible")
  })
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div>DIV1
  <button class="play">Play</button>
  <button class="pause">Pause</button>
</div>
<div>DIV2
  <button class="play">Play</button>
  <button class="pause">Pause</button>
</div>
<div>DIV3
  <button class="play">Play</button>
  <button class="pause">Pause</button>
</div>

Related