I'm trying to create a drawer on my eCommerce website. I want the drawer to be displayed as none when 1 of 3 things happens: I click outside of the section, I press Esc or I press the X button. I have a method that handles all 3 of them. Only when I click outside of the section the section disappears. When I try to consolelog them at the beginning of the method it returns what I expect to be returned. When I try to press the button nothing happens. When i try to press Esc i get this error:Uncaught TypeError: Cannot read properties of undefined (reading 'style')at HTMLDocument. (main.js:84:27).Why? Thank you.
let drawer = {
cartDrawer: document.getElementById("cartDrawer"),
drawerButton: document.getElementById('closeDrawer'),
generateDrawer() {
return (this.cartDrawer.innerHTML =this.cartDrawer.innerHTML+ basket
.map((x) => {
let { id, item } = x
let search = shopItemsData.find((y) => y.id === id) || []
return `
<div class='container'>
<div class='cartDrawerDetails'>
<p><img src=${search.img} alt="" />${search.desc}</p>
<div>${search.price}</div>
<div class="drawerQuantity">
<i onclick="changeItem.decrement(${id})" class="fa-solid fa-minus"></i>
<div class="quantity">${item}</div>
<i onclick="changeItem.increment(${id})" class="fa-solid fa-plus"></i></div>
</div>
<div class='erase' onclick="changeItem.removeItem(${id})">Sterge</div>
</div>
`
}).join(""))
},
closeDrawer() {
console.log(this.drawerButton)
console.log(this.cartDrawer)
//This works
document.addEventListener('click', (event) => {
const withinBoundaries = event.composedPath().includes(this.cartDrawer)
if (!withinBoundaries) {this.cartDrawer.style.display = 'none'}
})
//This doesnt works
this.drawerButton.addEventListener('click', () => {
console.log(this.cartDrawer)
this.cartDrawer.style.display = 'none'}
)
document.addEventListener('keydown', function(event){
if(event.key === "Escape")
{
this.cartDrawer.style.display = 'none'}
})
}}