• Home
  • HTML
    • HTML Introduction
    • HTML Basic
    • HTML Elements
    • HTML Attributes
    • HTML Headings
    • HTML Paragraphs
    • HTML Text Formatting
    • HTML Styles
    • HTML Comments
    • HTML Styles - CSS
    • HTML Links
    • HTML Images
    • HTML Tables
    • HTML Lists
    • HTML Block and Inline Elements
    • HTML class Attribute
    • HTML Forms
    • HTML Media
  • CSS
    • Introduction of CSS
    • CSS Syntax
    • CSS Selectors
    • How To Add CSS
    • CSS Comments
    • CSS Colors
    • CSS Backgrounds
    • CSS Borders
    • CSS Margins
    • CSS Text
    • CSS Lists
    • CSS Tables
    • CSS Box Model
    • CSS Dimension
    • CSS Padding
    • CSS Border
    • CSS Margin
    • CSS Outline
    • CSS Cursors
    • CSS Overflow
    • CSS Units
    • CSS Visual Formatting
    • CSS Display
    • CSS Visibility
    • CSS Position
    • CSS Layers
    • CSS Float
    • CSS Alignment
    • CSS Pseudo-classes
    • CSS Pseudo-elements
    • CSS Media Types
    • CSS Sprites
    • CSS Opacity
    • CSS Attribute Selectors
    • CSS Validation
    • CSS3 Border
    • CSS3 Gradients
    • CSS3 Text Overflow
  • JavaScript
    • JS Introduction
    • JS Getting Started
    • JS Syntax
    • JS Variables
    • JS Generating Output
    • JS Data Types
    • JS Operators
    • JS Events
    • JS Strings
    • JS Numbers
    • JS If Else
    • JS Switch Case
    • JS Arrays
    • JS Sorting Arrays
    • JS Loops
    • JS Functions
    • JS Objects
    • JS DOM Nodes
    • JS DOM Selectors
    • JS DOM Styling
    • JS DOM Get Set Attributes
    • JS DOM Manipulation
    • JS DOM Navigation
    • JS Window
    • JS Screen
    • JS Location
    • JS History
    • JS Navigator
    • JS Dialog Boxes
    • JS Timers
    • JS Date and Time
    • JS Math Operations
    • JS Type Conversions
    • JS Event Listeners
    • JS Event Propagation
    • JS Borrowing Methods
    • JS Hoisting Behavior
    • JS Closures
    • JS Strict Mode
    • JS JSON Parsing
    • JS Error Handling
    • JS Regular Expressions
    • JS Form Validation
    • JS Cookies
    • JS AJAX Requests
    • JS ES6 Features
  • jQuery
    • jQuery Introduction
    • jQuery Syntax
    • jQuery Selectors
    • jQuery Events
    • jQuery Show/Hide
    • jQuery Fade
    • jQuery Slide
    • jQuery Animation
    • jQuery Stop
    • jQuery Chaining
    • jQuery Callback
    • jQuery Get/Set
    • jQuery Insert
    • jQuery Remove
    • jQuery CSS Classes
    • jQuery Style Properties
    • jQuery Dimensions
    • jQuery Traversing
    • jQuery Ancestors
    • jQuery Descendants
    • jQuery Siblings
    • jQuery Filtering
    • jQuery Ajax
    • jQuery Load
    • jQuery Get/Post
    • jQuery No-Conflict
  • PHP
    • PHP Introduction
    • PHP Install
    • PHP Syntax
    • PHP Comments
    • PHP Variables
    • PHP Echo / Print
    • PHP Data Types
    • PHP Strings
    • PHP Constants
    • PHP Operators
    • PHP If...Else...Elseif
    • PHP Switch
    • PHP Loops
    • PHP Functions
    • PHP Arrays
    • PHP Superglobals
    • PHP Date and Time
    • PHP Include
    • PHP File Handling
    • PHP File Upload
    • PHP Cookies
    • PHP Sessions
    • PHP Filters
    • PHP Callback Functions
    • PHP JSON
    • PHP Exceptions
    • PHP What is OOP
    • PHP Classes/Objects
    • PHP Constructor
    • PHP Destructor
    • PHP Access Modifiers
    • PHP Inheritance
    • PHP Abstract Classes
    • PHP Interfaces
    • PHP Traits
    • PHP Static Methods
    • PHP Namespaces
  • SQL
    • Introduction to SQL
    • SQL Create Command
    • SQL ALTER Command
    • SQL Truncate Drop Rename
    • INSERT SQL command
    • UPDATE SQL command
    • DELETE SQL command
    • SQL COMMIT command
    • SQL ROLLBACK command
    • SQL GRANT and REVOKE Command
    • SQL WHERE clause
    • SQL LIKE clause
    • SQL ORDER BY Clause
    • SQL Group By Clause
    • SQL HAVING Clause
    • SQL DISTINCT keyword
    • SQL AND OR operator
    • SQL Constraints
    • SQL Functions
    • SQL JOIN
  • Python
    • Getting started with Python
    • Introduction to IDLE
    • Python 2.x vs. Python 3.x
    • Syntax Rules and First Program
    • Numbers and Math Functions
    • Python Operators
    • Python Variables
    • Python Modules and Functions
    • Python Input and Output
    • Data Types in Python
    • String in Python
    • String Functions in python
    • Lists in Python
    • Utilizing List Elements by Iterating
    • Deleting List Elements & other Functions
    • Dictionaries in Python
    • Functions for Dictionary
    • Tuples in Python
    • Relational and Logical Operators
    • Conditional Statements in Python
    • Looping in Python
    • Define Functions in Python
    • Python-Introduction to OOP
    • Object Oriented Programming in Python
    • Classes in Python
    • The concept of Constructor
    • Destructors - Destroying the Object in Python
    • Inheritance in Python
    • Access Modifers in Python
    • Types of Inheritance
    • Method Overriding in Python
    • Polymorphism
    • static Keyword
    • Operator Overloading Python
    • Introduction to Error Handling
    • Exception Handling: try and except
    • Exeption Handling: finally
    • Exception Handling: raise
    • File Handling
    • Reading and Writing File
    • Introduction to Multithreading
    • Threading Module in Python
    • Thread Object
    • Lock Object
    • RLock Object
    • Event Object
    • Timer Object
    • Condition Object
    • Barrier Object
    • __name__ Variable in Python
    • Iterable and Iterator
    • yield Keyword
    • Python Generators
    • Python Closures
    • Python Decorators
    • @property Decorator in Python
    • Assert Statement
    • Garbage Collection
    • Shallow and Deep Copy
    • Introduction to Logging
    • Configure Log LEVEL, Format etc
    • Python Logging in a file
    • Python Logging Variable Data
    • Python Logging Classes and Functions
    • Python MySQL Introduction
    • Create Database - Python MySQL
    • Create Table - Python MySQL
    • Insert Data in Table
    • Select Data from Table
    • Update data in Table
    • Delete data from Table
    • Drop Table from Database
    • WHERE clause - Python MySQL
    • Order By clause - Python MySQL
    • Limit clause - Python MySQL
    • Table Joins - Python MySQL
  • MongoDB
    • MongoDB Introduction
    • Overview of MongoDB
    • MongoDB vs SQL Databases
    • Advantages of MongoDB
    • When to go for MongoDB
    • Data Modelling in MongoDB
    • Is MongoDB really Schemaless?
    • Installing MongoDB on Windows and Linux
    • Datatypes in MongoDB
    • Create and Drop Database in MongoDB
    • MongoDB: Creating a Collection
    • CRUD Operations in MongoDB
    • Data Relationships in MongoDB
    • Indexing in MongoDB
    • Sorting in MongoDB
    • Aggregation in MongoDB
    • Data Backup and Restoration in MongoDB
    • Sharding in MongoDB
    • Java Integration with MongoDB
  • Elixir
    • Elixir Overview
    • Elixir Environment
    • Elixir Basic Syntax
    • Elixir Data Types
    • Elixir Variables
    • Elixir Operators
    • Elixir Pattern Matching
    • Elixir Decision Making
    • Elixir Strings
    • Elixir Char Lists
    • Elixir Lists and Tuples
    • Elixir Keyword Lists
    • Elixir Maps
    • Elixir Modules
    • Elixir Aliases
    • Elixir Functions
    • Elixir Recursion
    • Elixir Loops
    • Elixir Enumerables
    • Elixir Streams
    • Elixir Structs
    • Elixir Protocols
    • Elixir File I/O
    • Elixir Processes
    • Elixir Sigils
    • Elixir Comprehensions
    • Elixir Typespecs
    • Elixir Behaviours
    • Elixir Errors Handling
    • Elixir Macros
    • Elixir Libraries
  • TypeScript
    • TypeScript Overview
    • Install TypeScript
    • First TypeScript Program
    • Type Annotation
    • TypeScript Variable
    • TypeScript Data Type Number
    • TypeScript Data Type String
    • TypeScript Data Type Boolean
    • TypeScript Arrays
    • TypeScript Tuples
    • TypeScript Enum
    • TypeScript Union
    • TypeScript Any Data Type
    • TypeScript Void Data Type
    • TypeScript Never Data Type
  • Home
  • jQuery Introduction
  • jQuery Syntax
  • jQuery Selectors
  • jQuery Events
  • jQuery Show/Hide
  • jQuery Fade
  • jQuery Slide
  • jQuery Animation
  • jQuery Stop
  • jQuery Chaining
  • jQuery Callback
  • jQuery Get/Set
  • jQuery Insert
  • jQuery Remove
  • jQuery CSS Classes
  • jQuery Style Properties
  • jQuery Dimensions
  • jQuery Traversing
  • jQuery Ancestors
  • jQuery Descendants
  • jQuery Siblings
  • jQuery Filtering
  • jQuery Ajax
  • jQuery Load
  • jQuery Get/Post
  • jQuery No-Conflict
