Cancel Event Click Jquery preventDefault

Asked

Viewed 545 times

0

Hello, I am not able to use addClass when I give a replay on my page using ajax. What happens is that it adds the class to my html element for a moment, but the behavior is as if the page is being loaded, so nothing happens. I’m making a pagination.

$('.waves-effect a').click(function(e) {
  e.preventDefault();
  var url = $(this).data('href');

  $.ajax({
    type: "GET",
    url: url,
    success: function(response) {
      $('#form').html(response)
    },

    complete: function() {
      $(".waves-effect").click(function() {
        $(this).addClass("active");
      });
    }
  });
});
  <li class="waves-effect"><a data-href="webmail.php?page=<?=$i?>"><?=$i?></a></li>

I’m kind of a layman in Jquery, so I appreciate all your help.

  • I tested it here and it’s ok. Have you tried removing this event $(".waves-effect").click(function() {} ? Leave only the $(this).addClass("active"); in the complete?

  • I need to add the class "active", only where in the element clicked (this). I tried to remove and did not function =/

  • Try to do as Fernando posted below. The complete will only add the class activity when the request is completed.

1 answer

0

Try it like this:

<!-- NO HTML adicione o href="#" -->
<li class="waves-effect"><a href="#" data-href="webmail.php?page=<?=$i?>"><?=$i?></a></li>

<!-- NO JAVASCRIPT -->
$('.waves-effect a').click(function(e) {
  e.preventDefault();
  var element = $(this)
  var url = element.data('href');

  $.ajax({
    type: "GET",
    url: url,
    success: function(response) {
      $('#form').html(response)
    },

    complete: function() {
      $('.waves-effect a').removeClass('active')
      element.addClass("active");
    }
  });
});

Test yourself: https://jsfiddle.net/hbq0h831/1/

  • thus, it is adding the active before the request is completed, soon after the active is deleted

  • Okay, so you don’t need the click event inside the complete, you can try something like this: complete: function() {&#xA; $(this).addClass("active");&#xA; }

  • That’s what our friend Valdeir suggested in the answers above, but it doesn’t work pro 'this', it only works when I implement the class instead of 'this', but then he makes the addClass for everyone =/

  • I hadn’t noticed... so change the $(this) for $('.waves-effect')

  • I think finally, I understand the problem, I will rewrite and edit the answer..

  • Take a look..

  • Fernando, I made the modifications and I haven’t had any effect.

  • Here it doesn’t work at all, I don’t know if it’s because I’m using Materialize..

  • Can you create something in jsfiddle to better analyze the scenario??

Show 5 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.