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

guys!

I really do my best to solve the problem below, but after many hours I can not see the right way! Let me explain:

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

Any ideas? Thanks a lot oooh. 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');
    });
});

+5
source share
4 answers

Removing an identifier from an element does not remove any handlers associated with this element (unless you used "event delegation").

Either bind the click event using .one(instead of .onor deprecated .bind), which then automatically unscrews the handler after it is launched for the first time:

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

Or disable the event in the click handler:

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

NB: .on ( .one) .off .bind .click .. , .click ( ), .

+8

.one(), . .

$('#opener').one('click',function(){
     //your code
    });
+4

.one(), , , :

$('#opener').one('click', function(event) {
    // your code here
});
+2

one:

$('#opener').one("click", function() {

});

http://api.jquery.com/one/

+2

All Articles