// on method replaces bind, live and delegate
var link1 = $("#link1");
var f = function(e) {
console.log("f clicked " + $(this).attr("id"));
if ($("#cb1").attr("checked")) {
// this will prevent default behavior of link which is to go to the href. If it is false, after executing the statements in this function, the browser will try to navigate to the web page.
e.preventDefault();
}
if ($("#cb2").attr("checked")) {
// this will stop propagating the bubbling of events to the parent, so div's click wont get called however another associated event on the same link will still get called
e.stopPropagation();
}
if ($("#cb3").attr("checked")) {
// this will stop propagating the bubbling of events to the parent as well as to the same element, hence in this case neither the link's associated event will get called nor the div's
e.stopImmediatePropagation();
}
}
var f1 = function(e) {
console.log("f1 clicked " + $(this).attr("id"));
}
//on method is new in jquery and replaces the bind, delegate and live methods
link1.on("click", f);
link1.on("click", f1);
$("#div1").on("click", f);
//non existing events
var trafficLight = {};
var car = {
lightTurnedGreen: function() {
$("#output").append("Go Ahead..." + "<br/>");
},
lightTurnedRed: function() {
$("#output").append("STOP!!!" + "<br/>");
}
};
// traffic light has 2 custom events called green and red which are connected to car's lightTurnedGreen and lightTurnedRed methods
$(trafficLight).on("green", car.lightTurnedGreen);
$(trafficLight).on("red", car.lightTurnedRed);
$("#btnGreen").click(function() {
// here we trigger the green event
$(trafficLight).trigger("green");
});
$("#btnRed").click(function() {
// here we trigger the red event
$(trafficLight).trigger("red");
});
Please Whitelist JSFiddle in your content blocker.
Help keep JSFiddle free for always by one of two ways:
Whitelist JSFiddle in your content blocker (two clicks)
Go PRO and get access to additional PRO features →
Join the 4+ million users, and keep the JSFiddle dream alive.
Ad-free
All ads in the editor and listing pages are turned completely off.
Use pre-released features
You get to try and use features (like the Palette Color Generator) months before everyone else.
Fiddle collections
Sort and categorize your Fiddles into multiple collections.
Private collections and fiddles
You can make as many Private Fiddles, and Private Collections as you wish!
Console
Debug your Fiddle with a minimal built-in JavaScript console.