简体   繁体   中英

How exactly does event.preventDefault() affect the DOM?

Based on someone's advice I added this line $('body').on('touchstart', function(event){ event.preventDefault() }) in my mobile webapp to disable the native app bouncing in iOS. It works great for disabling the bounce but gives me some weird behavior elsewhere in DOM.

Click events that don't work, etc. I was hoping to get a better understanding of what this does and how to work around it's effects elsewhere in the DOM.

Thanks!

EDIT:

I have these two lines:

  $('body').on('touchstart', function(e){ e.preventDefault() };
  $('#home').on('click', function(){ alert('home') };

If I comment out the preventDefault line then the #home line works. If I leave it in the #home line doesn't respond. #home is just a div nested in the body .

Any idea what could be causing this behavior? It's part of a bigger codebase so it;s hard to give you all the details but I don't even know where to start.

Thanks Again!

e.preventDefault() tells the browser that if there is a default behavior for this event on this object, then skip that default behavior.

So, for example, if you had a submit button that the default behavior was to submit a form and you had a click handler on that button that did a preventDefault() , then the browser would not submit the form when the button was clicked. A classic use of this might be when the form doesn't validate so you show the user an error message and don't want the form to be submitted to the server.

Or another example. If you set up a click handler for a link and you call e.preventDefault() in that click handler, then the browser will not process the click on the link and will not follow the href in the link.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM