Types of JavaScript Events and their creation and JavaScript Regular Expression creation and use cases with Example code
JavaScript Events and JavaScript RegExp
What are JavaScript Events?
JavaScript events are actions or occurrences that happen in the browser, which JavaScript can respond to. Examples include clicking a button, typing in a text field, or moving a mouse over an element.
When an event happens, JavaScript can execute code to handle it. These actions are called event handlers.
Types of Events
1. Mouse Events
click
: When the user clicks on an element.dblclick
: When the user double-clicks on an element.mousedown
: When the mouse button is pressed down.mouseup
: When the mouse button is released.mouseover
: When the mouse is moved over an element.mouseout
: When the mouse is moved out of an element.mousemove
: When the mouse is moved within an element.
2. Keyboard Events
keydown
: When a key is pressed down.keypress
(deprecated): When a key is pressed down and produces a character.keyup
: When a key is released.
3. Form Events
submit
: When a form is submitted.change
: When the value of an input, select, or textarea changes.focus
: When an element gains focus.blur
: When an element loses focus.
4. Window Events
load
: When the browser finishes loading a page.resize
: When the browser window is resized.scroll
: When the user scrolls the page.
5. Document Events
DOMContentLoaded
: When the HTML document is fully loaded and parsed.visibilitychange
: When the visibility of the document changes.
6. Other Events
drag
: When an element is dragged.drop
: When a dragged element is dropped.contextmenu
: When the user right-clicks to open a context menu.
Sponsor Key-Word
How to Handle Events in JavaScript
1. Using Inline HTML Attributes
Add the event directly in the HTML using attributes like onclick
, onmouseover
, etc.
<button onclick="alert('Button clicked!')">Click Me</button>
2. Using DOM Properties
Assign a function to the event property of an element.
const btn = document.getElementById('myButton');
btn.onclick = function () {
alert('Button clicked!');
};
3. Using addEventListener
This is the preferred method as it allows adding multiple event listeners to the same element and separating JavaScript from HTML.
const btn = document.getElementById('myButton');
btn.addEventListener('click', function () {
alert('Button clicked!');
});
Event Object
When an event occurs, an object called the event object is automatically passed to the event handler. This object contains details about the event.
Example:
document.addEventListener('click', function (event) {
console.log('Clicked element:', event.target); // Logs the element clicked.
console.log('Mouse X:', event.clientX); // X coordinate of the click.
console.log('Mouse Y:', event.clientY); // Y coordinate of the click.
});
Event Bubbling and Capturing
- Event Bubbling: Events propagate from the innermost element to the outermost element.
- Event Capturing: Events propagate from the outermost element to the innermost element.
You can control the propagation phase using addEventListener
:
element.addEventListener('click', handler, true); // Capturing phase
element.addEventListener('click', handler, false); // Bubbling phase
Stopping Propagation:
Use event.stopPropagation()
to stop the event from propagating further.
document.querySelector('.child').addEventListener('click', function (event) {
event.stopPropagation();
alert('Child clicked!');
});
Sponsor Key-Word
"This Content Sponsored by Buymote Shopping appBuyMote E-Shopping Application is One of the Online Shopping AppNow Available on Play Store & App Store (Buymote E-Shopping)Click Below Link and Install Application: https://buymote.shop/links/0f5993744a9213079a6b53e8Sponsor Content: #buymote #buymoteeshopping #buymoteonline #buymoteshopping #buymoteapplication"
Common Event Use Cases
1. Button Click
document.querySelector('#myButton').addEventListener('click', function () {
alert('Button was clicked!');
});
2. Form Validation
document.querySelector('#myForm').addEventListener('submit', function (event) {
const input = document.querySelector('#username').value;
if (!input) {
alert('Username is required!');
event.preventDefault(); // Prevent form submission
}
});
3. Change Event
document.querySelector('#dropdown').addEventListener('change', function (event) {
alert('Selected value: ' + event.target.value);
});
4. Mouseover Event
document.querySelector('#myDiv').addEventListener('mouseover', function () {
console.log('Mouse is over the div!');
});
Best Practices
- Use
addEventListener
: It is more versatile and avoids overwriting existing handlers. - Keep JavaScript and HTML Separate: Don’t use inline event handlers; write event handling logic in external scripts.
- Use
event.preventDefault
andstopPropagation
Wisely: Prevent default browser behavior only when necessary. - Delegate Events When Possible: Use event delegation for dynamic elements to improve performance.
Event Delegation Example:
Instead of adding listeners to every button inside a container:
document.querySelector('#container').addEventListener('click', function (event) {
if (event.target.tagName === 'BUTTON') {
alert('Button clicked: ' + event.target.textContent);
}
});
JavaScript Regular Expressions (RegExp)
Regular Expressions (RegExp) are patterns used to match character combinations in strings. In JavaScript, RegExp is a built-in object that provides powerful pattern-matching capabilities.
Creating a RegExp
There are two ways to create a RegExp in JavaScript:
-
Literal Syntax
const regex = /pattern/flags;
Example:
const regex = /hello/i; // "i" makes it case-insensitive
-
Constructor Syntax
const regex = new RegExp('pattern', 'flags');
Example:
const regex = new RegExp('hello', 'i'); // Same as above
RegExp Flags
Flags modify the behavior of the regular expression:
Flag | Description |
---|---|
g |
Global search (find all matches). |
i |
Case-insensitive search. |
m |
Multiline search. |
s |
Allows . to match newline. |
u |
Treat the pattern as Unicode. |
y |
Sticky search (match from lastIndex). |
Common Methods
-
test()
Checks if a pattern exists in a string. Returnstrue
orfalse
.const regex = /hello/; console.log(regex.test('hello world')); // true
-
exec()
Searches for a match and returns an array with details ornull
if no match is found.const regex = /hello/; const result = regex.exec('hello world'); console.log(result); // Output: ['hello']
-
String Methods with RegExp
match()
: Finds matches and returns them in an array ornull
.const str = 'hello hello'; console.log(str.match(/hello/g)); // ['hello', 'hello']
replace()
: Replaces matched text with a new value.const str = 'hello world'; console.log(str.replace(/hello/, 'hi')); // 'hi world'
search()
: Returns the index of the first match or-1
if not found.const str = 'hello world'; console.log(str.search(/world/)); // 6
split()
: Splits a string into an array based on a pattern.const str = 'a,b,c'; console.log(str.split(/,/)); // ['a', 'b', 'c']
Sponsor Key-Word
Basic Syntax
Pattern | Description |
---|---|
. |
Matches any single character except newline. |
\d |
Matches any digit (0-9). |
\D |
Matches any non-digit. |
\w |
Matches any word character (alphanumeric + underscore). |
\W |
Matches any non-word character. |
\s |
Matches any whitespace character. |
\S |
Matches any non-whitespace character. |
^ |
Matches the start of a string. |
$ |
Matches the end of a string. |
\b |
Matches a word boundary. |
\B |
Matches a non-word boundary. |
\ |
Escapes special characters. |
Quantifiers
Quantifier | Description |
---|---|
* |
Matches 0 or more occurrences. |
+ |
Matches 1 or more occurrences. |
? |
Matches 0 or 1 occurrence. |
{n} |
Matches exactly n occurrences. |
{n,} |
Matches n or more occurrences. |
{n,m} |
Matches between n and m occurrences. |
Example:
const regex = /\d{3}/;
console.log('1234'.match(regex)); // ['123']
Character Sets
Syntax | Description |
---|---|
[abc] |
Matches any character in the set a , b , or c . |
[^abc] |
Matches any character not in the set. |
[a-z] |
Matches any lowercase letter. |
[A-Z] |
Matches any uppercase letter. |
[0-9] |
Matches any digit. |
Example:
const regex = /[a-z]/g;
console.log('AbC123'.match(regex)); // ['b', 'C']
Grouping and Alternation
-
Grouping with Parentheses
()
- Groups multiple tokens into one unit.
const regex = /(abc)+/; console.log('abcabc'.match(regex)); // ['abcabc']
-
Alternation with Pipe
|
- Acts like an OR operator.
const regex = /cat|dog/; console.log('catdog'.match(regex)); // ['cat']
-
Positive Lookahead
(?=...)
- Matches if a pattern is followed by another pattern.
const regex = /\d(?=px)/; console.log('5px'.match(regex)); // ['5']
-
Negative Lookahead
(?!...)
- Matches if a pattern is NOT followed by another pattern.
const regex = /\d(?!px)/; console.log('5em'.match(regex)); // ['5']
-
Positive Lookbehind
(?<=...)
(ES2018+)- Matches if a pattern is preceded by another pattern.
const regex = /(?<=\$)\d+/; console.log('$123'.match(regex)); // ['123']
-
Negative Lookbehind
(?<!...)
(ES2018+)- Matches if a pattern is NOT preceded by another pattern.
const regex = /(?<!\$)\d+/; console.log('123'.match(regex)); // ['123']
Sponsor Key-Word
Greedy vs Lazy Matching
- Greedy: Matches as much as possible (default).
- Lazy: Matches as little as possible (add
?
).
Example:
const str = 'abcabc';
const greedy = /a.*c/; // Greedy
const lazy = /a.*?c/; // Lazy
console.log(str.match(greedy)); // ['abcabc']
console.log(str.match(lazy)); // ['abc']
Examples
-
Validate Email
const regex = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,6}$/; console.log(regex.test('test@example.com')); // true
-
Extract Numbers
const regex = /\d+/g; console.log('Order #1234'.match(regex)); // ['1234']
-
Replace Words
const str = 'JavaScript is awesome!'; console.log(str.replace(/awesome/, 'great')); // 'JavaScript is great!'
Best Practices
-
Escape Special Characters: Use
\
for characters like.
,*
,+
, etc.const regex = /\./; // Matches a literal dot
-
Test with Tools: Use online regex testers like regex101.
-
Optimize Patterns: Use specific patterns instead of overly generic ones to improve performance.
Comments
Post a Comment