Reputation: 533
I have this piece of jquery:
$('#team-members .team-thumb').on('click', function(e){
e.preventDefault();
var member = $(this).data('member');
$('#team-members .team-profiles').slideToggle();
teamSlider.reloadSlider({
startSlide: member,
pager: false,
adaptiveHeight: true
});
$('html,body').animate({
scrollTop: $("#team-profiles").offset().top},
'fast');
$('.bx-viewport').prepend('<div id="slide-me"></div>');
});
How do i make it only prepend this event once so on the second click it dosn't add it to the DOM:
$('.bx-viewport').prepend('<div id="slide-me"></div>');
Upvotes: 2
Views: 235
Reputation: 73896
You can do this inside the click event:
var $viewport = $('.bx-viewport');
if($viewport.find('#slide-me').length === 0)
$viewport.prepend('<div id="slide-me"></div>');
bx-viewport
element first.slide-me
is not inserted in the beginning of bx-viewport
element yet, then prepend the element, else do nothing.Upvotes: 2
Reputation: 47956
Use jQuery's one()
command:
$('#team-members .team-thumb').one('click', function(e){ ... }
Description: Attach a handler to an event for the elements. The handler is executed at most once per element per event type.
Other than this built in command, you could always use a boolean flag:
var event_handler_enabled = true;
$('#team-members .team-thumb').one('click', function(e){
if ( event_handler_enabled ){
// code for handling click goes here
event_handler_enabled = false; // ensure this code will not be executed again
}
}
I'd recommend the first option. There's no reason to re-invent the wheel. If jQuery has a built in method for executing a handler only once - use it! :)
Upvotes: 4