Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • Trigger() method in jQuery

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 422
    Comment on it

    Trigger() method:

    It is used to trigger an event for selected element and also trigger default behaviour of an event for the selected html element. It works similar to the triggerHandler() method, but triggerHandler() does not trigger default behavior of an event.

    Syntax:

     $(selector).trigger(event,[data])
    • event-It specifies the event to trigger for specified element.
    • data- Optional Parameter.It represents additional data to pass as argument to the event handler.

    Example:

    <!DOCTYPE html>
    <html lang="en-us">
    <head>
      <meta charset="utf-8">
      <title>Trigger Method</title>
     
      <script type = "text/javascript" 
             src = "https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
       <script type = "text/javascript" language = "javascript">
             $(document).ready(function() {
          
                $("#box1").click( function () {
                   $("#box2").trigger('click');   // It will trigger click event on box2
                });
    
                $("#box2").click( function () {
                   alert( "Box 2 has been clicked");
                   $("#box2").css("background", "grey");
                });
            
             });
          </script>
          <style type="text/css">
             #box1{background:#64B96B;width:200px;border:1px solid #000;padding:25px;color:#fff;line-height:30px;text-align: center;}
             #box2{background:#64B96B;width:200px;border:1px solid #000;padding:25px;color:#fff;line-height:30px;text-align: center;margin-top: 20px;}
          </style>
    </head>
    <body>
      <p>Click Box 1 to see the result:</p>
        
          <div id = "box1">
            <p>Box 1</p>
            
          </div>
    
          <div id = "box2">
            <p>Box 2</p>
          </div>
        </body>
    </html>

    In the above example on clicking box 1 we are triggering click event on box 2 and we are changing the background color of box2 when it will be clicked by user.

    You can check the output of above example here: https://jsfiddle.net/gf1mfu2a/

     

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: