Home > Mobile >  Close div by clicking outside (with 2 different divs)
Close div by clicking outside (with 2 different divs)

Time:06-23

In my web i did two div with message 1 for succes and the other one for error, i have been searching how to do it but when i did it, only one div closes, for example if the succes div appears i could close, but if the error div appears it doesn´t close.

Here is my code:

 function hideAlertInc() {
    document.getElementById("alert-inc").style.display = "none";
}

function hideAlertCo() {
    document.getElementById("alert-co").style.display = "none";
}

document.onclick = function (e) {
    if (e.target.id !== 'alert-inc') {
        hideAlertInc()
    }
}

document.onclick = function (b) {
    if (b.target.id !== 'alert-co') {
        hideAlertCo()
    }
}

CodePudding user response:

You have added onclick event two times. The last one is called and the previous one is overridden. Using the following should work:

document.onclick = function (e) {
    if (e.target.id !== 'alert-inc') {
        hideAlertInc()
    }
    if (b.target.id !== 'alert-co') {
        hideAlertCo()
    }
}

CodePudding user response:

i could do it if someone is interesting the only thing i do is change onclick on the second div to onm ousedown

like this:

    function hideAlertInc() {
    document.getElementById("alert-inc").style.display = "none";
}

function hideAlertCo() {
    document.getElementById("alert-co").style.display = "none";
}

document.onclick = function (e) {
    if (e.target.id !== 'alert-inc') {
        hideAlertInc()
    }else{
        hideAlertInc()
    }
}

document.onmouseup = function (e) {
    if (e.target.id !== 'alert-co') {
        hideAlertCo()
    }else{
        hideAlertCo()
    }
}

If someone know a better solution let me know.

  • Related