Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to prevent click event in jQuery?

My html code is as follows:

<h4 class="milestonehead" style="cursor: pointer;" onclick="editFun('35');">
     Some Header
     <img src="/images/delete.gif" style="float: right;" onclick="deletefun('35');">
</h4>

There are two functions in <h4> if user click on header i.e <h4> then I need to open a popup with edit form. If user click on delete image/icon then I need to execute a delete function.

Both functions editFun and deletefun execute ajax calls. In my case if the user clicks on delete icon then first it calls editFun function and then it is calling deleteFun. How can I call the appropriate function for the event.

like image 990
Swap L Avatar asked Jan 30 '14 13:01

Swap L


People also ask

How do I disable click event?

To disable the click event in HTML, the “pointer-events” property of CSS is used. For this purpose, add an HTML element and set the value of the pointer-events property as “none” to disable its click event. This article explained how to disable the click event using CSS along with its example.

What is event preventDefault () in jQuery?

The event. preventDefault() method stops the default action of an element from happening. For example: Prevent a submit button from submitting a form. Prevent a link from following the URL.

What is event preventDefault ()?

The preventDefault() method cancels the event if it is cancelable, meaning that the default action that belongs to the event will not occur. For example, this can be useful when: Clicking on a "Submit" button, prevent it from submitting a form. Clicking on a link, prevent the link from following the URL.

What is the difference between stopPropagation and preventDefault?

stopPropagation prevents further propagation of the current event in the capturing and bubbling phases. preventDefault prevents the default action the browser makes on that event.


1 Answers

If you're using jQuery, get rid of the inline JS and CSS and move them into their own files:

CSS:

.milestonehead { cursor: pointer; }
.image { float: right; }

HTML

<h4 class="milestonehead" data-id="35">
  Some Header
  <img class="image" src="/images/delete.gif">
</h4>

JS

$(document).on('click', '.milestonehead', function () {
  var id = $(this).data('id');
  editFun(id);
});

In this case you can just use the data id on the parent node. Data attributes are by far the best way to store data on your HTML elements.

$(document).on('click', '.image', function (e) {
  e.stopPropagation();
  var id = $(this).parent().data('id');
  deleteFun(id);
});
like image 123
Andy Avatar answered Oct 07 '22 00:10

Andy