I\'m making a system where a user clicks a button and their score increases. There is a counter which I would like to increase the value of using jQuery (so that the page do
Go to the below site and tryout. http://www.counter12.com/
From the above link I have selected the one design that I liked to have in my site accepted terms and it has given me a div that I have pasted in my html page.
It did awesomely worked.
I am not answering to your problem on JQuery, but giving you an alternate solution for your problem.
I'm going to try this the following way. I've placed the count variable inside the "onfocus" function so as to keep it from becoming a global variable. The idea is to create a counter for each image in a tumblr blog.
$(document).ready(function() {
$("#image1").onfocus(function() {
var count;
if (count == undefined || count == "" || count == 0) {
var count = 0;
}
count++;
$("#counter1").html("Image Views: " + count);
}
});
Then, outside the script tags and in the desired place in the body I'll add:
<div id="counter1"></div>
Several of the suggestions above use global variables. This is not a good solution for the problem. The count is specific to one element, and you can use jQuery's data function to bind an item of data to an element:
$('#counter').data('count', 0);
$('#update').click(function(){
$('#counter').html(function(){
var $this = $(this),
count = $this.data('count') + 1;
$this.data('count', count);
return count;
});
});
Note also that this uses the callback syntax of html to make the code more fluent and fast.
You are trying to set "++" on a jQuery element!
YOu could declare a js variable
var counter = 0;
and in jQuery code do:
$("#counter").html(counter++);
You cannot use ++
on something which is not a variable, this would be the closest you can get:
$('#counter').html(function(i, val) { return +val+1 });
jQuery's html() method can get and set the HTML value of an element. If passed a function it can update the HTML based upon the existing value. So in the context of your code:
$("#update").click(function() {
$('#counter').html(function(i, val) { return +val+1 });
}
DEMO: http://jsfiddle.net/marcuswhybrow/zRX2D/2/
When it comes to synchronising your counter on the page, with the counter value in your database, never trust the client! You send either an increment or decrement signal to you server side script, rather than a continuous value such as 10, or 23.
However you could send an AJAX request to the server when you change the HTML of your counter:
$("#update").click(function() {
$('#counter').html(function(i, val) {
$.ajax({
url: '/path/to/script/',
type: 'POST',
data: {increment: true},
success: function() { alert('Request has returned') }
});
return +val+1;
});
}
It's just
var counter = 0;
$("#update").click(function() {
counter++;
});