jQuery delegate()
0 1496
- The delegate() jQuery function binds one or more event handlers with the specific HTML elements that are children of selected HTML element.
- This method provides a function to run when the events occur.
- If we create an element in runtime by script, this method will also work for that element.
Related Topics:
jQuery load
jQuery unload
jQuery delegate()
Syntax:
$(selector). delegate(child_selector,event,data,function);
Parameter description:
- child_selector: This parameter represents one or more child elements to attach to the event handler. It is a mandatory parameter.
- event: This parameter represents one or more events to attach to the elements. It is also mandatory.
- data: This represents the additional data to pass to the function. It is an optional parameter.
- function: It represents the function to run when the event occurs.
Example:
<html>
<head>
<title> jQuery Example </title>
<script type = "text/javascript"
src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js">
</script>
<style>
p{
background:pink;
padding:20px;
}
span{
background:green;
color:white;
padding:20px;
}
</style>
<script>
$(document).ready(function(){
$("body").delegate("p", "click", function(){
$(this).slideToggle();
});
$("span").click(function(){
$("<p>Click me to hide!</p>").insertAfter("span");
});
});
</script>
</head>
<body>
<h2> jQuery delegate() Method Example </h2>
<p> Click me to hide! </p>
<span> Click me to insert new one </span>
</body>
</html>
Output:
When you click on the pink paragraph, it will hide immediately.
When you click on the green paragraph, It will insert a new paragraph every time.
Share:
Comments
Waiting for your comments