Home >> jquery >> jQuery Events

jQuery Events

Events are mostly triggered by the user's interaction with the page, like when a button or link is clicked, a selection is made in a select box, a key is pressed on the keyword, the mouse pointer is moved, the text is entered into an input box or textarea and so on. However, the browser on its own can trigger the events, like the page load and unload events.

JQuery improves the fundamental event-handling mechanisms by offering the events methods for most native browser events. These methods includes ready(), click(), keypress(), focus(), blur(), change(), and so on. Take for instance, in other for you to execute some JavaScript code when the DOM is ready, you can use the jQuery ready() method, as shown below:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Executing a Function when Document is Ready in jQuery</title>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
$(document).ready(function(){
    // Code to be executed
    alert("Hello World!");
});
</script> 
</head>
<body>
    <!--Contents will be inserted here-->
</body>
</html>

Try with example

 

Events can be categorized into four main groups. These four groups will be discussed briefly in this tutorial, as well as related jQuery methods one after the other.

 

Mouse Events

For example, when the user clicks some event or moves the mouse pointer the mouse event is fired. 

Below are some commonly used jQuery methods to handle the mouse events.

The click() Method

The click() method in jQuery is used to attach an event handler function to the selected elements for the "click" event. This attached function is executed the element is clicked by the user. The example below shows how you can hide the <p> elements on a page when they are clicked.

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Executing a Function on Click Event in jQuery</title>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<style>
    p{
        padding: 20px;
        font: 20px sans-serif;
        background: khaki;
    }
