skip to Main Content

When I press a <button>, I want to wait for an asynchronous function, then add some classes to the <button>, but it doesn’t work. I want to use jQuery to do this.

Here is my code:

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

2

Answers


  1. 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.

    Login or Signup to reply.
  2. 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')
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search