Reputation: 9731
I have a function which executes on click event, but the thing is that I want it to execute only once.
The function that get's executed on click represents a google map plotting to an targeted element. The function looks like this :
Cluster.prototype.initiate_map_assembling = function(target, latitude, longitude) {
var canvas = $(target).children();
var coordinates = new google.maps.LatLng(latitude, longitude);
var options = {
zoom: 9,
center: coordinates,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map($(canvas)[0], options);
var marker = new google.maps.Marker({
position: coordinates,
map: map
});
};
And I'm running it on click
event like this :
Cluster.prototype.initiate_google_maps_action = function() {
var self = this;
return $(this.maps_wrapper_class).each(function(index, element) {
var canvas = $(element).parents().eq(3).find(self.map_canvas_wrapper_class);
return $(element).on('click', function(ev) {
var latitude = $(element).attr('data-latitude');
var longitude = $(element).attr('data-longitude');
self.initiate_map_assembling(canvas, latitude, longitude);
($(canvas).hasClass('selected')) ? $(canvas).removeClass('selected') : $(canvas).addClass('selected');
ev.preventDefault();
});
});
};
What I want to achieve is stop the plotting each time I click the button, because it's only needed once since I'm only hiding the container div and not destroying it. So how could I do that ? I tried with temporary variables added when the function executes ( and setting it as true after the first time and as false when initiated ) and returning false if the temporary variable is true, but with little success as I could not return false inside the plotting function.
Upvotes: 1
Views: 4065
Reputation: 9848
Use jQuery's .one()
.
As per OP's explanation: there's always the possibility to define more than one click event for an element.
So you can define one with .one()
and the other with on()
as you already do, putting the code to run only once in the first.
Upvotes: 2
Reputation: 60835
Two choices:
one
, the other with on
Something like:
var counter = 0;
return $(element).on('click', function() {
counter++;
if ( counter > 1 ) {
}
});
Upvotes: 1
Reputation: 100205
you could bind click only once like:
$(document).one('click', function(e) {
//do your code here
});
OR
$('#someBtn').click(function(){
if ($(this).attr('data-once')!='already_clicked' ){
//your code here
$(this).attr('data-once', 'already_clicked');
}
});
Upvotes: 2