</style>
<script>
$(document).ready(function(){
    $("p").click(function(){
        $(this).slideUp();
    });
});
</script>
</head>
<body>
    <p>Click on me and I'll disappear.</p>
    <p>Click on me and I'll disappear.</p>
    <p>Click on me and I'll disappear.</p>
</body>
</html>

Try with example

 

The dblclick() Method

The dblclick() method in jQuery attaches an event handler function to the selected elements for the "dblclick" event. When the user double-clicks on the element, the attached function is then executed. The example below shows how you can hide the <p> elements when they are double-clicked.

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Executing a Function on Double-click Event in jQuery</title>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<style>
    p{
        padding: 20px;
        font: 20px sans-serif;
        background: khaki;
    }
</style>
<script>
$(document).ready(function(){
    $("p").dblclick(function(){
        $(this).slideUp();
    });
});
</script>
</head>
<body>
    <p>Double-click on me and I'll disappear.</p>
    <p>Double-click on me and I'll disappear.</p>
    <p>Double-click on me and I'll disappear.</p>
</body>
</html>

Try with example

 

The hover() Method

The hover() method in jQuery attaches one or two event handler functions to the selected elements that are executed if the mouse pointer enters and also leaves the elements. When the user places a mouse pointer over an element, the first function is executed, while the second function is executed when the user removes the mouse pointer from that same element.

