Reputation: 15
I tried to bind document to delegate my click event if user click out of the part of loginpage it should be disappear or be removed, but except signinpage when I clicked loginpage the others part it still be removed(like input). it should bubble to the div signinpage or it's not working like that? it have confused me two days, plz help me to fix it.
const loginbtn = document.getElementById('loginbtn')
const whitepart = document.getElementById('whitepart')
const loginpage = document.createElement('div')
loginpage.id = "loginpageid"
loginbtn.addEventListener('click', () => {
whitepart.appendChild(loginpage)
loginpage.innerHTML = `
<div id="sign_in_out" >
<div id="logopaint">
<img src="../image/FE_logo-2.png" alt="sorry, something worng!">
</div>
<form id="forclick">
<input type="email" name="user_email" id="mail" placeholder="Email" autocomplete="email">
<input type="password" name="user_password" id="password" placeholder="Password" autocomplete="current-password">
</form>
</div>`
const signinpage = document.getElementById('sign_in_out')
if (!!signinpage) {
document.addEventListener('click', (e) => {
if (e.target !== signinpage) {
loginpage.removechild(signinpage)
}
})
}
Upvotes: 1
Views: 48
Reputation: 10604
Inside your click listener change e.target !== signinpage
to e.target.closest("#sign_in_out")
, so if the user click inside the login page, the e.target.closest("#sign_in_out")
will return the sign_in_out
div reference, otherwise the reference will be null.
When you use
e.target
it can be anything, it can beimg, form, or input
, theevent.target
returns the item on which user clicked. The target property of the Event interface is a reference to the object that dispatched the event.
document.addEventListener('click', (e) => {
if (e.target.closest("#sign_in_out") === null) {
loginpage.removechild(signinpage)
}
})
Upvotes: 2