Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Removing jQuery event from #id after clicking on it (or prevent a second click)

guys!

I am really doing my best to solve the problem below, but after many hours I am not able to see the correct path to go! Let me explain:

  • I have a element a-href (#opener) that, when clicked, fires a jQueryUI modal dialog who loads through ajax a URL inside a div (#target).
  • Everything works perfect, but I want this to happen once!
  • After loading the modal window I was able to set a class (.deactivated) to my #opener a-href and to remove the id (#opener) to prevent the action to be fired again, however it does not work... the a-href remains clickable and opening the modal window (#target) as many times as I click on it!
  • The only solution I found was to remove the a-href completely from the DOM --- using $(this).fadeOut(); ---, but it is really ugly, since my link #opener just vanishes in thin air.

Any ideas? Thank yo sooo much. G.

<script>
$(document).ready(function() {
    $('#opener').click (function() {

        $('#target').load ('http://my.url', function(){
            $('#target').dialog({
                title: 'My Title',
                draggable: true,
                dialogClass:'My Class',
                modal: true,
                hide: { effect: 'fade', speed: 'fast' },
                show: { effect: 'fade', speed: 'fast' },
                closeOnEscape: true,
                closeText: 'Close',
                beforeClose: function(event, ui) { 
                   'window.location.reload(true)'
                },
            });//end dialog   
        });
        $(this).addClass('.deactivated');
        $(this).removeAttr('id');
    });
});

like image 870
Cospefogo Avatar asked Mar 15 '13 12:03

Cospefogo


2 Answers

Removing the ID from the element doesn't remove any handlers bound on that element (unless you had used "event delegation").

Either bind on the click event using .one (instead of .on or the obsolete .bind) which then automatically unbinds the handler after it fires the first time:

$('#opener').one('click', ...)

Or disable the event within the click handler:

$('#opener').on('click', function() {
    ...
    $(this).off('click').addClass('.deactivated');
});

NB: it's good practise to always use the newer .on (or .one) and .off functions instead of .bind, or .click, etc. It makes event handling code more consistent and avoids confusion with how .click can be used to both register an event handler or (without parameters) trigger the event handlers.

like image 197
Alnitak Avatar answered Sep 28 '22 16:09

Alnitak


Description

.one(), Attach a handler to an event for the elements. The handler is executed at most once per element.

$('#opener').one('click',function(){
     //your code
    });
like image 42
sasi Avatar answered Sep 28 '22 16:09

sasi