Tips for binding JavaScript to dynamically generated elements?

I have a dynamic JavaScript rotation function set up with a div element that is generated dynamically by a button. The challenge I am facing is figuring out how to correctly append this rotation slider for each dynamically created element so it can operate individually for each one, rather than affecting all of them and only working on the first created element. You can see an example here:

http://jsfiddle.net/fqjvd7sa/24/

Rotation Function

$(function() {
   $('.s1').slider({
      range: 'min',  
      min: -13,
      max: 13,
      slide: refreshRotate
   });

   function refreshRotate() {
      var rotate = $('.s1').slider('value'),
          x = $('.x');
          x.html(rotate);
      $('.list').css('-webkit-transform', 'rotate(' + rotate + 'deg)');
      $('.list').css('-moz-transform', 'rotate(' + rotate + 'deg)');
      $('.list').css('-ms-transform', 'rotate(' + rotate + 'deg)');
      $('.list').css('-o-transform', 'rotate(' + rotate + 'deg)');
      $('.list').css('transform', 'rotate(' + rotate + 'deg)');
   }
});

Dynamically Generated Content

var dom = {

        // Build the main button
        buildButton: function(){

            // Create new DOM element - div
            var button = document.createElement('div');

            // Set element attribute
            button.setAttribute('id', 'strip');
            button.setAttribute('class', 'newclass');            

            // Style the element
            button.style.width = "500px";
            button.style.height = "400px";
            button.style.margin="0px 10px 0px 30px";
            // Add content - FileAPI
            button.innerHTML = '<div class="s1"></div><div class="list"></div>';

            // Print element
            document.body.appendChild(button);
        }
    };

 document.getElementById("first-div").onclick = dom.buildButton;

Answer №1

Ensure that the slider is set up individually for each image, rather than just once for the first one. To achieve this, customize the rotate-slider within the buildButton function for each specific image. Using jquery, you can efficiently generate new elements and establish the required one-to-one connections.

Answer №2

Utilizing the .each() method allowed the //tilt slider to operate on every .list element, rather than just once. I opted not to use #ID's, but the slider script is effectively looped.

   var dom = {

        // Creating the main button
        buildButton: function(){

            // Creating a new DOM element - div
            var button = document.createElement('div');

            // Setting element attributes
            button.setAttribute('id', 'strip');
            button.setAttribute('class', 'newclass');            

            // Styling the element
            button.style.width = "500px";
            button.style.height = "400px";
            button.style.margin="0px 10px 0px 30px";
            
            // Adding content - FileAPI
            button.innerHTML = '<div class="s1"></div><div class="list"></div>';





            // Appending the element
            document.body.appendChild(button);


            // Tilt Slider
 $('.list').each(function() {   
$(function() {
$('.s1').slider({
range: 'min',  
min: -13,
max: 13,
slide: refreshRotate

});


function refreshRotate() {
var rotate = $('.s1').slider('value'),
x = $('.x');
x.html(rotate);
$('.list').css('-webkit-transform', 'rotate(' + rotate + 'deg)');
$('.list').css('-moz-transform', 'rotate(' + rotate + 'deg)');
$('.list').css('-ms-transform', 'rotate(' + rotate + 'deg)');
        $('.list').css('-o-transform', 'rotate(' + rotate + 'deg)');
        $('.list').css('transform', 'rotate(' + rotate + 'deg)');
}
});

});




        }
    };





document.getElementById("first-div").onclick = dom.buildButton;

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

Accessing Struts2 tag attributes with JavaScript

Currently, I am using struts2 with jsp. Within the JSP file, there is a table with several rows of data. To display the row data in the table, iterators are being used. Each row includes a button that allows the user to update the row's data, such as ...

Combining data from multiple API calls in a for loop with AngularJS

I'm working with an API that contains pages from 1 to 10 and my goal is to cycle through these page numbers to make the necessary API calls. app.factory('companies', ['$http', function($http) { var i; for (i = 1; i < 11 ...

"Using Node.js to create a simulated mobile environment: a step-by-step guide

I am seeking a way to replicate the functionalities of a mobile browser using Node.js. This means that all mobile browser features should be accessible on the client-side, even if they are simulated. The goal is for webpages to believe they are being load ...

Exploring innerHTML in JavaScript for event listening

