-
Couldn't load subscription status.
- Fork 0
jQuery
The JsBaseClass library seamlessly integrates with jQuery, one of the most popular JavaScript libraries for DOM manipulation, event handling, and AJAX requests. This page provides practical examples to help you use jQuery effectively within a class that extends JsBaseClass. Whether you're handling button clicks, form submissions, or dynamic DOM updates, this guide has you covered.
- Simplified DOM Manipulation: jQuery makes it easy to select and manipulate DOM elements.
-
Event Handling: Easily bind events like
click,submit, and more. - AJAX Support: Simplify AJAX requests with jQuery's intuitive API.
- Cross-Browser Compatibility: jQuery handles browser inconsistencies, ensuring your code works everywhere.
Here’s how to handle a button click using jQuery within a class that extends JsBaseClass:
<button id="myButton">Click Me</button>class ClassJQuery extends JsBaseClass {
async onDomContentLoaded() {
// Bind a click event to the button
$('#myButton').on('click', () => this.handleButtonClick());
}
handleButtonClick() {
this.console.log('Button clicked!');
alert('Button clicked!');
}
}
// Initialize the example
window.objJQuery = new ClassJQuery();
objJQuery.init();Here’s how to handle form submissions using jQuery:
<form id="myForm">
<label for="name">Name:</label>
<input type="text" id="name" name="name" required>
<label for="email">Email:</label>
<input type="email" id="email" name="email" required>
<button type="submit">Submit</button>
</form>class ClassJQuery extends JsBaseClass {
async onDomContentLoaded() {
// Bind a submit event to the form
$('#myForm').on('submit', (event) => this.handleFormSubmit(event));
}
handleFormSubmit(event) {
event.preventDefault(); // Prevent the default form submission
// Retrieve form data
const formData = {
name: $('#name').val(),
email: $('#email').val(),
};
this.console.log('Form submitted with data:', formData);
alert(`Form submitted!\nName: ${formData.name}\nEmail: ${formData.email}`);
}
}
// Initialize the example
window.objJQuery = new ClassJQuery();
objJQuery.init();Here’s how to retrieve custom data attributes from elements and handle their click events:
<div class="product" data-product-id="101" data-product-name="Laptop">
<p>Product: Laptop</p>
<button class="viewDetails">View Details</button>
</div>
<div class="product" data-product-id="102" data-product-name="Smartphone">
<p>Product: Smartphone</p>
<button class="viewDetails">View Details</button>
</div>class ClassJQuery extends JsBaseClass {
async onDomContentLoaded() {
// Bind a click event to buttons with the class "viewDetails"
$('.viewDetails').on('click', (event) => this.handleProductClick(event));
}
handleProductClick(event) {
// Get the closest parent element with the class "product"
const productElement = $(event.target).closest('.product');
// Retrieve custom data attributes
const productId = productElement.data('product-id');
const productName = productElement.data('product-name');
// Display the product details
this.console.log(`Product ID: ${productId}, Product Name: ${productName}`);
alert(`Product Details:\nID: ${productId}\nName: ${productName}`);
}
}
// Initialize the example
window.objJQuery = new ClassJQuery();
objJQuery.init();Here’s how to dynamically update the DOM using jQuery:
<div id="content">
<p>Initial content</p>
</div>
<button id="updateContent">Update Content</button>class ClassJQuery extends JsBaseClass {
async onDomContentLoaded() {
// Bind a click event to the button
$('#updateContent').on('click', () => this.updateContent());
}
updateContent() {
// Update the content of the div
$('#content').html('<p>New content updated dynamically!</p>');
this.console.log('Content updated.');
}
}
// Initialize the example
window.objJQuery = new ClassJQuery();
objJQuery.init();Here’s how to make an AJAX request using jQuery:
class ClassJQuery extends JsBaseClass {
async onDomContentLoaded() {
// Make an AJAX request
await this.fetchData();
}
async fetchData() {
try {
this.console.info('Fetching data...');
const response = await $.ajax({
url: 'https://jsonplaceholder.typicode.com/todos/1',
method: 'GET',
});
this.console.log('Data fetched:', response);
} catch (error) {
this.console.error('Error fetching data:', error);
}
}
}
// Initialize the example
window.objJQuery = new ClassJQuery();
objJQuery.init();Here’s how to toggle the visibility of an element using jQuery:
<button id="toggleButton">Toggle Visibility</button>
<div id="toggleContent" style="display: none;">
<p>This content is hidden by default.</p>
</div>class ClassJQuery extends JsBaseClass {
async onDomContentLoaded() {
// Bind a click event to the button
$('#toggleButton').on('click', () => this.toggleVisibility());
}
toggleVisibility() {
// Toggle the visibility of the content
$('#toggleContent').toggle();
this.console.log('Visibility toggled.');
}
}
// Initialize the example
window.objJQuery = new ClassJQuery();
objJQuery.init();Here’s how to animate an element using jQuery:
<div id="animatedBox" style="width: 100px; height: 100px; background: red;"></div>
<button id="animateButton">Animate Box</button>class ClassJQuery extends JsBaseClass {
async onDomContentLoaded() {
// Bind a click event to the button
$('#animateButton').on('click', () => this.animateBox());
}
animateBox() {
// Animate the box
$('#animatedBox').animate({ width: '200px', height: '200px' }, 1000);
this.console.log('Box animated.');
}
}
// Initialize the example
window.objJQuery = new ClassJQuery();
objJQuery.init();Here’s how to use event delegation to handle events for dynamically added elements:
<ul id="myList">
<li>Item 1</li>
<li>Item 2</li>
</ul>
<button id="addItem">Add Item</button>class ClassJQuery extends JsBaseClass {
async onDomContentLoaded() {
// Bind a click event to the list using event delegation
$('#myList').on('click', 'li', (event) => this.handleItemClick(event));
// Bind a click event to the "Add Item" button
$('#addItem').on('click', () => this.addItem());
}
handleItemClick(event) {
this.console.log('Item clicked:', $(event.target).text());
}
addItem() {
// Add a new item to the list
const itemCount = $('#myList li').length + 1;
$('#myList').append(`<li>Item ${itemCount}</li>`);
this.console.log('Item added.');
}
}
// Initialize the example
window.objJQuery = new ClassJQuery();
objJQuery.init();- Event Delegation: Use event delegation for dynamically added elements to avoid binding multiple event listeners.
- Chaining: Take advantage of jQuery's chaining capabilities for cleaner code.
- AJAX Error Handling: Always handle errors in AJAX requests to provide a better user experience.
- Performance: Minimize DOM manipulations and use efficient selectors to improve performance.
With these examples, you can effectively use jQuery within JsBaseClass to handle DOM manipulation, events, and AJAX requests. Whether you're building simple interactions or complex dynamic UIs, this integration makes your code cleaner and more maintainable. 🚀