jQuery preventDefault() doesn't work with .on()


Mr Gandy

Yes, I've read many other articles with the same problem, but I don't understand how to fix this. I have created a bookmark button that needs to change the icon when clicked.

my jQuery:

jQuery(document).ready( function() {
    
    var bm = jQuery(".user_bookmark");
    
    bm.on("click", ".user_bookmark", function (e) {
        e.preventDefault(); 
        post_id = jQuery(this).attr("data-post_id")
        nonce = jQuery(this).attr("data-nonce")

        jQuery.ajax({
         type : "post",
         dataType : "json",
         url : bookmarkAjax.ajaxurl,
         data : {action: "eri_user_bookmark", post_id : post_id, nonce: nonce},
         success: function(response) {
            if(response.type == "success") {
                var add = 'Add Bookmark';
                var remove = 'Remove Bookmark';
                var display = bm.attr('display');
                var bookmarked = bm.attr('bookmarked');
                if (display == 'icon') {
                    add = '<i class="x-icon" data-x-icon-o="&#xf02e;" aria-hidden="true"></i>';
                    remove = '<i class="x-icon" data-x-icon-s="&#xf02e;" aria-hidden="true"></i>';
                }
                if (bookmarked) {
                    bm.html(remove);
                    bm.attr('bookmarked', 'false');
                } else {
                    bm.html(add);
                    bm.attr('bookmarked', 'true');
                }
            }
            else {
               alert("Your bookmark could not be added")
            }
         }
        })  
    });

})

First, I had it bm.click(), but it only took one click to use, then read to switch to the .on()feature, now refreshing the page.

I tried switching out function (e)with function ()and replacing e.preventDefault();with return false;, e.stopImmediatePropagation();and e.stopPropagation();.

Also tried switch bm.on()with jQuery(document).on()all these changes. That still runs my code and doesn't refresh, but doesn't change the element in the jQuery code.

HTML example:

<a class="user_bookmark" data-nonce="2b92b05de9" data-post_id="1" href="https://example.com/wp-admin/admin-ajax.php?action=eri_user_bookmark&amp;post_id=1&amp;nonce=2b92b05de9" display="icon" bookmarked="true" style="outline: none;">
   <i class="x-icon" data-x-icon-s="" aria-hidden="true"></i>
</a>

Complete PHP Gist : https://gist.github.com/mrgandy/91361fca86e769235eec684a4647b875

Rory McCrossan

The problem is because you accidentally nested event handlers. You will attach a delegated event handler to .user_bookmarklisten for click events on child .user_bookmark elements . Your HTML shows that these elements are not nested, so the event handler never fires, so no preventDefault()call or AJAX request.

Assuming the element <a />you're targeting is not dynamically created, then remove the second parameter you used in the on()call .