Two code snippets were tested, one worked as expected while the other didn't produce the desired result. The goal was to display a different text every time a user clicked on a button. However, the unsuccessful code always displayed err, with no chang ...

Get the docx file generated with Flask and VueJS

I've been grappling with the challenge of downloading a docx file in VueJS. Initially, I attempted to generate the file on the frontend, but it kept getting corrupted. To solve this issue, I resorted to using Flask to create the docx file, which worke ...

Incorporate JSON data from a file into a d3 visualization within a Node.js/Express

I am working on an express app and I have the requirement to load JSON data from the "public" folder into d3 (version 4). Here is my current folder structure: public |-myData.json view |-index.jade app.js The JSON data I want to load using d3: { { ...

Creating a background color without using the <canvas id> element can be achieved by utilizing CSS properties such as

As a novice in the world of HTML and CSS, I find myself working on creating my website using HTML. Upon inspecting my site, I notice that the default background color is white. Despite trying to change it by using #canvas { background-color: black; } in ...

Creating an image with Python utilizing an HTML template for later printing

Currently, I'm working on merging or assembling 3, 4, 6, or even more photos into one single file based on a specific template. This file will then be sent to a printer in a photobooth style. I attempted to achieve this using the Pillow library but f ...

The element in the HTML source code evades detection by Selenium

Given: Python 3.11.2 Selenium 4.8.2 Chrome as the browser engine I am searching for the following HTML code snippet: <input type="text" class="datepicker apex-item-text apex-item-datepicker hasDatepicker" size="32" value= ...

Centering numerous elements on all screen sizes and devices

Is there a way to align elements in the center of the screen both vertically and horizontally without specifying width and height for mobile and desktop views? How can I make it responsive so that it appears centered on all devices? .parent-container{ ...

Angular neglects the specified animation timing

I created a sidebar component that relies on the sidebarExpanded state passed through Input(). Despite the correct animation trigger upon input change, the width adjustment happens abruptly. Interestingly, the same animation code works flawlessly in anothe ...

karma - Plugin not located

Attempting to run JS test cases using karma, but consistently receiving a plugin not found error. Oddly enough, the same configuration file works perfectly for one of my co-workers. Below are the logs: $ karma start karma.conf.js 04 10 2016 17:51:24.755 ...

Currently, I'm attempting to figure out a way to create a CSS string in my MVC ASP.NET project. Any ideas or suggestions are greatly appreciated

I am currently exploring solutions to generate a CSS string in my ASP.NET MVC Web Application. Specifically, I am interested in creating this at the selector level. For instance, I might have a class named "TableFormat" with the following CSS properties: ...

What are the reasons that execCommand does not function correctly when attempting to justify text?

Why isn't justify with execCommand working properly? Take a look at the code below: $('#JustifyLeft').click(function(){ document.execCommand("JustifyLeft", false, ""); }); <script src="https://ajax.googleapis.com/ajax/libs/jquery/2 ...

What is the best way to position this material-ui select list at the bottom of the input block for proper alignment?

My material-ui select build is working fine overall, but I'm looking to align the top line of the select list with the bottom line of the input block. Any ideas on how to achieve this? This is my code: const styles = theme => ({ formControl: { ...

Issue with Vue.js: Textarea not functioning properly within a v-for loop

The v-model value within the v-for loop is not unique. Here is the provided template: <template> <div id="FAQ" v-for="(question, index) in questions.slice().reverse()" :key="index" ...

Updating state array within reducer leads to duplicate execution of calculations

const updateCartReducer = (state, action)=>{ console.log('running the updater function') const existingItemIndex = state.items.findIndex( (item) => item.restaurant === action.item.restaurant && ...

Adding a JavaScript widget to a WordPress page

Good morning! I need to place an affiliate external widget on a WordPress page. The code I have loads external content within the page. <script type="text/javascript" src="http://www.convert.co.uk/widget/mobiles.js"></script> The placement o ...

Adding a new div using Jquery after a specific table row

I am having trouble displaying additional data in a table when a specific row is clicked. Here is the table structure I am working with: <div id="display"> <div class="displayRow"> <img src="images/expand-arrow.gif" class="expandArrow ...

Initiate Ant Design select reset

I am facing an issue with 2 <Select> elements. The values in the second one depend on the selection made in the first one. However, when I change the selected item in the first select, the available options in the second one update. But if a selectio ...