I am trying to change an image to another image using the enter key with the keypress event handler. The function gets triggered and changes the image to the other one fine, and gets back to the original on another keypress(enter again) also fine, yet when I try to change it the 3rd time it just doesn't do anything. Meaning that when I try to change the original image again it doesn't do anything. I have tried to change keypress to keydown and also used the off function in vain. Can anybody tell me what is wrong here:
<script>
$(".logoheader").on("keypress",function(e) {
if(e.which == 13 || e.which == 32){
$(".logoheader").html("SKATE <img class='secondImage' src='./thought.png' align='center' width='100px' alt='logo image' /> STATE");
$(".logoheader").on("keypress", function() {
$(".logoheader").html("SK8 <img class='logoImage' src='./head.png' align='center' width='100px' alt='logo image' /> ST8");
$(".logoheader").off("keypress");
})
}});
function logoShift(){
$(".logoheader").html("SKATE <img class='secondImage' src='./thought.png' align='center' width='100px' alt='logo image' /> STATE");
$(".logoheader").click(function() {
$(".logoheader").html("SK8 <img class='logoImage' src='./head.png' align='center' width='100px' alt='logo image' /> ST8");
$(".logoheader").off("click");
});};
</script>
<html>
<h1 class="logoheader" align="center" onclick="logoShift()" tabindex=0> SK8 <img class="logoImage" src="./head.png" align="center" width="100px" alt="head" /> ST8</h1>
</html>
As you can see I have an on click function(logoShift) that is working fine, I even tried to trigger it on keypress but also in vain(it only worked for the first click without going back to the original image on the second keypress)
Just bind events on document ready and check for classname:
$(function() {
$(".logoheader").on("keypress", function(e) {
if (e.which == 13 || e.which == 32) {
if ($(this).find('img').hasClass('logoImage')) {
$(this).html("SKATE <img class='secondImage' src='https://brand.jquery.org/resources/jquery-mark-light.gif' align='center' width='100px' alt='logo image' /> STATE");
} else {
$(this).html("SK8 <img class='logoImage' src='https://brand.jquery.org/resources/jquery-mark-dark.gif' align='center' width='100px' alt='logo image' /> ST8");
}
}
});
$(".logoheader").click(function() {
if ($(this).find('img').hasClass('logoImage')) {
$(this).html("SKATE <img class='secondImage' src='https://brand.jquery.org/resources/jquery-mark-light.gif' align='center' width='100px' alt='logo image' /> STATE");
} else {
$(this).html("SK8 <img class='logoImage' src='https://brand.jquery.org/resources/jquery-mark-dark.gif' align='center' width='100px' alt='logo image' /> ST8");
}
});
});