byCoder
byCoder

Reputation: 9184

jQuery: catch click inside a link

I have such html:

  <a href="http://google.com" class="extended-link">
    <span class="extended-span" data-comment-href="http://example.com">text</span>
  </a>

and css:

.extended-link {
  display: inline-block;
  background: green;
  width: 200px;
  height: 500px;
  text-align: center;
}

.extended-span {
  display: inline-block;
  background: yellow;
  margin: 100px 0 0 0;
}

and js:

$('.extended-span').click(function(event) {
  event.stopPropagation();
  window.location.href = $(this).attr('data-comment-href');
});

but I can't catch .extended-span click, it always fire outer link redirection.

is it posible to catch click inside a link (link must be clickable, except span)

Plunker

Upvotes: 0

Views: 121

Answers (3)

Vishal Panchal
Vishal Panchal

Reputation: 90

Find the following code correction:

$(document).ready(function (){

$('.extended-span').click(function(event) {

window.location.href = $(this).attr('data-comment-href');

return false; });

});

Upvotes: 0

Zakaria Acharki
Zakaria Acharki

Reputation: 67505

event.stopPropagation() : Prevents the event from bubbling up the DOM tree, preventing any parent handlers from being notified of the event.

event.preventDefault() : If this method is called, the default action of the event will not be triggered.

In your case you have to use the second one event.preventDefault() because you want to prevent the default action and fire another customized action.

$('.extended-span').click(function(event) {
  event.preventDefault();
  window.location.href = $(this).attr('data-comment-href');
});
.extended-link {
  display: inline-block;
  background: green;
  width: 200px;
  height: 500px;
  text-align: center;
}

.extended-span {
  display: inline-block;
  background: yellow;
  margin: 100px 0 0 0;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a href="http://google.com" class="extended-link">
    <span class="extended-span" data-comment-href="http://example.com">text</span>
</a>

Hope this helps.

Upvotes: 1

stackoverfloweth
stackoverfloweth

Reputation: 6917

try event.preventDefault(); instead of event.stopPropagation();

Upvotes: 2

Related Questions