The example below shows how you can highlight <p> elements when you place the cursor on it, the highlighting will be removed when you remove the cursor.

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Executing a Function on Hover Event in jQuery</title>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<style>
    p{
        padding: 20px;
        font: 20px sans-serif;
        background: #f2f2f2;
    }
    p.highlight{
        background: yellow;
    }
</style>
<script>
$(document).ready(function(){
    $("p").hover(function(){
        $(this).addClass("highlight");
    }, function(){
        $(this).removeClass("highlight");
    });
});
</script>
</head>
<body>
    <p>Place mouse pointer on me.</p>
    <p>Place mouse pointer on me.</p>
    <p>Place mouse pointer on me.</p>
</body>
</html>

Try with example

 

The mouseenter() Method

The mouseenter() method in jQuery attaches an event handler function to the selected elements that are executed only if the mouse enters an element. The example below shows how you can add the class highlight to the <p> element when you place the cursor on it.

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Executing a Function on Mouseenter Event in jQuery</title>
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<style>
    p{
        padding: 20px;
        font: 20px sans-serif;
        background: #f2f2f2;
    }
    p.highlight{
        background: yellow;
    }
</style>
<script>
$(document).ready(function(){
    $("p").mouseenter(function(){
        $(this).addClass("highlight");
    });
    $("p").mouseleave(function(){
        $(this).removeClass("highlight");
    });
});
</script>
</head>
<body>
    <p>Place mouse pointer on me.</p>
    <p>Place mouse pointer on me.</p>
    <p>Place mouse pointer on me.</p>
</body>
</html>

Try with example

 

The mouseleave() Method

The mouseleave() method in jQuery attaches an event handler function to the selected elements that are executed if the mouse leaves an element. The example below shows how you can remove the class highlight from the <p> element when you remove the cursor from it.

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Executing a Function on Mouseleave Event in jQuery</title>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<style>
    p{
        padding: 20px;
        font: 20px sans-serif;
        background: #f2f2f2;
    }
    p.highlight{
        background: yellow;
    }
</style>
<script>
$(document).ready(function(){
    $("p").mouseenter(function(){
        $(this).addClass("highlight");
    });
    $("p").mouseleave(function(){
        $(this).removeClass("highlight");
    });
});
</script>
</head>
<body>
    <p>Place mouse pointer on me.</p>
    <p>Place mouse pointer on me.</p>
    <p>Place mouse pointer on me.</p>
</body>
</html>

Try with example

 

Keyboard Events

When the user press or release a key on the keyboard, the keyboard event is fired.. below are some commonly used jQuery methods in handling the keyboard events.

The keypress() Method

The keypress() method in jQuery attaches an event handler function to the selected elements (also acts as form controls) that is executed if the browser receives keyboard input from any user. The example shown below will display a message when the keypress event is fired and how many times it is fired when you press the key on the keyboard.

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Executing a Function on Keypress Event in jQuery</title>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<style>
    p{
        padding: 10px;
        background: lightgreen;
        display: none;
    }
    div{
        margin: 20px 0;
    }
</style>
<script>
$(document).ready(function(){
    var i = 0;
    $('input[type="text"]').keypress(function(){
        $("span").text(i += 1);
        $("p").show().fadeOut();
    });
});
</script>
</head>
<body>
    <input type="text">
    <div>Keypress: <span>0</span></div>
	<div><strong>Note:</strong> Enter something inside the input box and see the result.</div>
    <p>Keypress is triggered.</p>
</body>
</html>

Try with example

 

The keydown() Method

The jQuery keydown() method in jQuery attaches an event handler function to the selected elements (it acts as form controls) that is executed if the user first presses a key on the keyboard. The example shown below will display a message when the keydown event is fired and how many times it is fired if you press the key on the keyboard.

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Executing a Function on Keydown Event in jQuery</title>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<style>
    p{
        padding: 10px;
        background: lightgreen;
        display: none;
    }
    div{
        margin: 20px 0;
    }
