Attach a click event listener to content loaded through AJAX using only JavaScript, without relying on jQuery

I'm curious about how to attach a click event to an element that will be added later through an ajax call. I know jQuery can handle this like so:

$(document).on('click', '.ajax-loaded-element' function(){});

However, I'm not currently using jQuery. My approach is similar to the one below, but it may fail if the same file is called twice (not sure if necessary, but want to cover all bases).

bindAjaxBtn: function(selector, fnName) {
    let isBinded = false;
    document.addEventListener('click', function(e) {
        const btn = document.querySelector(selector);
        if(btn === e.target) {
            if(!isBinded) {
                btn.addEventListener('click', function() {
                    fnName();
                    isBinded = true;
                });
                btn.click();
            }
        }
    });
},

Any assistance on this matter would be greatly appreciated. :)

Answer №1

Here is a easy solution for you to try out. Give it a shot and see how helpful it can be.

document.getElementById('submitBtn').setAttribute('onclick', 'myFunction()');
function myFunction(){
  alert('Submission Successful');
}
<button id="submitBtn">Submit Now</button>

Wishing you success in your coding endeavors!

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

JavaScript code for Tree not functioning correctly on Internet Explorer

Seeking assistance to fix a bug in my JavaScript program. The code works perfectly on Google Chrome and Firefox, however it encounters an error in Internet Explorer 8 as indicated below. Any suggestions on how to resolve this issue would be greatly appreci ...

When utilizing npm install buefy and npm install font-awesome, there may be an unnecessary display of [email protected] and [email protected] extraneous errors

After installing buefy and font-awesome, I noticed that it is marked as extraneous and the folder appears with an arrow icon but is empty. How can this issue be resolved? For example: +-- <a href="/cdn-cgi/l/email-protection" class="__cf_email__" ...

Instead of modifying the selected class, jQuery generates inline styles

Utilizing the following code to dynamically create a class: $("head").append('<style type="text/css"></style>'); var newStyleElement = $("head").children(':last'); newStyleElement.html('.move{transform: translateX(1 ...

Implement RJS code within the onclick function of a button

I have experience adding JavaScript code to the onclick event of a button, for example: "this.disabled=true,this.form.submit();" %> Now I am curious if I can utilize rjs in the onclick. My goal is to render out a partial using it. Thank you ...

A guide on implementing the intl-tel-input plugin within an Angular 2+ project

Component : ng2-tel-input, Framework : Angular 4, JavaScript library : intl-tel-input Upon completing the installation with npm i ng2-tel-input I stumbled upon a note in the node_modules\intl-tel-input\src\js\intlTelInput.js file that ...

The printing feature in javascript does not include the ability to print values from textboxes

I'm encountering an issue when trying to print an HTML table with textboxes that should get their values from another function. However, the preview is not showing anything. Below is the complete code: <html> <head></head> < ...

To display the user's input value in the console log upon clicking

Having trouble displaying the user's input value in the console when the button is clicked. function submit(){ var userInput = document.getElementById('input_text').value; console.log(userInput); } ...

Checking for the existence of data in a MySQL table using Node.js resulted in an error message: "TypeError: res.send is

I am currently attempting to verify the existence of data in a mysql table. Upon doing so, I encountered an error indicating TypeError: res.send is not a function. The mysql table contains ample data with three columns, each specified as varchar(45), alon ...

Altering the input field's content in response to a button click through JavaScript's addEventListener function

I am struggling to get the input text from a form field to change when a button is clicked using JavaScript. I can't seem to figure out why it isn't working correctly. Any assistance would be greatly appreciated. <!doctype html> & ...

What is the correct way to define an abstract method within a class to ensure that an IDE detects and notifies if the abstract method is not implemented

Is there a way to properly define an abstract method in an abstract class and have the IDE notify us if we forget to implement it? I attempted the following approach, but it did not work: export abstract class MyAbstractClass { /** * @abstract ...

Button component in React remains visible until interacted with

https://i.stack.imgur.com/gTKzT.png I'm dealing with a sign out component in my app that requires me to click on it specifically to unselect any part of the application. This is implemented using React Material UI. <MenuItem onClick={e => this ...

JQuery's .each method is executed prior to making an Ajax request

I am currently working on a JavaScript (jQuery) function that loops through input elements in a form, builds an array to convert into a JSON string, and then sends it to an AJAX endpoint. However, I am facing an issue where the loop runs after the AJAX cal ...

What is the significance of the dollar sign prefix ($) in Vue.js?

Can you explain the significance of the dollar symbol prefix used before property names in Vue.js? For instance, consider this code snippet: this.$emit('clicked', 'demo') ...

Can you explain the process of obtaining getServerSideProps results for my IndexPage?

Having trouble with the getServerSideProps function. I'm a beginner and struggling to figure out why it's not running properly. Spent hours trying to fix it, but still getting undefined in the IndexPage console.log(props.data) export default fun ...

What do we need to ensure that the ajax server response is executed as intended in the jQuery ajax post function?

The jQuery script provided here returns the following string: '#prayer_date'.html("03/19/1968"); However, it remains unexecuted because the function does not interact with the data variable. To make sure the above result is executed within the ...

Tips for Showing a Portion of an Object in React JS

Need help displaying subitems of an object. I can display the main item but struggling with subitems. Here's the attached image for reference: I'm having trouble displaying the comments section in the object. I'm using Django API and trying ...

Looking for precise information within a Vue b-table by fetching data from an Axios API

My b-table is filled with data from an API hit through Swagger UI, and since there's a large amount of data, I need the search button at the center top of the page to work properly when inputting store code or branch. https://i.stack.imgur.com/l90Zx.p ...

React JS component experiencing issues with Material UI modal functionality

Attempting to reproduce the material ui modal example has proven to be a challenge for me. Initially, I encountered an error stating "Cannot read property 'setState' of undefined" which I managed to resolve. However, even after resolving this iss ...

What is the best way to transfer a JavaScript object to a VueJS component?

Even though it may seem like a basic question, I'm having trouble figuring out how to accomplish this in VueJS Here's the code I have in HTML: <script> var config = {'cols':4,'color':'red'} </script> ...

In terms of function efficiency, what yields better results: using conditional execution or employing conditional exit?

Feedback is welcomed on the efficiency of the following JavaScript/TypeScript solutions: function whatever(param) { if (param === x) { doStuff(); } } or function whatever(param) { if (param !== x) { return false; } doStuff(); } The se ...