lolol
lolol

Reputation: 4390

a element click and document click hierarchy

If I run the following code I get, as expected, 1, because the a element is inside the div element.

HTML:

<div class=".holder">
  <a href="#" class=".link">a</a>
</div>

jQuery:

$(document).click(function (e) {
  alert($(e.target).closest(".holder").length);
});

Now, the inside a element needs to repopulate the div element, including the a element itself, so:

$(".link").on("click", function (e) {
  e.preventDefault();
  $(".holder").html("some html");
});

The problem is: because the document click occurs after the a element click (makes sense, hierarchy), if I click the a element, I get 0 instead of 1, because the a element parent doesn't exist anymore, and the a element itself only exists in memory.

Is there a way to solve this without check for the a element click itself?

Upvotes: 0

Views: 737

Answers (2)

Sushanth --
Sushanth --

Reputation: 55750

You can try this approach

$(document).click(function (e) {
    if(e.target.className === 'link'){
        e.preventDefault();
        alert($(e.target).closest(".holder").length);
        $(".holder").html("some html");
    }
});

You can create a click event for the document and check what the current target is.. IF its the link then write up the code to handle what you want..

Also remove the dot . in your classnames class="link"

CHECK DEMO

Upvotes: 2

Ethan Brown
Ethan Brown

Reputation: 27292

You could defer the HTML replacement:

$(document).click(function (e) {
  alert($(e.target).closest(".holder").length);
  if( $('.holder').data('executeMe') )
    $('.holder').data('executeMe')();
});

$(".link").on("click", function (e) {
  e.preventDefault();
    $('.holder').data( 'executeMe', function() {
      $(".holder").html("some html");
    });
});

Upvotes: 1

Related Questions