Implementing dynamic AJAX functionality for dynamically generated elements using vanilla JavaScript

Currently, I am working on developing a movie information application using ajax. However, I have encountered a challenging issue that I am struggling to resolve. After creating an ajax request, I proceed to dynamically generate content and incorporate it into the webpage. Here is an example of my dynamically created content:

output +=
  `<div class="box">
    <div class="box-image">
     <img src="${val.Poster}" alt="${val.Title}">
    </div>
    <div class="box-body">
        <h4 class="box-title">${val.Title}</h4>
        <p class="year">${val.Year}</p>
        <a href="#" class="modal-trigger" id="modalTrigger">Modal Trigger</a>
    </div>
  </div>`.

My challenge lies in implementing a function for the anchor tag in order to open a modal. Additionally , I am searching for a way to prevent its default behavior within this function.

Answer №1

To create an event listener for clicks on the body document and target a specific element, follow these steps:

$("body").on('click', "a.modal-trigger", function(e) {
    e.preventDefault();

$("#ajax").click(function() {
  $("#output").append(
    $("<a/>")
    .attr("id", "modalTrigger")
    .attr("class", "modal-trigger")
    .attr("href", "#")
    .text("modal")
  );
});

$("body").on('click', "a.modal-trigger", function(e) {
  e.preventDefault();
  console.log('modal!');
  $("#output").append("modal!");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<body>
  <button id="ajax">
Make Ajax Request
</button>

  <div id="output">

  </div>
</body>

console.log('modal!'); });

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

Adding text chips to a text field in Vuetify - A simple guide

I have successfully integrated a text field with vuetify and now I am looking to incorporate chips into it. Currently, chips are only added if the entered text matches a specific pattern (such as starting with '{' and ending with '}'). ...

Are there any specific events in PrimeNg's p-calendar that trigger when the time is changed?

In my project, I utilized PrimeNg v5.2.7 for the From Date and To Date fields. I implemented minDate validation on the To Date field. However, I encountered a scenario where if I select 30th Jan 2021 as the From Date and only adjust the time in the To Da ...

Find the JavaScript code that selects the previous value chosen

When working with a select in React, I am facing an issue where the console.log is returning the last value selected instead of the current one. For instance, if I select 4 followed by 3 and then 5, the code will display 1 (default value), then 4, and fin ...

Ensure the md-sidenav remains open by default

I have set up a md-sidenav in my project. I would like the sidenav to be open by default, while still maintaining an overlay effect on the page and allowing users to close the sidenav, thus avoiding the use of md-is-locked-open. Any suggestions on how I ca ...

Arranging an array of objects in Angular based on the value inside each object

How can I retrieve objects by filtering the key value within the object? In the example below, I need to extract data only with session_id:23. data = [{ name: "First Name", session_id : "23", login: "date" }, { name: "Second Name", ...

Refine your search with a JSON object description in expressJS and UnderscoreJS

[ { "id": 1, "description": "Empty the garbage bin", "completed": false }, { "id": 2, "description": "Dine out for dinner", "completed": false }, { "id": 3, "description": "Exercise at the fitness center", "com ...

How can I alter the center point of an Object3D in Three.js?

I have a scenario where I am adding meshes dynamically to an Object3D. I'm curious if there is a way to obtain the center of the object so that I can apply rotations and translations evenly across the entire mesh, rather than having them centered on o ...

The component encountered an error because the element type provided was not valid

I've encountered an error that has me stumped: https://i.sstatic.net/glSvr.png I've been trying to locate the HeaderSegment, but it seems to be missing from my project. I've checked for any imports, such as: import HeaderSegment from &apos ...

The term "this" in the global scope versus within a function in the Node.js environment

console.log(this) // {} function abc(){ console.log(this) } abc() // global The concept of this can vary between the global space and inside a function in Node.js. console.log(this === module.exports) // true function abc(){ ...

Attempting to send data as arguments in an axios request

I have been working on setting up a forum and I want to implement a feature where clicking on a post title will take the user to a page I've already created that displays the title and body of the post. I utilized MUI for building the page, but I enco ...

Maintain the vertexShader's movement even when the mesh is rotating

Currently, I am adjusting the vertices of my cube along the y-axis. Although this method works well when simply moving the cube, issues arise when I begin rotating it. The movements continue to follow the global y-axis even during rotation. Is there a way ...

Experiencing difficulties integrating relational data with Angular and MongoDB

I have a view where I display 'Transporters'. Each Transporter has multiple 'Deliveries', so I want to associate Deliveries with the corresponding Transporters. My tech stack includes express, mongoose, and angular.js. Here are my mode ...

"webpack" compared to "webpack --watch" produces varying results in terms of output

My project is built on top of this setup: https://www.typescriptlang.org/docs/handbook/react-&-webpack.html Running webpack compiles a bundle that functions correctly in the browser. However, running webpack --watch to recompile on file changes resul ...

The elements being parsed are appearing as undefined

Currently, I am attempting to analyze this JSON structure: { "customers": [ { "name":"joe" , "cars":[ {"name":"honda","visits":[ {"date":"01/30/14","Id":"201"}, {"date":"01/30/14","Id":"201"}, {"date":"02/12/14","Id":"109"} ...

Upon employing the setTimeout method, the element with the id "sign-in-block" will have its display style set to "none" after a delay of 1000 milliseconds

I incorporated the setTimeout() function to make the HTML component appear for 1 second upon pageload. However, I would prefer this component not to load at all. Should I set the delay in the setTimeout() function to 0ms? Alternatively, is there another ...

In order to activate parallel building capabilities, be sure to include the '/m' switch

I tried to launch the sample code from https://github.com/Gottox/node-webterm, but encountered an error message when running the npm install command. Upon building the projects in this solution, I received several errors related to missing files and und ...

Instructions on converting Dart to JavaScript for a non-web platform

I am interested in compiling Dart to JS for a non-web target, such as fermyon/js or node How can I compile Dart to JS for a non-web target? Update: I have been informed that it is possible, and although I couldn't find specific documentation, there ...

You must include an argument for 'model' in the Angular service

My service requires an id parameter for a route, but when I tried to access the route with the id, I encountered the error mentioned above. Any suggestions on how to resolve this issue? https://i.sstatic.net/FEcqo.png #request const apiBaseUrl = `${envir ...

Missing index in the GET variable

I have a div with the class .excelDL. When this div is clicked, a form is submitted using AJAX without refreshing the page, and it works perfectly fine. However, the issue I am facing is that I need to check if $_GET['excel'] has been set to one ...

Is it possible to save an HTML5 Canvas screenshot directly onto the page?

After browsing numerous tutorials on saving HTML5 canvas screenshots as images and opening them in new tabs, I'm wondering if there's a way to display the captured screenshot in a pre-set div on the SAME WEBPAGE. Any suggestions or solutions woul ...