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/
JavaScript
x
9
1
$(document).ready(function() {
2
$("#button").on("click", function() {
3
$("#collapse").slideToggle("slow");
4
if ($(this).val() == "Hide")
5
$(this).val("Show");
6
else
7
$(this).val("Hide");
8
});
9
});
JavaScript
1
5
1
<script src="http://code.jquery.com/jquery-1.10.2.js"></script>
2
<input type="button" value="Hide" id="button">
3
<div id="collapse">
4
Hello World
5
</div>
Advertisement
Answer
Since you’re using jQuery, you can use the <input type="image">
and change the src
attribute using .attr("src"
.
JavaScript
1
12
12
1
$(document).ready(function() {
2
$("#button").on("click", function() {
3
$("#collapse").slideToggle("slow");
4
if ($(this).val() == "Hide") {
5
$(this).val("Show");
6
$(this).attr("src","https://www.gravatar.com/avatar/2e83e2d35f0b889da7d5905c7bf574c2?s=32&d=identicon&r=PG&f=1");
7
} else {
8
$(this).val("Hide");
9
$(this).attr("src","https://www.gravatar.com/avatar/2e83e2d00f0b889da7d5905c7bf574c2?s=32&d=identicon&r=PG&f=1");
10
}
11
});
12
});
JavaScript
1
5
1
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
2
<input type="image" value="Hide" id="button" src="https://www.gravatar.com/avatar/2e83e2d00f0b889da7d5905c7bf574c2?s=32&d=identicon&r=PG&f=1"></button>
3
<div id="collapse">
4
Hello World
5
</div>