What is jQuery Events

jQuery events are the actions that can be detected by your web application. They are used to create dynamic web pages. An event shows the exact moment when something happens


All the different visitors' actions that a web page can respond to are called events.
An event represents the precise moment when something happens.
Examples:


  1. moving a mouse over an element
  2. selecting a radio button
  3. clicking on an element
  4. Types of events

    1. Mouse Events
      • click
      • dblclick
      • mouseenter
      • mouseleave
    2. Keyboard Events
      • keypress
      • keydown
      • keyup
    3. Form Events
      • submit
      • change
      • focus
      • blur
    4. Document/Window Events
      • load
      • resize
      • scroll
      • unload

    jQuery Event Methods

    1) click()

    <html>
    <head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
    <script>
    $(document).ready(function(){
    $("p").click(function(){
    $(this).hide();
    });
    });
    </script>
    </head>
    <body>
    <p>If you click on me, I will disappear.</p>
    <p>Click me away!</p>
    <p>Click me too!</p>
    </body>
    </html>

    2) dblclick()

    $("p").dblclick(function(){
    $(this).hide();
    });



    3) mouseenter()

    $("#p1").mouseenter(function(){
    alert("You entered p1!");
    });

    4) mouseleave()

    $("#p1").mouseleave(function(){
    alert("Bye! You now leave p1!");
    });

    5) mousedown()

    $("#p1").mousedown(function(){
    alert("Mouse down over p1!");
    });

    6) mouseup()

    $("#p1").mouseup(function(){
    alert("Mouse up over p1!");
    });

    7) hover()

    <html>
    <head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
    <script>
    $(document).ready(function(){
    $("#p1").hover(function(){
    alert("You entered p1!");
    },
    function(){
    alert("Bye! You now leave p1!");
    });
    });
    </script>
    </head>
    <body>
    <p id="p1">This is a paragraph.</p> </body>
    </html>

    The on() Method

    The on() method attaches one or more event handlers for the selected elements.
    Attach a click event to a

    element:

    <html>
    <head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
    <script>
    $(document).ready(function(){
    $("p").on({
    mouseenter: function(){
    $(this).css("background-color", "lightgray");
    },
    mouseleave: function(){
    $(this).css("background-color", "lightblue");
    },
    click: function(){
    $(this).css("background-color", "yellow");
    }
    });
    });
    </script>
    </head>
    <body>
    <p>Click or move the mouse pointer over this paragraph.</p>
    </body>
    </html>