简体   繁体   中英

How to restore browser default behavior for an event? (javascript)

I have a webpage (using HTML5/javascript) using divs to define the layout.

As I have a handful of elements that I want to be able to drag and do not want text selected during this process, I have disabled the selectstart and onmousedown events for the outermost container div, using:

document.getElementById("mapContainer").onselectstart = function(){return false;};
document.getElementById("mapContainer").onmousedown = function(){return false;};

However, I also have a text box within the layout that I need to be able to select and write in for searching purposes. I have found numerous topics on how to disable browser default behavior for an event, but nothing concrete about how to restore the default behavior. I can if need be, but I would like to avoid significant re-writes to the script. Thus, I was wondering if there is a "restoreDefault" type function/setting that I could apply to just the text box.

Thanks.

Use addEventLsitener and removeEventListener for better access to your event listeners:

function fooBar(){
    return false;
}

document.getElementById('mapContainer').addEventListener('selectstart', fooBar);    // Start listening
document.getElementById('mapContainer').removeEventListener('selectstart', fooBar); // Stop lsitening

You can also remove the event listener you currently have like this:

document.getElementById('mapContainer').onmousemove = null;

You can check to see if it starts in the textarea before disabling it:

HTML

<div id="mapContainer">
  <h2>What what?</h2>
  <textarea id="ta">FOO BAR WORLD</textarea>
</div>

JavaScript

function testForElement(e) {
      e = e || window.event;
      var elem = e.srcElement || e.target;
      return elem && elem.id==="ta";
}

var myDiv = document.getElementById("mapContainer");
myDiv.onselectstart = testForElement;
myDiv.onmousedown = testForElement;

Example

JSFiddle

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