Javascript Detect click event outside of div

前端 未结 10 945
孤城傲影
孤城傲影 2020-11-27 06:07

I have a div with id=\"content-area\", when a user clicks outside of this div, I would like to alert them to the fact that they clicked outside of it. How would I use JavaSc

10条回答
  •  春和景丽
    2020-11-27 06:26

    I made a simple and small js library to do this for you:

    It hijacks the native addEventListener, to create a outclick event and also has a setter on the prototype for .onoutclick

    Basic Usage

    Using outclick you can register event listeners on DOM elements to detect whether another element that was that element or another element inside it was clicked. The most common use of this is in menus.

    var menu = document.getElementById('menu')
    
    menu.onoutclick = function () {
        hide(menu)
    }
    

    this can also be done using the addEventListener method

    var menu = document.getElementById('menu')
    
    menu.addEventListener('outclick', function (e) {
        hide(menu)
    })
    

    Alternatively, you can also use the html attribute outclick to trigger an event. This does not handle dynamic HTML, and we have no plans to add that, yet

    Have fun!

提交回复
热议问题