Search code examples
javascriptjqueryweb

Equivalent of attaching a listener to buttons on document ready in jQuery instead of vanilla JavaScript?


How do I convert this JavaScript code to jQuery code?

if (document.readyState == 'loading') {
    document.addEventListener('DOMContentLoaded', ready)
} else {
    ready()
}

function ready() {
    var removeCartItemButtons = document.getElementsByClassName('btn-danger')
    for (var i = 0; i < removeCartItemButtons.length; i++) {
        var button = removeCartItemButtons[i]
        button.addEventListener('click', removeCartItem)
    }
}

Solution

  • Running something when the document is ready is handled by the $( document ).ready() method.

    getElementByClassName can be replaced by a Class Selector (".class")

    Your for loop can be removed because with jQuery methods all are called on each returned element.

    addEventListener can be replaced by .click().

    Then your code is just three lines long:

    $(function(){
        $('.btn-danger').click(removeCartItem)
    })