Dynamic counter with Javascript or Ajax functionality

Is there a way to create a counter using JavaScript or Ajax that preserves its count even when the page is refreshed?

<script type="text/javascript">

var totalCount = parseInt(localStorage.getItem('counter')) || 0;
document.getElementById("p2").innerHTML = totalCount;

function countClicks() {
totalCount++;
localStorage.setItem('counter', totalCount);
document.getElementById("p2").innerHTML = totalCount;
}


</script>
</head>
<body>
<p>
<a href="javascript:countClicks();">Count Clicks</a>
</p>
<p id="p2">0</p>

Answer №1

One way to store data on the client side is by using localStorage:

<script type="text/javascript>
  localStorage.clickCount = localStorage.clickCount || 0;
  function incrementClicks() {
    localStorage.clickCount++;
    document.getElementById("click-counter").innerHTML = localStorage.clickCount;
  }
</script>

Upon a browser's first visit to the page, the localStorage.clickCount variable will be set to 0. Subsequent clicks will increase this count and keep it saved in the browser.

If you need a counter that is shared among all users viewing the page, server-side persistence would be required. The backend system must handle retrieving and updating the click count value.

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

jQuery returns varying values for checked status when using click() method versus manual click

I'm facing an issue with a checkbox generating dynamic content. Whenever I try to pre-create the dynamic content on page load by using click(), the "checked" attribute is not set until after the click function finishes. Strangely, when I manually cli ...

Sending forms through the .NET platform

On my .NET page, I have implemented client-side validation for a submit button within the form element. var register = $('#<%= Register.ClientId %>'); register.click(function(){ validation.init(); return false; }); Disabling the f ...

How to Retrieve Checkbox Values from Multiple Rows Using JavaScript

I have a variety of module rows that allow users to manage access rights by selecting specific options. My goal now is to extract the checked boxes from these checkboxes with the name "config{{$field->id}}". Below is the current functioning code. HTM ...

Is it possible for setTimeout to not increment the counter in node.js?

Even though the loop is executed multiple times in the Node.js program below, why does the control not exit the loop? I made sure to increment the value of i within setTimeout instead of forgetting to do i++ in the for loop. function abc () { for(var ...

Receive various JSON replies from PHP

I am currently developing an app using PhoneGap which involves a script to read a ticket code. The script performs two queries: one to update the ticket status in the database if it exists, and another to write a log in a separate table. This functionality ...

The slider components have an endless loop feature that only runs once before coming to a

I'm working on creating an infinite slider that loops continuously without the need for navigation buttons. Instead, I plan to allow users to control the slider using touch gestures (although this functionality is not yet implemented in the code snipp ...

Instead of presenting MySQL data in tables on an HTML page, showcase it in editable text boxes

I have successfully imported data from my database table into an HTML table, but now I want to display them in locked text boxes. When the user clicks an "edit" button, the corresponding text box should become unlocked so that they can edit the data and sa ...

Guide to defining a conditional statement in a Nuxt.js application

I am working on displaying data from the Wordpress API in a Nuxt.js project. I am trying to organize the data by category, for example where ('post.category ', '=', 'categoryName '). Can anyone help me with the syntax in Vue.j ...

Issue encountered while constructing my application (utilizing the "yarn run build" command and in Vercel)

Encountered an error during the build process, whether on the server or locally. This issue arises when using package managers like yarn, npm, and others. The error specifically points to a problem in the CSS file, but it only occurs in the production bu ...

What is the quickest way to change an HTML element as soon as it finishes loading?

Is there a way to modify an element as soon as it is created, without relying on the $(document).ready() function which can be inefficient when a page fails to load completely or loads slowly? Some delay is acceptable, but not if it takes multiple seconds ...

What are some ways to disguise websockets?

I'm currently working on writing a JavaScript client that sends websockets to a node.js/ws server. I've been doing a lot of research and have come across information indicating it's useful, or even required by RFC, to mask all data sent from ...

Utilize jQuery in phantom.js to send an ajax request across domains

I am currently in the process of testing a chrome plugin by emulating a portion of its functionality on phantomjs. My objective for phantom seems quite straightforward, yet I am encountering issues. I aim for it to navigate to a specific webpage and withi ...

Sorting arrays can yield varying results depending on the browser being used

The variations in output between Chrome 70.0, Chrome 69.0, and Firefox 63.0 for the same code are puzzling. var arr = [1,2,43,1233,5546,33,6,11]; arr.sort(() => -1); //[11, 6, 33, 5546, 1233, 43, 2, 1] arr.sort(() => 1); //[1, 2, 43, 1233, 5546, 33, ...

const React with several parameters

What is the recommended practice for parsing 2 parameters to a const in React? I am looking to use username and message instead of data. socket.on('updateChat', function (username, message) { addMessage(username, message); } const addMessag ...

Understanding the intricacies of JavaScript function calls often results in unexpected null returns

I currently have a code that is able to run and collect data using an AJAX library. My goal is to allow users to add their own functions to the library and execute them, similar to $.get. It may be a bit difficult to fully explain what I am trying to achie ...

What is the process of converting the timing from my stopwatch to a standard time format?

I am currently working on a stopwatch project where I log the time into an array. However, when I try to use Math.min(array) or Math.max(array), it returns NaN (not a number). The time format for the stopwatch is like 00:00:15.91 which is not recognized as ...

"Using Ajax in Django results in the retrieval of the entire HTML page

In attempting to create a basic form using the bootstrap modal, I am encountering an issue where upon form submission, the response received is the entire HTML page. The request method being used is POST. Despite trying various solutions found on StackOver ...

What HTTP header is typically used in requests made by JavaScript libraries?

When utilizing the Prototype JavaScript framework, I noticed that Ajax requests include a header known as X-Requested-With. Are other JavaScript libraries such as jQuery, dojo, and YUI also including headers in their Ajax requests? Is this header always n ...

Is it safe to utilize an AngularJS filter for parsing a URL?

When working on a web application, my client-side (angularjs based) receives JSON data from a web service. The JSON can contain a text field with some URLs, such as: blah blah ... http://www.example.com blah blah blah ... To render these links as HTML, I ...

What could be causing the child of an ES6 imported object to return as undefined?

Here is the code snippet I am working with: import * as _routes from '../../routes' console.log('parent:', _routes) console.log('child:', _routes.breadcrumb) This code produces the following output: https://i.stack.imgur.co ...