What is the best way to animate various sprites using distinct buttons in HTML and CSS?

I've been experimenting with animating a sprite by using different onClick button triggers. I encountered an issue where only one of the buttons works correctly in the fiddle. However, in my local file version, the other buttons work but only once and they do not reset. Essentially, some buttons play their animations, but only in a specific order and then become unresponsive to further clicks. My assumption was that the removeClass function would revert the sprite back to its original state after a certain period, allowing me to click on another button and restart the animation anew.

HTML

<div class="bannerimg" div id="bannerimg"></div>
<div id="sunbutton" class="sunbutton"></div>
<div id="waterbutton" class="waterbutton"></div>
<div id="foodbutton" class="foodbutton"></div>

Javascript

$('#sunbutton').click(function() 
{
$('.bannerimg').addClass('suncheck');
setTimeout(function() 
{ $(this).removeClass('suncheck'); }
, 1000);
});

$('#waterbutton').click(function() 
{
$('.bannerimg').addClass('watercheck');
setTimeout(function() 
{ $(this).removeClass('watercheck'); }
, 2000);
});

$('#foodbutton').click(function() 
{
$('.bannerimg').addClass('foodcheck');
setTimeout(function() 
{ $(this).removeClass('foodcheck'); }
, 1);
});

CSS

.bannerimg {
background-image: url(http://www.elainemcheung.com/wp-content/uploads/2014/03/sprite.png);
width: 669px;
height: 560px;
}

.suncheck {
animation: sun steps(7) 1s infinite;
-webkit-animation: sun steps(7) 1s infinite;
-moz-animation: sun steps(7) 1s infinite;
}

@keyframes sun {
0% {background-position: 0 0; }
100% {background-position: -4683px 0;}
}
@-webkit-keyframes sun {
0% {background-position: 0 0; }
100% {background-position: -4683px 0;}
}
@-moz-keyframes sun {
0% {background-position: 0 0; }
100% {background-position: -4683px 0;}
}

.foodcheck {
animation: food 3s steps(12) 0.15s infinite;
-webkit-animation: food 3s steps(12) 0.15s infinite;
-moz-animation: food 3s steps(12) 0.15s infinite;
}

@keyframes food {
0% {background-position: 0 -560; }
100% {background-position: -8028px -560;}
}
@-webkit-keyframes food {
0% {background-position: 0 -560; }
100% {background-position: -8028px -560;}
}
@-moz-keyframes food {
0% {background-position: 0 -560; }
100% {background-position: -8028px -560;}
}

.watercheck {
animation: water steps(15) 2s infinite;
-webkit-animation: water steps(15) 2s infinite;
-moz-animation: water steps(15) 2s infinite;
}

@keyframes water {
0% {background-position: 0 -1120; }
100% {background-position: -10035px -1120;}
}
@-webkit-keyframes water {
0% {background-position: 0 -1120; }
100% {background-position: -10035px -1120;}
}
@-moz-keyframes water {
0% {background-position: 0 -1120; }
100% {background-position: -10035px -1120;}
}

.sunbutton {
position:relative;
margin:10px auto;
color: white;
text-align: center;
text-shadow: 0 1px 0 rgba(0,0,0,.5);
font-size: .9em;
cursor: pointer;
}
.sunbutton:after {
top: 0px;
left: 500px;
position: absolute;
display: block;
padding: 5px 0;
width: 125px;
border: 1px solid #894603;
border-radius: 4px;
background: linear-gradient(to bottom,rgba(247,147,30,1) 0%,rgba(216,123,25,1) 44%,rgba(168,94,20,1) 100%);
box-shadow: 0px 0px 10px rgba(0,0,0,.6);
font-family: 'Duru Sans', sans-serif;
content: "SUN ME";
}

.waterbutton {
position:relative;
margin:10px auto;
color: white;
text-align: center;
text-shadow: 0 1px 0 rgba(0,0,0,.5);
font-size: .9em;
cursor: pointer;
}
.waterbutton:after {
top: 0px;
left: 275px;
position: absolute;
display: block;
padding: 5px 0;
width: 125px;
border: 1px solid #63072D;
border-radius: 4px;
background: linear-gradient(to bottom,rgba(212,20,90,1) 0%,rgba(181,21,86,1) 44%,rgba(140,16,66,1) 100%);
box-shadow: 0px 0px 10px rgba(0,0,0,.6);
font-family: 'Duru Sans', sans-serif;
content: "WATER ME";
}

.foodbutton {
position:relative;
margin:10px auto;
color: white;
text-align: center;
text-shadow: 0 1px 0 rgba(0,0,0,.5);
font-size: .9em;
cursor: pointer;
}
.foodbutton:after {
top: 0px;
left: 50px;
position: absolute;
display: block;
padding: 5px 0;
width: 125px;
border: 1px solid #321559;
border-radius: 4px;
background: linear-gradient(to bottom,rgba(131,94,170,1) 0%,rgba(100,76,132,1) 44%,rgba(69,48,96,1) 100%);
box-shadow: 0px 0px 10px rgba(0,0,0,.6);
font-family: 'Duru Sans', sans-serif;
content: "FEED ME";
}

JSFIDDLE: http://jsfiddle.net/22Skk/

Answer №1

The reason for the issue is that $(this) in setTimeout is referring to the window object instead of your button. To fix this, update your JavaScript as follows:

var bannerImg = $( '.bannerimg' );
$( '#sunbutton' ).click( function() {
  bannerImg.addClass( 'suncheck' );
  setTimeout( function() { bannerImg.removeClass( 'suncheck' ); }
    , 1000 );
} );

$( '#waterbutton' ).click( function() {
  bannerImg.addClass( 'watercheck' );
  setTimeout( function() { bannerImg.removeClass( 'watercheck' ); }
    , 2000 );
} );

$( '#foodbutton' ).click( function() {
  bannerImg.addClass( 'foodcheck' );
  setTimeout( function() { bannerImg.removeClass( 'foodcheck' ); }
    , 1000 );
} );

I have tested this on my local machine and it worked perfectly. You can also check out the working demo on jsFiddle: http://jsfiddle.net/D7rD6/

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Ensuring full height on Bootstrap 4 columns without triggering a scrollbar in the browser

I'm currently working with Bootstrap 4 and attempting to make 3 columns on the page fill 100% height, only displaying scrollbars within the columns and not on the entire page. I have experimented with applying h-100 to the row div, as well as implemen ...

Transferring token values between collections in POSTMAN - AUTOMATION | NEWMAN: A step-by-step guide

My goal is to streamline my unit test cases by utilizing the POSTMAN Collections API & NEWMAN. I successfully created two test cases that are performing as expected. Upon exporting the collection from POSTMAN, I proceed to generate the test report using NE ...

Display a sneak peek on a separate tab

I have an editor on my website where users can input and edit their own HTML code. Instead of saving this to a database, I want to display the current user's HTML code in a new window using JavaScript. How can I achieve this without storing the code p ...

The attempt to run 'setProperty' on 'CSSStyleDeclaration' was unsuccessful as these styles are precalculated, rendering the 'opacity' property unchangeable

I am attempting to change the value of a property in my pseudo element CSS class using a JavaScript file. Unfortunately, I keep encountering the error mentioned in the title. Is there any other method that can be used to achieve this? CSS Code: .list { ...

When using Rspec and Capybara, utilizing jQuery to set focus on an element may not apply the `:focus` CSS as expected

I have implemented jump links for blind and keyboard users on my website, but I've hidden them off-screen visually. When these links gain focus, they are moved into the viewport. Trying to test this behavior using RSpec and Capybara has been unsucces ...

PHP: Locate a class within an HTML element using a regular expression

I have a question about customizing my HTML ul menu with submenus. Specifically, I am looking to dynamically add a "first-item" class to the first item within the submenu using PHP. <ul id="menu-main" class="menu"> <li id="menu-item-68" class=" ...

Ways to Conceal <div> Tag

I need help with a prank .html page I'm creating for a friend. The idea is that when the user clicks a button, a surprise phrase pops up. I have managed to hide and unhide the phrase successfully using JavaScript. However, my issue is that when the pa ...

Infinite rendering caused by React custom hook

I developed a custom hook that retrieves data from a News API and provides handling for loading, errors, and data (similar to Apollo Client). The issue I'm facing is that the hook seems to trigger infinitely, even when the items in the dependency arra ...

Is there a way to alter a class using ng-class only when the form is deemed valid?

I am trying to implement a feature where an input field shows as required, but once the user enters text, it indicates that the input is valid by changing the border color from red to green. I am facing an issue with this line of code always returning fal ...

The instance cannot be accessed by ES6 class methods

Having trouble accessing the this instance in one of my methods within a class that I created. In my router, I am calling the method like this: import Emails from '../controllers/emails' import router from 'express' .... route.post(&a ...

Exploring the possibility of detecting page scrolling in Javascript by clicking on scroll bars

I have implemented a unique feature on my page that allows users to scroll up and down using custom buttons I created. This functionality is achieved by smoothly transitioning between anchor points on the page using jQuery's animate function. However ...

I can't find my unit test in the Test Explorer

I'm currently working on configuring a unit test in Typescript using tsUnit. To ensure that everything is set up correctly, I've created a simple test. However, whenever I try to run all tests in Test Explorer, no results are displayed! It appear ...

What is the rationale behind positioning the closing right angle-bracket of an HTML tag next to the opening left angle-bracket of a different HTML tag?

I came across a clever trick using this coding structure where the ending tag 'angle bracket' is placed at the beginning of a new left 'angle-bracket' tag opening. Unfortunately, I can't recall why it was done or where I saw it. I ...

You are unable to declare a variable within an AJAX function using jQuery

Struggling to update variables within the AJAX function? For example, if there is a variable declared outside like var myName = "My name is Kenny"; and inside the AJAX function you attempt myName.replace("Kenny", "Earl"); Upon running console.log(myNa ...

Leverage Typescript to convert string literal types to uppercase

type x = 'first' | 'second' I am looking to create a type y that is similar to this: type y = 'FIRST' | 'SECOND' Here is what I attempted: type x = 'first' | 'second' type y = {[key in x]: key[& ...

Retrieve the quantity of files in a specific directory by implementing AJAX within a chrome extension

I need assistance with obtaining the count of images in a specific directory using JS and AJAX within my chrome extension. My current code is included below, but it does not seem to be functioning as expected since the alert is not displaying. main.js .. ...

Traversing a hierarchical JSON structure reminiscent of a tree object

I am working with a complex object structure, var cObj = { name: 'Object1', oNumbers: 3, leaf: [ { name: 'Inner Object 1', oNumbers: 4, leaf: [] }, { name: 'Inner Object 2', oN ...

Emphasize table cells dynamically

Query How can I dynamically highlight a selected td? Codepen Example View Pen here Code Snippet The map consists of a randomly generated 2D array, like this: map = [[1,1,1,1,0], [1,0,0,0,0], [1,0,1,1,1], [1,0,0,0,1], [1,1, ...

Enhance a collection by incorporating methods to the result of an angular resource query

After executing a query, I am left with an array from the resource: .factory('Books', function($resource){ var Books = $resource('/authors/:authorId/books'); return Books; }) I was wondering if there is a way to incorporate pr ...

css effect of background image transitioning on mouse hover

Is there a way to have an element on my webpage with a background image that follows the movement of the mouse when hovered over? I want it to be similar to this website: This is the HTML code I currently have: <section id="home" data-speed="3" data-t ...