jQuery - on()

on() adds an any event listener.

Also - The on() method attaches one or more event handlers for the selected elements. Mouseover or click the Hello World text.

Hello World


// javascript
orderButton.addEventListener("click", function () { alert("buying"); });

// is same as jQuery's...
orderButton.on("click", function () { alert("buying"); });

$("#demo1").on(
{
    mouseenter: function () { $(this).css("background-color", "lightgray"); },
    mouseleave: function () { $(this).css("background-color", "lightblue"); },
    click: function () { $(this).css("background-color", "yellow"); }
});

 

Another example...click a item

  • Price: $9.99
  • Artist: Van Gogh
  • Title:
  • Description: Self-portrait

let productInfo = $(".product-props li");
productInfo.on("click", function () { alert("you clicked on [" + $(this).text()+ "]");});

The straight javascript approach would be to use addEventLister like so:


    var demo2 = document.getElementById("demo2");
    demo2.addEventListener("mouseover", function () { demo2.style.backgroundColor = "#D94A38"; });
    demo2.addEventListener("mouseout", function () { demo2.style.backgroundColor = "#ffcc00"; });