Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Button created from javascript is not clickable

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!")
}
.wrapper {
  position: relative;
  z-index: 10;
}

.bg-backdrop {
  position: fixed;
  top: 0px;
  right: 0px;
  bottom: 0px;
  left: 0px;
  background-color: black;
  opacity: 0.2;
}
<div class="wrapper">
 <div class="bg-backdrop"></div>
</div>

the button created inside JavaScript doesn't work, can't 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 doesn't work!

like image 432
young hwc Avatar asked Oct 23 '25 16:10

young hwc


1 Answers

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.

const button = document.createElement("button")
const subject = document.querySelector(".bg-backdrop")

button.textContent = "Register"
button.setAttribute('style', 'position:relative; z-index: 100;')
subject.insertAdjacentElement("beforebegin", button)

button.addEventListener("click", word)

function word() {
  console.log("It works!", document)
}
.wrapper {
  position: relative;
  z-index: 10;
}

.bg-backdrop {
  position: fixed;
  top: 0px;
  right: 0px;
  bottom: 0px;
  left: 0px;
  background-color: black;
  opacity: 0.2;
}
<div class="wrapper">
  <div class="bg-backdrop"></div>
</div>
like image 138
kandarp dangi Avatar answered Oct 26 '25 06:10

kandarp dangi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!