Open In App

Explain the use of the $.fn.bind and $.fn.trigger

In this article, we will learn two methods that are related to jQuery events of DOM when the user or the program triggers an event.

Use of bind():



Example 1:




<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" 
        content="IE=edge">
    <meta name="viewport" content=
"width=device-width, initial-scale=1.0">
    <script src=
    </script>
    <title>Bind Method</title>
    <style>
        div{
            background-color: #ff0056;
            height: 200px;
            width: 200px;
        }
    </style>
</head>
<body>
    <h2 style="color:green">GeeksforGeeks</h2>
    <div id="colour-box"></div>
     
    <script>
        colours = ['steelblue', 'tomato', 'aquamarine', '#ff0056', 
                'khaki', 'black', 'gray', 'blue', 'green',
                'yellow', 'brown', 'golden', 'violet', 'orange'];
        $("#colour-box").bind("mouseover click mouseout", ()=>{
            color = colours[(Math.floor(Math.random()*colours.length))];
            $("#colour-box").css("background-color", `${color}`)
        })
    </script>
</body>
</html>

 



Output:

 

Use of trigger():

Example:




<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <script src=
    </script>
    <meta name="viewport" content=
 "width=device-width, initial-scale=1.0">
     
    <style>
        div{
            background-color: #ff0056;
            height: 200px;
            width: 200px;
        }
    </style>
</head>
<body>
    <h2 style="color:green">GeeksforGeeks</h2>
    <div id="colour-box"></div>
    <hr>
    <h1>Triggerring click event on div tag <br/>
        without clicking on the div tag</h1>
    <button id="trigger">Click Me</button>
    
    <script>
        colours = ['steelblue', 'tomato', 'aquamarine', '#ff0056', 'khaki', 
            'black', 'gray', 'blue', 'green', 'yellow', 
            'brown', 'golden', 'violet', 'orange'];
        $("#colour-box").bind("mouseover click mouseout", ()=>{
            color = colours[(Math.floor(Math.random()*colours.length))];
            $("#colour-box").css("background-color", `${color}`)
        })
  
        $("#trigger").click(()=>{
            $("#colour-box").trigger('click');
        })
    </script>
</body>
</html>

Output:

 

 


Article Tags :