Tips for accessing and passing the clicked element as "THIS" within an addEventListener

Currently in the process of developing a custom JS library similar to jQuery, I've encountered a stumbling block.

I have successfully created an event delegation function intended for a simple click event.

While working within this prototype section, I'm attempting to execute some logic (such as adding a class), but I'm facing issues with the 'this' keyword. Specifically, I need to be able to add a class to the clicked element.

Constructor.prototype.on = function (eventName , elementSelector, callback) {
    document.addEventListener(eventName, function(e) {
        for (var target = e.target; target && target != this; target = target.parentNode) {
            if (target.matches(elementSelector)) {
                callback.call(target, e);
                break;
            }
        }
    }, false);
};

// X represents the plugin
X('body').on('click','.someClass',function(){
     X(this).addClass('clicked');// unfortunately, this won't work 
});

Answer №1

To enhance your code, consider updating your Constructor function to accept a DOM element as an argument rather than just a selector. This modification will enable you to utilize X(this) to instantiate a class instance containing the specified element.

var Constructor = function(element) {
  if (!element) return;
  if (typeof element != string) {
    this.nodes = [element];
  } else if (element === 'document') {
    this.nodes = [document];
  } else if (element === 'window') {
    this.nodes = [window];
  } else {
    this.nodes = document.querySelectorAll(element);
  }
  this.length = this.nodes.length;
};

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The browser is unable to access localhost:3000

Backend: Utilizing an Express server, created with the npx create-express-api command Frontend: Using Next.js, set up with npx create-react-app in the frontend directory Having executed these commands in the root folder, I attempted to run npm start xxx ...

Why won't my setTimeout function work?

I'm having trouble working with the setTimeout function, as it doesn't seem to be functioning properly. First and foremost, Player.prototype.playByUrl = function (url) { this.object.data = url; return this.play(); } The co ...

What is the most effective way to remove or modify an element in an array when a button is clicked?

I've hit a roadblock because I'm uncertain about how to access and remove elements stored within an array, especially if the user wants to delete from the middle. In this scenario, using pop won't suffice as it removes from the end without c ...

Executing a Select Change in a React Application using CasperJS

Has anyone else encountered difficulties with this issue? I have a basic React page set up, with a simple component that renders a select element and triggers a callback function when the value changes. Here is the basic structure of the component: const ...

Is there a simple way to display all the data from a JSON object even if the contents are unknown beforehand?

Greetings! I am Pearson's dictionary api. Here is a glimpse of what I receive from an api call: { "status": 200, "offset": 0, "limit": 10, "count": 10, "total": 135, "url": "/v2/dictionaries/entries?headword=dog", "results": [ { ...

How do I transfer a PDF received from a third-party to my client using a REST API on the backend?

After receiving a PDF from a third party, I stored the file on S3. Upon checking the file on S3, I was able to view the PDF without any issues. However, when sending the PDF to the client and verifying it using Postman, an empty PDF is displayed. Below is ...

Discover the nodes with the highest connections in a D3 Force Graph

As I explore the functionalities of a D3 Force Directed Graph with zoom and pan features, I encounter an issue due to my limited knowledge of d3.js. Is there a way to estimate the number of links for each node in this scenario? I am currently at a loss on ...

Select value not updating as expected

I have a select box that is linked to a switch statement in PHP, which changes the order of the results returned from the database based on the value selected in the select box. However, I am facing an issue with my JavaScript not working correctly. Can an ...

Using Styled components and react-router-dom v6 to emphasize the active navigation link upon clicking

I'm just starting out with react and I am trying to figure out how to keep my hover style active while the current page is open. I think I need to set a condition but I am not sure how. const StyledLi = styled.li` `list-style: none; displa ...

Error: The combination of 0 and .... is invalid and cannot be used as a function

I am currently in the process of developing a next.js application using Material-ui. I have been attempting to integrate material-ui into my project. Following guidance from the official GitHub page, I have copied the _app.js , _document.js , theme.js fil ...

Storing the information received from an API as an HTML element

My HTML file contains JavaScript, along with a URL that displays data retrieved from an AWS lambda API call via AWS API Gateway. The page initially appears blank and the data is structured like this: [ {"user": "bob", "groups": ["bobsGroup"], "policies": ...

Encounter an error while attempting to store and retrieve an array of JavaScript objects in localStorage and parsing the data

I'm dealing with an array of JavaScript objects, like this: var objectList = [{phone: true},{name: 'room'}]. My goal is to store this array in localStorage, retrieve it later, and continue working with the objects it contains. Here is what ...

Uploading files to AWS-S3 using Angular $http PUT method: A step-by-step guide

When attempting to upload a file to AWS-S3 using $http.put(url, file) in my Angular application, I encounter an issue. The HTTP-403 Forbidden error message indicates that the signature calculated by S3 differs from the one I provided. However, if I use c ...

Determine whether the click occurs inside or outside of a bar on a ChartJS graph

I'm currently working with a bar graph using chartJS. I'm trying to figure out how to detect where the user clicked - whether it was inside or outside of the bar region in chartJS. const waterFChart = new Chart(canvasRef.current, { plugins: [ ...

What's preventing me from utilizing Leaflet Map on Next.js despite attempting Dynamic Import?

When using Leaflet, it requires the global window object which is not available on SSR (Server-Side Rendering) and can cause an error stating "window is not defined". I have tried extensively to find a solution, and the only method I found was to use dyna ...

Tips for sending an API request from a local Ionic server to a separate local Express server

I currently have two applications running on my local machine: an ionic2 app running on http://localhost:8041 and an express app running on http://localhost:8000. Using Angular 2 observables, I am encountering an issue when making API calls with absolute p ...

What is the most efficient method for transferring session data from a Client component to a server component in NEXT.js version 13 and beyond?

Currently, I am working on a web application that requires passing session?.user?.email from the useSession() function in next-auth/react to a server-side component. This server-side component will then execute a fetch request to /api/users/email/ to deter ...

Implementing an Asynchronous Limited Queue in JavaScript/TypeScript with async/await

Trying to grasp the concept of async/await, I am faced with the following code snippet: class AsyncQueue<T> { queue = Array<T>() maxSize = 1 async enqueue(x: T) { if (this.queue.length > this.maxSize) { // B ...

Using ngFor and ngModel: What is the best way to add values to the beginning of the array I am looping through?

I am facing an issue with my array of elements in which users can edit, add, and delete complete array elements. Everything works smoothly until I try to add a value to the beginning of the array using the unshift method. Below is a test that showcases th ...

Ways to dynamically link a JSON response object to an entity?

In my ng2 implementation, I have a user.service.ts file that calls a REST service and returns JSON data. The code snippet below shows how the getUser function retrieves the user information: getUser(id: number): Promise<User> { return this.http. ...