Čamo
Čamo

Reputation: 4160

How to preventDefault on dynamically created anchors

I have a list of tasks with id #tasks with delete anchors with class .deleteTask next to each list element. This elements and its delete links are created dynamically by ajax. So if I want hook some handlers to elements I use it like this:

$('#tasks').on('click', '.deleteTask', function (event)
{
    if( ! confirm('Are you sure?') ) event.preventDefault();
});

But it seems the click event on anchors with class .deleteTask is triggered before the click on parent #tasks element. So I can't call preventDefault() on it. I think it is because of bubbling. But how can I trigger preventDefault() on anchors which are dynamically created?

Here is the example https://jsfiddle.net/dyLa915b/1/

Upvotes: 0

Views: 1691

Answers (3)

Himanshu Upadhyay
Himanshu Upadhyay

Reputation: 6565

There are three things you should change.

1st: You are using same id for numbers of ids tasks on the same page which is wrong. The ID attribute should be unique in one DOM. So you should use class instead id. And then you should use that class as a selector with jQuery.

2nd: You said that these elements are dynamically created, so they are not known to the DOM because when the page was rendered 1st time they were not there on DOM. They were created after DOM got ready. In such cases you should use jQuery event delegation.

3rd: write preventDefault at very first line of your jQuery function.

So final updated code would be :

$(document).on('click', '.delete', function (event)
{
    event.preventDefault();
    if( ! confirm('Are you sure?') ) {
          // Write code if user clicks `ok` button of confirmbox.
    }
});

Upvotes: 2

Ali Soltani
Ali Soltani

Reputation: 9927

You can use delegate for do it. delegate used for dynamic elements. please see this similar post.

Upvotes: 0

JSingh
JSingh

Reputation: 375

You should put event.preventDefault() before your logic. Here's an example:-

var $links = $('.deleteTask');

$links.off('click').on('click', function($event){
  $event.preventDefault();
  $event.stopPropagation();
  
  if( ! confirm('Are you sure?') ){
  // do stuff  
  };
  
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div>
  <li>  
    <a class="deleteTask" href="www.google.com">Google</a>
  </li>
  <li>  
    <a class="deleteTask" href="www.youtube.com">Youtube</a>
  </li>
</div>

Upvotes: 0

Related Questions