</style>
<script>
$(document).ready(function(){
    var i = 0;
    $('input[type="text"]').keydown(function(){
        $("span").text(i += 1);
        $("p").show().fadeOut();
    });
});
</script>
</head>
<body>
    <input type="text">
    <div>Keydown: <span>0</span></div>
	<div><strong>Note:</strong> Enter something inside the input box and see the result.</div>
    <p>Keydown is triggered.</p>
</body>
</html>

Try with example

 

The keyup() Method

The jQuery keyup() method in jQuery attaches an event handler function to the selected elements (it acts as form controls) that is executed only if the user releases a key on the keyboard. The example shown below will display a message when the keyup event is fired and how many times it is fired if you press and release a key on the keyboard.

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Executing a Function on Keyup Event in jQuery</title>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<style>
    p{
        padding: 10px;
        background: lightgreen;
        display: none;
    }
    div{
        margin: 20px 0;
    }
</style>
<script>
$(document).ready(function(){
    var i = 0;
    $('input[type="text"]').keyup(function(){
        $("span").text(i += 1);
        $("p").show().fadeOut();
    });
});
</script>
</head>
<body>
    <input type="text">
    <div>Keyup: <span>0</span></div>
	<div><strong>Note:</strong> Enter something inside the input box and see the result.</div>
    <p>Keyup is triggered.</p>
</body>
</html>

Try with example

 

Form Events

A form event in jQuery is fired when a form control receives or loses focus, or when the user modifies a form control value by doing either of these; typing text in a text input, selecting an option in a select box, and so on. Below are some commonly used jQuery methods in handling the form events.

The change() Method

The change() method in jQuery attach an event handler function to the <input>, <textarea> and <select> elements which are executed when their value changes. The example shown below will display an alert message if you select any option in dropdown select box.

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Executing a Function on Change Event in jQuery</title>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
$(document).ready(function(){
    $("select").change(function(){
        var selectedOption = $(this).find(":selected").val();
        alert("You have selected - " + selectedOption);
    });
});
</script>
</head>
<body>
    <form>
        <label>City:</label>
        <select>
            <option>London</option>
            <option>Paris</option>
            <option>New York</option>
        </select>
    </form>
	<p><strong>Note:</strong> Select any value from the dropdown select and see the result.</p>
</body>
</html>

Try with example

 

The focus() Method

The jQuery focus() method is a type of form event that attaches an event handler function to the selected elements (typically form controls and links) that is executed when it gains focus The example shown below will display a message when the text input receives focus.

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Executing a Function on Focus Event in jQuery</title>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<style>
    label{
        display: block;
        margin: 5px 0;
    }
    label span{
        display: none;
    }
</style>
<script>
$(document).ready(function(){
    $("input").focus(function(){
        $(this).next("span").show().fadeOut("slow");
    });
});
</script>
</head>
<body>
    <form>
        <label>Email: <input type="text"> <span>focus fire</span></label>
        <label>Password: <input type="password"> <span>focus fire</span></label>
        <label><input type="submit" value="Sign In"> <span>focus fire</span></label>
    </form>
    <p><strong>Note:</strong> Click on the form control or press the "Tab" key to set focus.</p>
</body>
</html>

Try with example

 

The blur() Method

The jQuery blur() method is also a type of form event, it attach an event handler function to the form elements such as <input>, <textarea>, <select> that is executed if it loses focus. The example shown below will display a message when the text input loses focus.

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Executing a Function on Blur Event in jQuery</title>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<style>
    label{
        display: block;
        margin: 5px 0;
    }
    label span{
        display: none;
    }
</style>
<script>
$(document).ready(function(){
    $("input").blur(function(){
        $(this).next("span").show().fadeOut("slow");
    });
});
</script>
</head>
<body>
    <form>
        <label>Email: <input type="text"> <span>blur fire</span></label>
        <label>Password: <input type="password"> <span>blur fire</span></label>
        <label><input type="submit" value="Sign In"> <span>blur fire</span></label>
    </form>
    <p><strong>Note:</strong> Click away from the form control or press the "Tab" key to remove focus.</p>
