Search code examples
javascriptdom-events

How to restore browser default behavior for an event?


I have a web page (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.


Solution

  • 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;