preventDefault does not work in Browsers for Mobile

Asked

Viewed 105 times

0

In computer browsers I can prevent the default anchor action normally, but using in most mobile browsers does not work.

I need that when clicking the link the browser does not direct to the link URL, just show in an Alert which URL is in the attribute href, follows code I’m using:

$(".myGallery a").on("click touchstart", function(event){
  event.preventDefault();
  alert($(this).attr("href"));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<div class="myGallery">
  <a href="https://www.yourhtmlsource.com/images/media/banjotooiebig.jpg">
    <img src="https://www.yourhtmlsource.com/images/media/banjotooiesmall.jpg" alt="Image">
  </a>
</div>

I tried in the following browsers to Android:

  • Chrome 70.0.3538.110
  • Chrome 34.0.1847.114
  • Opera Mini 35.0.2254.127755
  • CM Browser 5.22.17.0003
  • 1

    Put a return false; at the end of the function.

1 answer

1

You can put a return false; at the end of the event function that the action of the element that triggered the event will not proceed.

Under normal circumstances the preventDefault() should work, as I tested here in Chrome below mentioned in the question:

inserir a descrição da imagem aqui

Code:

$(".myGallery a").on("click touchstart", function(event){
  event.preventDefault();
  alert($(this).attr("href"));
  return false;
});
  • It worked in this version @Sam, will have a way to make it work in other?

  • Man, weird this, I’ve never seen it not work on... Worse than I can’t even test because I can’t install previous versions of these browsers. Opera Mini, for example, is already in version 37 and there were no problems.

  • I understand, I have a phone that I do not update precisely to test some features, so far this was the only problem I could not solve with old browsers. As I have no way to guarantee which browser the user will access the application have to take precautions.

  • Is it not incompatibility with jQuery? Try to do with pure JS.

  • I will try now with pure JS.

  • With pure JS was not...

  • I don’t know if it will work, but for test purposes, try putting onclick="event.preventDefault()" right in the <a tag>

Show 2 more comments

Browser other questions tagged

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