Home > database >  jQuery inside an event using classList
jQuery inside an event using classList

Time:10-23

I'm trying to add some classes to a button when I press it, but it doesn't work.

Here is my code:

$("#btnSta").addEventListener("click", () => {
    getAccount().then(addresses => {
        $("#btnSta").classList.add('opacity-50 cursor-not-allowed');
    }
})

CodePudding user response:

You are trying to combine the DOM API (.classList) with jQuery. Instead, you should only use jQuery functions. The equivalent jQuery is this:

async function getAccount() {
  // .. do something ..
  return null; // just for the example
}

$("#btnSta").click(async () => {
  const addresses = await getAccount();
  $("#btnSta").addClass('opacity-50 cursor-not-allowed');
});
.opacity-50 {
  opacity: 50%;
}

.cursor-not-allowed {
  cursor: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button id="btnSta">Test</button>

You can also change your .then statement to the newer async/await syntax.

CodePudding user response:

As noted you are referencing vanila javascript methods on jquery selectors. Change parts

$("#btnSta").addEventListener("click",

to

$("#btnSta").on("click",

and

$("#btnSta").classList.add('opacity-50 cursor-not-allowed')

to

$("#btnSta").addClass('opacity-50 cursor-not-allowed')
  • Related