</body>
</html>

Try with example

 

The submit() Method

Lastly, the jQuery submit() method in jQuery attach an event handler function to the <form> elements that are executed only if the user is attempting to submit a form. The example shown below will display a message depending on the value entered if you try to submit the form.

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Executing a Function on Form Submit Event in jQuery</title>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<style>
    .error{
        color: red;
    }
</style>
<script>
$(document).ready(function(){
    $("form").submit(function(event){
        var regex = /^[a-zA-Z]+$/;
        var currentValue = $("#firstName").val();
        if(regex.test(currentValue) == false){
            $("#result").html('<p class="error">Not valid!</p>').show().fadeOut(1000);
            // Preventing form submission
            event.preventDefault();
        }
    });
});
</script>
</head>
<body>
    <p><strong>Note:</strong> If try to submit any invalid value. It will produce an error.</p>
    <form action="/jquery/example/action.php" method="post" id="users">
        <label for="firstName">First Name:</label>
        <input type="text" name="first-name" id="firstName">
        <input type="submit" value="Submit">
        <div id="result"></div>
    </form>    
</body>
</html>

Try with example

 

Document/Window Events

Events can be triggered in situations where the webpage Document Object Model (DOM) is ready or when the user resizes or scrolls the browser window, and so on. Below are some commonly used jQuery methods to handle such kinds of events.

The ready() Method

The method here is the jQuery ready() method, it specifies a function to be executed when the DOM is loaded fully.

The example shown below will replace the paragraph's text as soon as the DOM hierarchy has been fully constructed and ready for manipulation.

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Executing a Function on Ready Event in jQuery</title>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
$(document).ready(function(){
    $("p").text("The DOM is now loaded and can be manipulated.");
});
</script>
</head>
<body>
    <p>Not loaded yet.</p>
</body>
</html>

Try with example

 

The resize() Method

The resize() method in jQuery, is used to attach an event handler function to the window element that is executed if the size of the browser window changes.

The example shown below will display the current width and height of the browser window if you try to resize it by dragging its corners.

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Executing a Function on Resize Event in jQuery</title>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<style>
    p{
        padding: 20px;
        font: 20px sans-serif;
        background: #f0e68c;
    }
</style>
<script>
$(document).ready(function(){
    $(window).resize(function() {
        $(window).bind("resize", function(){ 
            $("p").text("Window width: " + $(window).width() + ", " + "Window height: " + $(window).height());
        });
    });
});
</script>
</head> 
<body>
    <p>Open the output in a new tab and resize the browser window by dragging the corners.</p>
</body>
</html>

Try with example

 

The scroll() Method

Lastly, the jQuery scroll() method is another method, it attaches an event handler function to the window or scrollable iframes and elements that are executed every time the element's scroll position changes.

The example shown below will display a message when you scroll the browser window.

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Executing a Function on Scroll Event in jQuery</title>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<style>
    p{
        width: 100%;
        padding: 50px 0;
        text-align: center;
        font: bold 34px sans-serif;
        background: #f0e68c;
        position: fixed;
        top: 50px;
        display: none;
    }
    .dummy-content{
        height: 600px;
        font: 34px sans-serif;
        text-align: center;
    }
</style>
<script>
$(document).ready(function(){
    $(window).scroll(function() {
        $("p").show().fadeOut("slow");
    });
});
</script> 
</head> 
<body>
    <p>Scroll Happened!</p>
    <div class="dummy-content">Scroll the viewport.</div>
    <div class="dummy-content">Scroll the viewport.</div>
    <div class="dummy-content">Scroll the viewport.</div>
    <div class="dummy-content">Scroll the viewport.</div>
    <div class="dummy-content">Scroll the viewport.</div>
</body>
</html>

Try with example

 

  • Prev
  • Next


-Advertisement-


DeveloperTutorial
[email protected] © 2022-2023 Developers Tutorial All rights reserved.

Follow Us

Facebook Twitter LinkedIn Printerest Reddit

Announcement

Its a big achivement for us, We make a partnership with TutorialWithExample.com for the better content of our users.

Still Need Help ?

Let us now about your issue and a Professional will reach you out.