Skip to content
Advertisement

Changing input button to images

I am new to JavaScript.
I am having trouble changing the show button and hide button to images instead.
The show button will be a different image to the hide button.
How would I go about doing this?

https://jsfiddle.net/ej0r4amd/2/

$(document).ready(function() {
  $("#button").on("click", function() {
    $("#collapse").slideToggle("slow");
    if ($(this).val() == "Hide")
      $(this).val("Show");
    else
      $(this).val("Hide");
  });
});
<script src="http://code.jquery.com/jquery-1.10.2.js"></script>
<input type="button" value="Hide" id="button">
<div id="collapse">
  Hello World
</div>

Advertisement

Answer

Since you’re using jQuery, you can use the <input type="image"> and change the src attribute using .attr("src".

$(document).ready(function() {
  $("#button").on("click", function() {
    $("#collapse").slideToggle("slow");
    if ($(this).val() == "Hide") {
      $(this).val("Show");
      $(this).attr("src","https://www.gravatar.com/avatar/2e83e2d35f0b889da7d5905c7bf574c2?s=32&d=identicon&r=PG&f=1");
    } else {
      $(this).val("Hide");
      $(this).attr("src","https://www.gravatar.com/avatar/2e83e2d00f0b889da7d5905c7bf574c2?s=32&d=identicon&r=PG&f=1");
    }
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="image" value="Hide" id="button" src="https://www.gravatar.com/avatar/2e83e2d00f0b889da7d5905c7bf574c2?s=32&d=identicon&r=PG&f=1"></button>
<div id="collapse">
  Hello World
</div>
Advertisement