Issue with invoking a function from dynamically generated HTML code

I am attempting to modify the HTML code using JavaScript and running into an issue where the function is not being called when applied to created "div" elements.

Even though the generated 'html' includes the class "screen" after invoking the function, the newly created 'div's do not seem to support it.

var i;
var clear = 2;
$("#container").click(function() {
  var clickid = $(this).attr('id');
  var left = document.getElementById(clickid).offsetLeft;
  var top = document.getElementById(clickid).offsetTop;
  var height = document.getElementById(clickid).offsetHeight;
  var width = document.getElementById(clickid).offsetWidth;
  var x = document.getElementById(clickid).value;
  orient = prompt("vertical or horizontal ?");
  numdiv = prompt("How many divisions should be created ?");
  var divsper = [];
  var html = "";
  for (i = 0; i < numdiv; i++) {
    per = prompt("Percentage of " + (i + 1) + "th division ?");
    divsper.push(per);
  }
  if (orient == "vertical") {
    for (i = 0; i < numdiv; i++) {
      l = Math.floor(left + ((i * divsper[i] * width) / 100));
      w = Math.floor((divsper[i] * width) / 100);
      html = html + "<div id=" + clickid + " class=\"screen\" style=\"float:left; top:" + (top) + "px; left:" + (l) + "px; height:" + (height - clear) + "px; width:" + (w - clear) + "px; border:1px solid black;\"></div>"
    }
    document.getElementById(clickid).outerHTML = html;
    //document.getElementById(clickid).unwrap();
  }

});
* {
  padding: 0px;
  margin: 0px;
}

body {}

#container {
  background-color: pink;
  top=0%;
  left=0%;
  height: 100vh;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="container" class="screen">
</div>

Answer №1

Update the line '$("#container").click(function() {' to '$("html").on('click', '[id*=container]', function() {' and see the magic happen.

var i;
var clear = 2;
$("html").on('click', '[id*=container]', function() {
  var clickid = $(this).attr('id');
  var left = this.offsetLeft;
  var top = this.offsetTop;
  var height = this.offsetHeight;
  var width = this.offsetWidth;
  var x = this.value;
  orient = prompt("vertical or horizontal ?");
  numdiv = prompt("How many divisions should be created ?");
  var divsper = [];
  var html = "";
  for (i = 0; i < numdiv; i++) {
    per = prompt("Percentage of " + (i + 1) + "th division ?");
    divsper.push(per);
  }
  if (orient == "vertical") {
    for (i = 0; i < numdiv; i++) {
      l = Math.floor(left + ((i * divsper[i] * width) / 100));
      w = Math.floor((divsper[i] * width) / 100);
      html = html + "<div id=" + clickid + (i + 1) + " class=\"screen\" style=\"float:left; top:" + (top) + "px; left:" + (l) + "px; height:" + (height - clear) + "px; width:" + (w - clear) + "px; border:1px solid black;\"></div>"
    }
    this.outerHTML = html;
    //this.unwrap();
  }

});
* {
  padding: 0px;
  margin: 0px;
}

body {}

#container {
  background-color: pink;
  top=0%;
  left=0%;
  height: 100vh;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="container" class="screen">
</div>

Answer №2

Consider utilizing $('#container').on('click') as an alternative approach. The handling of html events that are generated dynamically can vary slightly.

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 Twitch API is providing inaccurate channel information

Currently facing an issue while working with the Twitch API. When making a GET request to /api.twitch.tv/helix/search/channels?query=[STREAMER_NAME], it seems to be returning the wrong streamer/user. For instance: /api.twitch.tv/helix/search/channels?quer ...

CSS for aligning div logo in the center

I am currently working on optimizing the mobile version of our website and have encountered a roadblock while trying to center the logo in the header section. I have attempted using the flex property along with justify-content:center;. Here is the snippet ...

Error: JSON parsing encountered an issue with token "o" at position 1 while making an ajax request

When I try to make an AJAX call, my code is set up like this: var Data = { name : $('input[name=name]').val(), email : $('input[name=email]').val(), phoneno : $('input[nam ...

What is the best way to implement a JSON object within an <img> src attribute?

Currently, I am in the process of creating a dynamic Vuetify navigation drawer and I have the intention of storing images in a JSON array. My main inquiry revolves around figuring out if it's feasible to extract the image attribute and incorporate it ...

Create a unique onblur event listener for every element in a loop in Javascript

https://i.sstatic.net/tRYul.png I have added several items to a column in the database, but I am unsure of how to implement an onblur function for validation for each item within a loop. For example, if the NAME field is empty, I want to display an alert ...

Organize information in a React table following a predetermined sequence, not based on alphabetical order

As a beginner with React, I'm looking to sort my data by the column "Status" in a specific order (B, A, C) and vice versa, not alphabetically. The data structure looks like this: export interface Delivery { id: number; name: string; amount: num ...

Unable to display a cube using Three.js on a custom WebGL layer in Mapbox GL JS

Attempting to showcase the cube using this example: Add a 3D model. The example functions fine up to version 117 on three.js. However, starting from version 118, the cube disappears immediately after refreshing the page. After reviewing the changelog, it ...

Displaying Bootstrap Alert for a single occurrence

One issue I'm facing involves setting up alerts with Bootstrap. Initially, these alerts are hidden from view. However, when a rating is submitted using raty, an Ajax request is triggered. Upon successful completion of the request, an alert is displaye ...

Asynchronous POST request in Chrome Extension's popup.js

Apologies for asking again, but has anyone encountered a similar issue? I have a popup.js file with a login form that sends a request to an API to retrieve an API key for user authentication. When I set the request as synchronous (async: false), everythin ...

Exploring Python code to access the value of a JavaScript variable

As a newcomer to Python programming, I appreciate your patience. I have an HTML file containing multiple div layers. When clicked on, each div layer stores a value in a global JavaScript variable. This file is accessed within a webkit.WebView object. My ...

What is the best way to create an impact?

Need help fixing the parallax effect on this page. I attempted to implement a parallax effect but encountered some issues. Here is the JavaScript code: $objWindow = $(window); $('section[data-type="background"]').each(function(){ var $bgOb ...

What is the method for adding up elements based on their identification numbers?

Is it possible to calculate the sum of multiple range sliders using their unique IDs? Multiplying each range slider value by the corresponding input. And finally, adding up all the multiplication results. $(document).ready(function() { $(".range") ...

Simple steps for importing JS files in a web application

Upon examining the code snippet below: const express = require('express'); const app = express(); const http = require('http').Server(app); const io = require('socket.io')(http); const cors = require('cors'); app.u ...

What are the practical applications of integrating the Isotope jQuery library into Minima.pl?

I am really puzzled by the implementation done by Minima.pl (http://minima.pl/pl) where they integrated a feature in Isotope library that allows clicking on a thumbnail to open a larger gallery of images. One can click on a single image and cycle through t ...

Storing data from an HTML table into a database using ASP.NET MVC and JQUERY/AJAX

I am currently developing a Point of Sale system using ASP.NET MVC and I have encountered an issue with saving the content of the HTML table that displays all the orders to the database. I attempted to send the data through JSON to the controller, but it s ...

Creating a webpage with a feature that allows users to click a button and instantly change the background to a

Here is the code I have for generating random colors: const colors = ["green", "red", "rgba(133,122,200)", "#f15025"]; const btn = document.getElementById('btn'); const color = document.querySelector('.color'); btn.addEventListener(&a ...

Maintain the focus of the button when switching between tabs in a TabPane

Currently, I have implemented two different menus on my application. One is a tabPane while the other is a VBox containing buttons. By using psuedo selectors, I was able to style the tabs when they are selected with CSS, like shown in this example: .tab.l ...

PhpStorm 2019.2 introduces Material UI components that have optional props instead of being mandatory

My PhpStorm 2019.2 keeps showing me a notification that the Button component from Material UI needs to have an added href prop because it is required. However, when I refer to the Material UI API, I see something different. Take a look at this screenshot: ...

Determine the variance between two dates with the most efficient method

Currently, I am working on a page that allows users to search for GitHub profiles. Once a username is entered, all the repositories belonging to that user are displayed. In order to achieve this functionality, I am utilizing the GitHub API. Here is an exam ...

Next.js Server Error: ReferenceError - 'window' is undefined in the application

I am currently in the process of integrating CleverTap into my Next.js application. I have followed the guidelines provided in the documentation Web SDK Quick Start Guide, however, I encountered the following issue: Server Error ReferenceError: window is ...