I need my script to do something the first time the element clicks and continues to do something else when clicking 2,3,4, etc.
$('selector').click(function() { //I would realy like this variable to be updated var click = 0; if (click === 0) { do this var click = 1; } else { do this } });//end click
Actually, I think it should rely on variables, but I can't figure out how to update the variable here, any help would be awesome.
Take a look at the jQuery method .data(). Consider your example:
.data()
$('selector').click(function() { var $this = $(this), clickNum = $this.data('clickNum'); if (!clickNum) clickNum = 1; alert(clickNum); $this.data('clickNum', ++clickNum); });
See a working example here: http://jsfiddle.net/uaaft/
Use data to save your state with an element.
$().data( 'NUMBER_OF_CLICKS')
$().data( 'NUMBER_OF_CLICKS', some_value)
.
: $(this).data('number_of_clicks') false,
:
, one $(document).ready() ( , ), , , bind click.
one
$(document).ready()
bind
click
function FirstTime(element) { // do stuff the first time round here $(element.target).click(AllOtherTimes); } function AllOtherTimes(element) { // do stuff all subsequent times here } $(function() { $('selector').one('click', FirstTime); });
, :
$('selector'). toggle (function() {...}, function() {...}, function() {...},...);
$('# foo'). one ('click', function() { alert (' .'); });
click Html .
, , :
$( "# Foo" ). Bind ('click', () {
//
$( "# Foo" ) ("click"). // .
});
vanilla Js. ,
const onNextTimes = function(e) { // Do this after all but first click }; node.addEventListener("click", function onFirstTime(e) { node.addEventListener("click", onNextTimes); }, {once : true});
, CanIUse