Triggering Events Programmatically
In this page:
Trigger Click
trigger(click) fires an element's click handlers programmatically, exactly as if a user had physically clicked it. This is commonly used to simulate user interaction from within a script or test.
Example: Trigger Click
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
</head>
<body>
<button id="btn">Click</button>
<script>
$("#btn").on("click", function() { console.log("Clicked!"); });
$("#btn").trigger("click");
</script>
</body>
</html>
Trigger Change
Triggering a change event with trigger(change) is useful after you've updated a form control's value via JavaScript, since setting .val() directly does not automatically fire the handlers a real user interaction would.
Example: Trigger Change
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
</head>
<body>
<input id="name" type="text">
<script>
$("#name").on("change", function() { console.log("Changed to:", $(this).val()); });
$("#name").val("Alice").trigger("change");
</script>
</body>
</html>
Trigger Custom Events
trigger() also works with entirely custom event names you invent yourself, like trigger('cart:updated'), letting different parts of your code communicate without directly calling each other's functions.
Example: Trigger Custom Events
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
</head>
<body>
<script>
$(document).on("cart:updated", function() {
console.log("Cart was updated");
});
$(document).trigger("cart:updated");
</script>
</body>
</html>
Pass Event Data
Passing an array as trigger()'s second argument sends extra data along to the handler, which receives it as additional arguments after the event object.
Example: Pass Event Data
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
</head>
<body>
<script>
$(document).on("greet", function(event, name) {
console.log("Hello,", name);
});
$(document).trigger("greet", ["Alice"]);
</script>
</body>
</html>
Trigger Form Events
Triggering form events programmatically is especially useful in automated tests, where you want to simulate a user submitting a form or checking a box without any actual user interaction.
Example: Trigger Form Events
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
</head>
<body>
<form id="myForm"><input type="checkbox" id="agree"></form>
<script>
$("#agree").on("change", function() { console.log("Checkbox toggled:", $(this).is(":checked")); });
$("#agree").prop("checked", true).trigger("change");
</script>
</body>
</html>
Chapter Quiz — Complete all 11 topics to unlock
0/11 topics done
Complete these topics first: