javascript - How to make sure that click functions are only performed once -
when user clicks on either .class or #id, changes made css of both divs , value of #id increases 1. however, when user clicks on either 1 of divs, changes should made once - if user clicks again, nothing happen unless page refreshed.
$('.class, #id').one('click', function(e) { $('.class, #id').css({ 'background-color' : 'rgb(232,69,73)', 'color' : '#fff', }); $("#id").html(function(i, val) { return val*1+1 }); }); above shows code using. can see, have used .one make sure code performed once. works, problem user can click on .class , click on #div means code can performed twice.
how edit code can performed once - clicking on 1 div means other div can not clicked on.
you can set data attribute on both objects , increment counter if not set:
$('.class, #id').one('click', function(e) { if (!$(this).data("valueset")) { $('.class, #id').css({ 'background-color' : 'rgb(232,69,73)', 'color' : '#fff' }).data("valueset", true); $("#id").html(function(i, val) { return val*1+1 }); } }); or, if know there no other jquery click handlers want retain, you can unbind jquery click handlers both objects:
$('.class, #id').one('click', function(e) { $('.class, #id').off("click").css({ 'background-color' : 'rgb(232,69,73)', 'color' : '#fff' }) $("#id").html(function(i, val) { return val*1+1 }); }); or, can unbind specific event handler putting event handler in named function:
function oneclick(e) { $('.class, #id').off("click", oneclick).css({ 'background-color' : 'rgb(232,69,73)', 'color' : '#fff' }) $("#id").html(function(i, val) { return val*1+1 }); } $('.class, #id').one('click', oneclick); a little more generic scheme create custom function ever perform action once:
function oneaction(fn) { var calledyet = false; return function() { if (!calledyet) { calledyet = true; return fn.apply(this, arguments); } } } then, can use this:
$('.class, #id').one('click', oneaction(function(e) { // ever executed once $('.class, #id').css({ 'background-color' : 'rgb(232,69,73)', 'color' : '#fff' }) $("#id").html(function(i, val) { return val*1+1 }); }));
Comments
Post a Comment