jQuery($ => {
  var $bm = $('.user_bookmark');

  $bm.on('click', function(e) {
    e.preventDefault();
    let post_id = $(this).data('post_id');
    let nonce = $(this).data('nonce');

    console.log(post_id, nonce);
    console.log('ajax request here...');
  });
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<a class="user_bookmark" data-nonce="2b92b05de9" data-post_id="1" href="https://example.com/wp-admin/admin-ajax.php?action=eri_user_bookmark&amp;post_id=1&amp;nonce=2b92b05de9" display="icon" bookmarked="true" style="outline: none;">
  <i class="x-icon" data-x-icon-s="" aria-hidden="true"></i>
  Lorem ipsum
</a>

If you were actually adding elements dynamically to the DOM after the page loaded, you would need to assign the delegated event handlers to a static parent, which would look like this:

jQuery($ => {
  $(document).on('click', '.user_bookmark', function(e) {
    e.preventDefault();
    let post_id = $(this).data("post_id");
    let nonce = $(this).data("nonce");

    console.log(post_id, nonce);
    console.log('ajax request here...');
  });
})

Related


jQuery preventDefault() doesn't work with .on()

Mr Gandy Yes, I've read many other articles with the same problem, but I don't understand how to fix this. I have created a bookmark button that needs to change the icon when clicked. my jQuery: jQuery(document).ready( function() { var bm = jQuery(".u

jQuery preventDefault() doesn't work with .on()

Mr Gandy Yes, I've read many other articles with the same problem, but I don't understand how to fix this. I have created a bookmark button that needs to change the icon when clicked. my jQuery: jQuery(document).ready( function() { var bm = jQuery(".u

jQuery preventDefault() doesn't work with .on()

Mr Gandy Yes, I've read many other articles with the same problem, but I don't understand how to fix this. I have created a bookmark button that needs to change the icon when clicked. my jQuery: jQuery(document).ready( function() { var bm = jQuery(".u

jQuery preventDefault() doesn't work with .on()

Mr Gandy Yes, I've read many other articles with the same problem, but I don't understand how to fix this. I have created a bookmark button that needs to change the icon when clicked. my jQuery: jQuery(document).ready( function() { var bm = jQuery(".u

jQuery preventDefault doesn't always work

myhappycoding I have a function called showBasket that shows you a list of items added to shoppingBasket. This happens whenever the user clicks the link. Every time you click outside the menu, it hides again. My problem is that in this menu I have a list of li

jQuery preventDefault() doesn't work in AJAX call

coronavirus disease So when the user enters an email, I'm checking if that email exists. $('form.recover-form#check-form').on('submit', function(e){ var form = $(this), input = $('.check-recover-email'), span = $('.recover-error')

jQuery preventDefault doesn't always work

myhappycoding I have a function called showBasket that shows you a list of items added to shoppingBasket. This happens whenever the user clicks the link. Every time you click outside the menu, it hides again. My problem is that in this menu I have a list of li

jQuery .click() event.preventDefault() doesn't work

Richard King: I'm building an extensible web application by putting scripts into a preset directory. The script needs to read the file header before going to the page, so I need to use .preventDefault() when I click the link and run some JScript first. Unfortu

jQuery's preventDefault doesn't work with generated forms

Signal I am trying to generate a form by clicking on a list of users and post the data using AJAX. The preventDefaultelement does not work. I want to validate the form using AJAX without reloading the page. my code: $(function(){ $("#members_list ul > li")

jQuery .click() event.preventDefault() doesn't work

Richard King: I'm building an extensible web application by putting scripts into a preset directory. The script needs to read the file header before going to the page, so I need to use .preventDefault() when I click the link and run some JScript first. Unfortu

jQuery .click() event.preventDefault() doesn't work

Richard King I'm building an extensible web application by putting scripts into a preset directory. The script needs to read the file header before going to the page, so I need to use .preventDefault() when I click the link and run some JScript first. Unfortun

jQuery event.preventDefault() doesn't work unless debugging

metal encoder I am trying to use this method in order to convert GET parameters to POST. I also want the anchors to be handled correctly even when the middle mouse button is clicked. This is how the event handler is bound: $(document).ready(function () { $

JQuery 2.1.4 preventDefault on form submit doesn't work

salipshitz I have an HTML form that I'm trying to handle with JQuery 2.1.4 by using event.preventDefault() in the .on('submit', function(event) {})method , but it just reloads even though I'm event.preventDefault()there. Here is my HTML, CSS and JS code: var g

jQuery UI tab beforeLoad preventDefault doesn't work

Judge God Somehow the e.preventDefault()on beforeLoad()event in jQuery UI Tabs is not working properly. Here is a small example: <div id="tabs"> <ul> <li><a href="#exampleExistingTab">Existing Tab</a></li> <li><a href="/path/to/remote/tab">

jQuery UI tab beforeLoad preventDefault doesn't work

Judge God The e.preventDefault()on beforeLoad()event in jQuery UI Tabs is not working properly. Here is a small example: <div id="tabs"> <ul> <li><a href="#exampleExistingTab">Existing Tab</a></li> <li><a href="/path/to/remote/tab">Remote T

jQuery preventDefault doesn't work after field validation

Jules The following code is designed to validate that the input is not Blankt and then submit the form via Ajax. After removing the validation it works fine, but in place preventDefault doesn't seem to work. $(document).on("keydown", "input[class='p']", functi

jQuery's preventDefault doesn't work with generated forms

Signal I am trying to generate a form by clicking on a list of users and post the data using AJAX. The preventDefaultelement does not work. I want to validate the form using AJAX without reloading the page. my code: $(function(){ $("#members_list ul > li")

jQuery event.PreventDefault doesn't work in user defined function

Mickey I am creating a function that will receive a URL and then display that URL in a lightbox. I'm having trouble with event.preventDefault() in a function, it says it's not a function in the error console. I've tried passing the event to the function explic

jQuery .click() event.preventDefault() doesn't work

Richard King: I'm building an extensible web application by putting scripts into a preset directory. The script needs to read the file header before going to the page, so I need to use .preventDefault() when I click the link and run some JScript first. Unfortu

jQuery preventDefault doesn't work after field validation

Jules The following code is designed to validate that the input is not Blankt and then submit the form via Ajax. After removing the validation it works fine, but in place preventDefault doesn't seem to work. $(document).on("keydown", "input[class='p']", functi

jQuery UI tab beforeLoad preventDefault doesn't work

Judge God Somehow the e.preventDefault()on beforeLoad()event in jQuery UI Tabs is not working properly. Here is a small example: <div id="tabs"> <ul> <li><a href="#exampleExistingTab">Existing Tab</a></li> <li><a href="/path/to/remote/tab">

jQuery event.PreventDefault doesn't work in user defined function

Mickey I am creating a function that will receive a URL and then display that URL in a lightbox. I'm having trouble with event.preventDefault() in a function, it says it's not a function in the error console. I've tried passing the event to the function explic

preventDefault doesn't work in Firefox

Andrew Burrow I have an input called shop_cat_edit and the code below. But in FireFox this code never works...even IE accepts it. What am I doing wrong? $('[name=shop_cat_edit]').on('click',function(e){ $('#shop_cat_selector_form').on('submit', function(){e

PreventDefault doesn't work with delegates

Mika H. I'm trying to write some JQuery so that whenever the user clicks on a link (ie, a amarker), an alert appears and the link doesn't actually jump to another place. $(document).ready(function() { $(document.body).on('click',"a",function(event){

PreventDefault doesn't work with delegates

Mika H. I'm trying to write some JQuery so that whenever the user clicks on a link (ie, a amarker), an alert appears and the link doesn't actually jump to another place. $(document).ready(function() { $(document.body).on('click',"a",function(event){

PreventDefault doesn't work with delegates

Mika H. I'm trying to write some JQuery so that whenever the user clicks on a link (ie, a amarker), an alert appears and the link doesn't actually jump to another place. $(document).ready(function() { $(document.body).on('click',"a",function(event){