HTML
<div class="wrapper">
<div class="bg-backdrop"></div>
</div>
CSS
.wrapper {
position: relative;
z-index: 10;
}
.bg-backdrop {
position: fixed;
top: 0px;
right: 0px;
bottom: 0px;
left: 0px;
background-color: black;
opacity: 0.2;
}
JS
const button = document.createElement("button")
const subject = document.querySelector(".bg-backdrop")
button.textContent = "Register"
subject.insertAdjacentElement("beforebegin",button)
button.addEventListener("click", word)
function word() {
console.log("It works!")
}
the button created inside javascript doesnt work, cant be clicked, and no output is shown
I have tried removing z-index but still not working. Also putting the button element outside of wrapper, still doesnt work
3
Answers
just add this code in javascript file
added this line at line number 5 :
button.setAttribute('style','position:relative; z-index: 100;')
basically we have to add z-index for button and also a position to make z-index work.
You can easily solve this problem by using
z-index: -1
for the.bg-backdrop
class.The issue you’re facing could be related to the stacking context and the z-index of the elements in your code.
Z-Index and Stacking Context:
When an element has a higher z-index within its stacking context, it will appear on top of elements with a lower z-index. However, in your case, the .bg-backdrop element has a fixed position and is likely creating its own stacking context. The dynamically created button, despite having a higher z-index, might be placed behind the .bg-backdrop because of this.
To address this, you can increase the z-index of the dynamically created button and ensure that it is in the same stacking context as the .bg-backdrop element.
HTML:
CSS:
JavaScript:
By keeping the button and the .bg-backdrop in the same stacking context and adjusting their z-index accordingly, the button should be clickable and work as expected.