Creating a Click Counter with jQuery 2.0.1/2.0.2: A Step-by-Step Guide

Currently in the process of creating a fundraising webpage for charity, I have chosen to display an animated rabbit making its way Around The World.

My progress so far includes a non-looping gif that plays on click, with a limitation on how often it can be clicked. You can view the webpage here.

This is a preliminary version of what the final result will resemble. However, I am looking to incorporate a click counter into the image, so that every time the rabbit jumps, the count increments by one. Eventually, this count will become universal (but that's a task for another day). See this link for the JSFiddle containing the codes I've implemented thus far (excluding some minor adjustments). How can I integrate a click counter into this script? Feel free to utilize the JSFiddle link and explore the page!

Below is the complete script for the current state of the page:

<html>
<head>
<title>Around The World</title>

<script src="http://code.jquery.com/jquery-2.0.0.js"></script>

<style type="text/css">
    body {margin:0; }
</style>

<script>
$(function(){
    var image = new Image();
    image.in_action = false;  // flag to determine current state. Initialize to ready to     animate.
    image.duration = 750;  // This is rough, if you are creating the gif you can peg this     to the proper duration
    image.src ='transparent.gif';
    $('#img').click(function(){
        if (!image.in_action) {
           image.in_action = true;  // Set the image as in progress
           $(this).attr('src',image.src);
            window.setTimeout(function() {
                image.in_action = false;  // After image.duration amount of miliseconds,     set as finished
            }, image.duration);
        }
    });
});
</script>


<style>
img {
    position: relative;
    top: 100px;
    width:150px;
    height:206px;
}
</style>

</head>
<body bgcolor="00FFFF">

<center>
<img id = "img"

src = "still.png">
<center>

</body>
</html>

Appreciate all the help in advance!

Answer №1

It seems like using a simple global variable might solve the issue:

...
<script>

var count = 0;

$(function(){
    var picture = new Image();
...
   if (!picture.isActive) {
       count++;               // Increment count by 1
       $('#click-count').text('Total clicks: '+count); // display somewhere
       picture.isActive = true;  // Mark the picture as active
...

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

Is it possible to use HTML code as content in CSS?

How do I go about displaying the variable $text as HTML? Take a look at the code snippet provided below: <?php header('Content-type: text/css'); $background = "#ffafff"; $color = "#000000"; $green = "#16a86f"; $text= '<h1&g ...

Vue is struggling to load the component files

Lately, I've been encountering an error during webpack build that is causing some issues. ERROR There were 3 errors encountered while compiling The following relative modules could not be found: * ./components/component1.vue in ./resources/assets/ ...

Things, their examples and the impact of setTimeOut

I'm currently delving into object oriented programming in JavaScript. function doStock() { //my class var that = this; var nAntiFreeze = null; // timeout ID var getContent = function(oInPageContainer) { GM_log('Antifreeze, before clea ...

Automation of transmitting HTML data to a database

After dabbling in web development for some time, I've come to realize that transferring data between an HTML form and a database can be quite challenging. My usual solution involves using an AJAX call to a PHP script, as illustrated in the image below ...

I'm facing an issue with my 'root' div on ReactJS - it doesn't stretch all the way to the top. Any suggestions on how I can make it expand properly

While I realize this issue has been discussed extensively, none of the suggested solutions have worked for me. As a final attempt to resolve it, I am turning to you all here. The point at which my root div stops is puzzling: I've explicitly defined ...

An 'Syntax Error' message appears in Internet Explorer when JSONP does not receive a response

Our current application needs to retrieve information from another application, and this second application does not have to be active to respond to the JSONP request. In this case, the requester will receive an alert message informing them of this. funct ...

Alter the default time zone in JavaScript

PHP features a function known as date_default_timezone_set which impacts the GMT time that is used by the Date() command. Is there a way for this function to also impact JavaScript? Here is a custom function I have: function calcTime(offset) { d = n ...

Attempting to grasp the fundamentals of angular Routing, however, upon attempting to reload the page, nothing appears to be displayed

While working in the Bracket editor, I created a file structure with various files located under the 'scripts' tags within the Index.html file. The root folder is named 'projectAngular', inside which there are subfolders like 'appC ...

Jumping occurs in Slick Carousel when adjusting the width of the active slide

Check out the fiddle link here: http://jsfiddle.net/br24p3Lr/ I've been attempting to perfect the animation when transitioning to a new active slide. Despite trying various approaches to resolve this issue, I seem to be stuck at the moment. The foll ...

Resetting the index and length in Vue.js each time a new page is loaded

Currently facing an unusual issue that I'm struggling to resolve. My goal was to include an index number in a for-each loop and calculate the total count of data within my vue.js component. While I successfully achieved this, I encountered a problem w ...

Learn how to extract substrings from a variable within an API using Vue.js

Exploring VueJs for the first time and looking to split a string by comma (,) retrieved from an API into separate variables. The data is coming from a JSON server. "featured-property": [ { "id": "1", " ...

Could you break down the concept of the for/in loop for me?

/* Follow the instructions provided to implement each function. The parameters of a function that reference `cart` pertain to an object structured like this: { "Gold Round Sunglasses": { quantity: 1, priceInCents: 1000 }, "P ...

Hide elements forever once the form is submitted

I'm seeking help to figure out how to make certain elements disappear after a form submission on my website's dashboard page. Specifically, I need to hide three elements once the user has submitted a form. Elements that need to be hidden: .vc_t ...

Issue with binding background images to DIV elements in Angular 4 CSS

Here is a template example: <div [style.background-image]="profileImage" ></div> In the TypeScript file: We declare private profileImage: any; and use DomSanitizer for security. Fetching photo from service: We set this.profileImage using b ...

Insert data into a drop-down menu and organize it

When I choose a value in one Select, the other options are removed and the previous value is added to them. How can I use JQuery to add the previous value to Select and then sort it alphabetically? ...

Tips for using a unique format for a single field in jqGrid

My JQGRID site has table configuration set up like this: configid config rule 1. Application_name 'MyApps' 2. Max number 1,000,00 3. Application End 12/31/2012 Some cells are for numbers and others for dates. If a user wants to edit a date ce ...

Learn the steps to invoke a JavaScript function from a <td> element within an ng-repeat loop

How can I call an Angular function inside ng-repeat td and replace the value from the function with the value in the td element? The code snippet provided below is not functioning as expected. Instead of getting the date, the same getCSTDateTime function i ...

Unable to apply box-shadow styling to input elements

Why am I having trouble adding box shadows to input elements in my CSS? I've tried something like this http://jsfiddle.net/DLCTh/, and while it applies correctly to div elements, it doesn't seem to work on text inputs. Am I overlooking something ...

Guide on connecting MySQL 'id' to an HTML element

I need assistance with setting up a functionality on my website. I have a database containing rows of data, and each row has an 'ID' field in MySQL. I want to connect each ID to a button so that when the button is clicked, a PHP script will run t ...

Implementing JavaScript for showcasing weights

I've encountered a JavaScript function that modifies user preferences for weight units, allowing them to choose between metric and imperial measurements. When displaying weights on my page, I typically present them as follows: This is a brief explan ...