Skip to content
Marcelo XP edited this page Jan 17, 2025 · 3 revisions

jQuery Integration with JsBaseClass

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.


Why Use jQuery with JsBaseClass?

  • 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.

Basic Example: Button Click Event

Here’s how to handle a button click using jQuery within a class that extends JsBaseClass:

HTML

<button id="myButton">Click Me</button>

JavaScript

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();

Handling Form Submissions

Here’s how to handle form submissions using jQuery:

HTML

<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>

JavaScript

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();

Get Custom Data from Element

Here’s how to retrieve custom data attributes from elements and handle their click events:

HTML

<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>

JavaScript

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();

Dynamic DOM Updates

Here’s how to dynamically update the DOM using jQuery:

HTML

<div id="content">
    <p>Initial content</p>
</div>
<button id="updateContent">Update Content</button>

JavaScript

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();

AJAX Requests with jQuery

Here’s how to make an AJAX request using jQuery:

JavaScript

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();

Advanced Example: Toggle Visibility

Here’s how to toggle the visibility of an element using jQuery:

HTML

<button id="toggleButton">Toggle Visibility</button>
<div id="toggleContent" style="display: none;">
    <p>This content is hidden by default.</p>
</div>

JavaScript

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();

Additional Examples

1. Animations with jQuery

Here’s how to animate an element using jQuery:

HTML

<div id="animatedBox" style="width: 100px; height: 100px; background: red;"></div>
<button id="animateButton">Animate Box</button>

JavaScript

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();

2. Event Delegation

Here’s how to use event delegation to handle events for dynamically added elements:

HTML

<ul id="myList">
    <li>Item 1</li>
    <li>Item 2</li>
</ul>
<button id="addItem">Add Item</button>

JavaScript

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();

Best Practices

  1. Event Delegation: Use event delegation for dynamically added elements to avoid binding multiple event listeners.
  2. Chaining: Take advantage of jQuery's chaining capabilities for cleaner code.
  3. AJAX Error Handling: Always handle errors in AJAX requests to provide a better user experience.
  4. 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. 🚀

Clone this wiki locally