Ash
Ash

Reputation: 444

removing a placed jquery click event listener after initial click

Got some simple functionality set up on a page. Initially I want to replace default action of a hyperlink click with some functionality which will display an overlay.

After the overlay is displayed I want to remove the event listener I have placed on the hyperlink so it reverts to what it was previously (i believe there is another event listener on here, I dont want to remove this one while removing mine). Within the overlay is another button which when clicked, should trigger the initial functionality of the button.

Ive tried the .off() jquery method, however this seems to prevent the ".mmclose" button from working.

Not quite sure where i am going wrong with this..

// placing event listener on initial link
$("#utility_0_HyperLinkLogout").click(function() {
  // removing event listener(?)
  $("#utility_0_HyperLinkLogout").off("click");
  // preventing default button behavior
  event.preventDefault();
  //overlay replacing original content
  I62originalContent.hide();
  $("#mmi62wrapper").fadeIn("slow", function() {
    // new event listener placed on button within overlay (as callback)        
    $(".mmclose").click(function() {
      //new button should now trigger original buttons original functionality?
      $("#utility_0_HyperLinkLogout").trigger("click");
    })
  })
});

Upvotes: 0

Views: 43

Answers (1)

Yeldar Kurmangaliyev
Yeldar Kurmangaliyev

Reputation: 34189

You can use jQuery .one method to attach a handler which will be executed only once. You don't need to worry about removing this handler anymore.

Check this example:

$(".myClass").click(function() {
  this.innerText += "!";
});

$("#myId").one('click', function() {
  this.innerText += "?";
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button class="myClass" id="myId">Click me twice</button>

In this example, clicking the button keeps adding "!", while "?" is only added once. Other handlers are not affected.

Upvotes: 1

Related Questions