Is it possible for JavaScript to generate numerous functions using various other functions independently?

I currently have a substantial amount of code containing multiple event listeners on various HTML objects, all using the 'click' listener. However, I now realize that in addition to these click listeners, I also want mouseenter listeners on all of these objects. As I started writing out the code manually, it occurred to me that there must be a simpler way to achieve this. Although it may seem unclear, here is an overview of what I currently have:

object1.addEventListener("click", function(){
    if(condition1){
        function1();
    }
});

object2.addEventListener("click", function(){
    if(condition2){
        function2();
    }
});

and so forth

My goal is to retain these functions and add new ones with 'mouseenter' listeners. These new functions will perform the same action as the click listeners if the specific condition for each object is met. Here is the desired outcome:

object1.addEventListener("click", function(){
    if(condition1){
        function1();
    }
});

object1.addEventListener("mouseenter", function(){
    if(condition1){
        myAnimation();
    }
});

object2.addEventListener("click", function(){
    if(condition2){
        function2();
    }
});

object2.addEventListener("mouseenter", function(){
    if(condition2){
        myAnimation();
    }
});

and so forth

As mentioned, although I could manually write out all of this code, there are over 100 functions involved. It would be fantastic if there was a way for JavaScript to generate this automatically using a function.

EDIT:

My current project involves constructing a storyline (in VR using Aframe). There are numerous elements within the scene that can be clicked only if they align with the story's progression, hence the conditions in the listeners. What I am trying to accomplish now (which dawned on me belatedly) is to introduce an animation with the cursor whenever it hovers over the correct clickable element, providing users with a visual cue. Therefore, all of the 'mouseenter' listeners will share the same specific condition as their corresponding 'click' listeners. I understand this explanation might still sound vague, but unfortunately, I'm unsure how to elaborate further.

Answer №1

If you want to add event listeners to multiple HTML objects, you can do so by iterating over them using CSS selectors. Assuming each object has a class of 'object', you can use the following code snippet:

var objects = document.querySelectorAll('.object');
[].forEach.call(objects, function(object) {
  // Perform actions on each object
  object.addEventListener("click", ...
  object.addEventListener("mouseenter", ...
});

You can customize the behavior of the click function based on the properties of each 'object'.

If you are unable to use selectors, there are other methods to gather an array of objects for iteration and conditional event listener application.

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

Delightful Bootstrap Tabs with Dynamic Content via Ajax

My website has a lot of tabs designed with Bootstrap. I wanted to make them responsive, so I tried using a plugin called Bootstrap Tabcollapse from https://github.com/flatlogic/bootstrap-tabcollapse (you can see a demo here: http://tabcollapse.okendoken.co ...

Attention: React is unable to identify the `pId` property on a DOM element

After removing the span tag below, I noticed that there were no warnings displayed. <span onClick={onCommentClick} className={'comment'}> <AiOutlineComment className={"i"} size={"20px"}/> Co ...

Ensuring that an added row remains at the bottom of a table composed of rows generated dynamically by utilizing the .detach() method

I need to ensure that the "subtot" row is always appended as the last row in the table. When dynamically adding rows, the "subtot" row appears as the last row the first time, but does not stay at the bottom when more rows are added. Even though I want the ...

ReactJS Error: Attempting to access undefined property "updateNumber"

Just getting my feet wet with js and React, attempting to create a simple Sudoku program. Encountering an issue when adding UpdateNumberInCell={this.updateNumber} as a property in the Cell component - receiving the error: "Uncaught TypeError: Cannot read ...

I'm having trouble getting onClick to function properly in CodeIgniter

While attempting to utilize onClick in the PHP page as shown below: <a href="javascript:void(0);" onClick="deleteCourse('<?php echo $row->courseId;?>');" class="delete">Delete</a> And in the JavaScript page, the function is ...

storing negative floating point numbers in an array using regular expressions in JavaScript

I am currently working on creating a regular expression that can detect both positive and negative floating point numbers of any length. My goal is to store the captured values in an array as double data type. I have attempted the following pattern: input ...

Unit testing tips: the art of mocking a wrapper function

Unit testing is a new concept for me and I'm currently trying to learn how to stub a wrapper function in Sinon/Mocha. For example, if I have a function like: const user = await User.findOne({ email: email }); I've been successful in stubbing it ...

Trouble with loading images on hbs/nodejs

I'm currently working on a web application using NodeJs and express-handlebars. However, I am facing an issue with images not displaying correctly on the HTML page that is being rendered using handlebars. Here is the structure of my app: The root fo ...

AngularJS - Swipe to update

I've been trying to use the pull to refresh plugin for Angular JS, but unfortunately it's not working for me. Even though I can see the text, when I try to pull nothing happens! I followed all the steps outlined on this GitHub page: https://githu ...

Click on the hyperlinks one by one that trigger ajax events

There is a feature on the popular social media platform reddit.com where you can load more comments by clicking a link. I understand that comments may be hidden for performance reasons, but I would like to automatically expand all comments without having t ...

The compatibility between Node JS and Vue JS front-end seems to be glitchy and

I am currently developing a Node JS backend application and Vue JS front-end. In order to authenticate users, I need to implement sessions in the API. For my backend server, I am using the following components: express (4.18.2) express-session (1.17.3) c ...

What is the best way to include a JavaScript function in a dynamically generated div?

By clicking a button, I am able to dynamically generate a table row that contains a div element with the class "contents." $(document).on("click", ".vote", function() { // Removing selected row var rowLoc = this.parentNode.parentNode. ...

Sending data from an external input field to a form using AngularJS programmatically with element name

I am facing a challenge where I need to include an Input element in a Form, even though the Input is located outside of the form. While I have managed to add the input using form.$addControl(outerInput), it is not producing the desired outcome as shown in ...

Challenges with handling JSON data in JavaScript

I am currently attempting to retrieve and parse JSON data in order to display it on a blank HTML file. Unfortunately, I keep encountering an issue where if I retrieve and parse the data, I receive an error stating Uncaught TypeError: Cannot read property & ...

Recharge Backbone prior to a lockdown

I'm currently utilizing a script within Backbone in a Cordova application (Android) that causes the app to freeze for 5 seconds, and unfortunately I am unable to find an alternative method. Due to this issue, I would like to display a loading message ...

Unconventional way of assigning class properties in Typescript (Javascript): '?='

Recently, I came across the ?= assignment expression within a class property declaration. Can anyone provide some insight into what this means? I am familiar with the new Optional Chaining feature (object?.prop), but this particular syntax is unfamiliar t ...

How to print a specific div from an HTML page with custom dimensions

I am looking for a solution to print just a specific div from a website with dimensions of 3"x5". Despite setting up the print button, the entire page continues to print every time. Is there a way to hide all non-div content in print preview? CSS .wholeb ...

Explore the wonders of Jest and Playwright by heading over to youtube.com and discovering an exciting video!

As part of my job responsibilities, I have been tasked with automating tests for a web application that our team developed. Using Playwright and Jest, I am required to write automation scripts from scratch. To practice utilizing Playwright, I decided to cr ...

Discover the capability to choose dates from different months using the DatePicker component from @material-ui/pickers

I am currently in the midst of a React project that requires the use of the DatePicker component from @material-ui/pickers. The specific mandate is to show dates outside of the current month and allow users to select those days without needing to switch m ...

Using jQuery to restrict the occurrence of Ajax POST requests to once every 10 seconds

I created an interactive wizard using HTML that displays multiple panels. Users can navigate through the panels using a Next button and there is also a Finish button available. Whenever the user clicks on the next button, I have set up a click handler to s ...