Struggling to add a click event listener to a button using JavaScript object-oriented programming

I am encountering an issue with attaching a click event to a button with the class "nextPage". I have provided the code below for reference.

function myContent() {

}

myContent.prototype.clickNext = function() {
alert("clicked");    
};


var objMyContent = new myContent();

var el = document.getElementsByClassName('nextPage');
el.onclick=objMyContent.clickNext();

Your insights on where I may have gone wrong would be greatly appreciated. Thank you.

Answer №1

When setting a click handler, it's important to reference the function rather than execute it.

Instead of:

el.onclick = objMyContent.clickNext();

Use this:

el.onclick = objMyContent.clickNext;

The first example executes the clickNext function and assigns its return value to el.onclick.
The second method assigns a reference to the clickNext function to el.onclick, which is the correct approach.

Additionally, keep in mind that getElementsByClassName returns an HTMLCollection, which is essentially an array of HTML elements.
You will need to assign the click handler to each element within that collection:

for(var i = 0; i < el.length; i++){
    el[i].onclick = objMyContent.clickNext;
}

Answer №2

Loop through the array and set up the click event

let myData = new Data();

let elements = document.querySelectorAll('.nextPage'); for(let i=0;i<elements.length;i++) elements[i].onclick=myData.handleClick;

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

Completing numerous forms on a website

Every day, I find myself manually completing forms for a game and I am looking to automate this repetitive process. The only difference in each form is the 'nation' it is being sent to. To simplify, I want to create a list of nations and then loo ...

Having trouble reaching the unidentified function

There are two different scenarios where the 3rd party library (BrowserPrint.js) is used; FUNCTIONAL ENV - JS and jQuery with the 3rd party libraries included simply in the <head> section of the document and the main function being called in $(do ...

Managing authentication sessions in React

I have been working on a two-part application that combines React, Express, and Apollo for GraphQL. To handle authentication, I have been studying guides and tutorials, and I have made progress by utilizing JWT tokens and the Context API in React: When a ...

Encountering an error message stating "TypeError: Unable to access properties of undefined (reading 'map')" while attempting to retrieve data

Having a React frontend, I am encountering an issue when trying to fetch data from my Node.js backend. Despite having the API structured correctly, I am facing difficulties. const SingleProductPage = () => { const { productId } = useParams(); cons ...

What is the best way to combine an element retrieved from jQuery with a custom element or tag?

Imagine if I have an element selected using a jQuery selector, stored it in a variable, and now wish to append a custom element to it before performing any DOM operations on that variable. For instance, when I execute this: var placeHolder = $('.cla ...

Determine the class of the <body> element through the use of AJAX

I'm currently working with this AJAX code snippet: function ajax(){ if (!navigator.standalone) return; for (var i= document.links.length; i-->0;) { document.links[i].onclick= function() { if(this.getAttribute("class") == "noeffect") return; va ...

Avoiding do/while loop

Hey everyone, I'm currently working on an algorithm designed to remove concrete branches, similar to Depth-First Search (DSF), from a NodeTree. Basically, the algorithm checks if a specific node is acting as a parent for other nodes; if so, it grabs t ...

Encountering a CORS issue while trying to make requests to the Facebook Graph

I utilized the facebook live comments API to fetch real-time video comments. I was able to accomplish this successfully in my local environment. However, when I deployed the project with a domain name, I encountered a CORS error. Any suggestions on how to ...

Python/Selenium Issue: JS/AJAX Content Fails to Load when URL is Accessed

Currently, I am attempting to gather data from the following URL: The data that I am looking to extract is loaded dynamically, such as the Center Bore information. When accessing the link through a standard web browser, the content loads without any issue ...

Generate text in a random spot effortlessly

After doing some research on various development platforms, I stumbled upon this JSFiddle that seems to have a solution for my requirements. The only thing missing is the ability to input a specific word (without user input) and automate the process at fix ...

Having trouble with jquery AJAX get function experiencing undefined error when processing a valid JSON response

Hey team, I am relatively new to working with jQuery and I've run into a problem with a valid JSON response that's causing an unknown error. My project is a web-based C# MVC with a SQL Server backend database, using EF. Here is the code snippet ...

Javascript - The art of accessing an anonymous array

I'm trying to extract data from an API, but I've run into a snag. There's a list without a name attached to it, making it impossible for me to access the values inside. Here's a simplified example of what I mean: (Here is the JSON stru ...

Tips for incorporating real-time updating charts into your Yii project using Highcharts

Currently utilizing Yii along with Activehighcharts for displaying charts. http://www.yiiframework.com/extension/activehighcharts The controller code snippet is shown below: public function actionChartView(){ $dataProvider=new CActiveDataProv ...

Using Styled Components to achieve full width for input tag in relation to its parent

I am working with an input field that has a specific width set. My goal is to increase the width of this input field to 100% by selecting it from its parent component. Is there a way to achieve this without passing an explicit width prop in the styled c ...

a reactjs beforeunload event listener was added but not properly removed

I am working on a React component that looks like this: import React, { PropTypes, Component } from 'react' class MyComponent extends Component { componentDidMount() { window.addEventListener("beforeunload", function (event) { ...

What is the best way to achieve transparency in the alpha channels of my animated sprite?

Exploring the capabilities of ThreeJS through a small game project has been quite fascinating. Currently, I have an animated sprite that fits well in my scene using PlaneGeometry and a png texture in MeshBasicMaterial. However, the issue arises when the al ...

Using THREE.js to cast rays from a secondary camera onto the scene

I've been attempting to raycast the mouse from my camera in order to trigger hover and click events on meshes within my scene. The issue I'm facing is that my camera is currently a child object of another mesh (to facilitate easier camera moveme ...

Grunt is throwing an error message of "Cannot GET/", and unfortunately ModRewrite is not functioning properly

I've recently started using Grunt (just began last Friday). Whenever I run Grunt Serve, it displays a page with the message "cannot GET/" on it. I tried implementing the ModRewrite fix but the error persists. Any assistance would be highly appreciat ...

Execute the task from an external JavaScript file using npm

Utilizing node and npm as a task runner from gitbash cli has been successful for the most part. However, I am facing an issue where I am unable to call tasks in separate .js files from my package.json. Any assistance with the syntax would be greatly apprec ...

What is the best way to manipulate an object within HTML5 canvas by utilizing text input?

As someone just getting started with HTML5 canvas, I've figured out how to interact with users through keyboard and mouse inputs. But now I'm curious about how to check text input instead. For instance, if a user types "walk 20," I want an object ...