On Click i want to show button and again on click i want to hide a button

Viewed 41

i am not sure, what i should be using, please help

$(document).ready(function() {
  $('#btn2').hide()
  $("#btn1").click(function () {
   $("#btn2").show()
  });
 });
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>
  <button id="btn1">BTN 1</button>
  <button id="btn2">BTN 2</button>
</div>

4 Answers

$(document).ready(function() {
  $('#btn2').hide()
  $("#btn1").click(function () {
   $("#btn2").toggle()
  });
 });
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>
  <button id="btn1">BTN 1</button>
  <button id="btn2">BTN 2</button>
</div>

You can make use of toggle https://api.jquery.com/toggle/

$(document).ready(function() {
  $('#btn2').hide()
  $("#btn1").click(function () {
   $("#btn2").toggle()
  });
 });
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>
  <button id="btn1">BTN 1</button>
  <button id="btn2">BTN 2</button>
</div>

Hide it in HTML or CSS and then toggle it

$(function() {
  $("#btn1").on("click", function() {
    $("#btn2").toggle()
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>
  <button id="btn1">BTN 1</button>
  <button id="btn2" hidden>BTN 2</button>
</div>

You should either use $("#btn2").toggle() instead of $("#btn2").show(), or you can add an if condition to check whether the button is visible or not.

Related