I am trying to make a play / pause button. This is what I have right now. Here is the html.
<img alt="play" src="img/play.png" id="imgClickAndChange" onclick="changeImage()" class="hidden-xs hidden-sm" style="position: relative; width: 10%; z-index: 10000; margin: 0 auto; top: 42%;"/>
Here is the javascript:
function changeImage() {
if (document.getElementById("imgClickAndChange").src = "../final_copy/img/play.png")
{
document.getElementById("imgClickAndChange").src = "../final_copy/img/pause.png";
}
else {
if (document.getElementById("imgClickAndChange").src = "../final_copy/img/pause.png")
{
document.getElementById("imgClickAndChange").src = "../final_copy/img/play.png";
}
}
}
I know th second "if" probably isn't needed but neither way works. I can only get the image to change from the play image to the pause image but when I click it again it doesn't change back.
Thanks for the help!
You are comparing those src values wrong. Use ==
instead of =
if (document.getElementById("imgClickAndChange").src == "../final_copy/img/play.png") {
document.getElementById("imgClickAndChange").src = "../final_copy/img/pause.png";
}
else {
if (document.getElementById("imgClickAndChange").src == "../final_copy/img/pause.png") {
document.getElementById("imgClickAndChange").src = "../final_copy/img/play.png";
}
}
If its a simple toggle function, you'd need just one check:
function changeImage() {
if (document.getElementById("imgClickAndChange").src == "../final_copy/img/play.png") {
document.getElementById("imgClickAndChange").src = "../final_copy/img/pause.png";
}else{
document.getElementById("imgClickAndChange").src = "../final_copy/img/play.png";
}
}
you need var isPasued=false; switch image src!
var isPaused=false;
var imgObj=document.querySelect("img")[0]; //edit this
imgObj.addEventListener("click",function(){
if(!isPaused){
imgObj.src="../final_copy/img/play.png";
isPaused=true;
}
else
{
imgObj.src="../final_copy/img/pause.png";
isPaused=false;
}
});
= is == I agree the one answer in up!
var element = "document.getElementById("imgClickAndChange").src",
play = "../final_copy/img/play.png",
pause = "../final_copy/img/pause.png";
if (element == play) {
element = pause;
} else {
if (element == pause) {
element = play";
}
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.