Issue with applying CSS properties of 'top' and 'left' to a dynamically created div using

After an extensive search on both the site and the internet, I have not had any luck so far.

I am dealing with a series of dynamically-generated divs using JQuery, cloned from the original HTML source. While I can manipulate the positioning properties of the original divs, the cloned ones are unresponsive (not reacting to height and width properties) even though I can select them without issues.

Here is the initial HTML:

<div style="width: 504px; height: 252px; left: 333px; top: 135px;" id="mainHolder">
    <div style="width: 504px; height: 252px;" id="holder">
        <div style="width: 126px; height: 63px;" id="idTile_5369" class="tile"></div>
        <div style="width: 126px; height: 63px;" id="idTile_5373" class="tile"></div>
        <div style="width: 126px; height: 63px;" id="idTile_5377" class="tile"></div>
        <div style="width: 126px; height: 63px;" id="idTile_5381" class="tile"></div>                   
    </div>
    <div id="holderHandler"></div>
</div>

The following CSS rules are applied:

#mainHolder{
    position: relative;
}
#holder, #holderHandler, .tile, .tileHandler{
    position: absolute;
}

Below is the corresponding JS code:

getDataJsonServer('tiles.php', (function(data){ //getDataJsonServer --> custom function to obtain json data from the server through the JQuery getJson method
    var mainHolder=$('#mainHolder');
    var tilesHandler=$('#holder .tile', this.mainHolder).clone();
    tilesHandler.addClass('tileHandler');
    tilesHandler.removeClass('tile');
    tilesHandler.attr('id', function(i, idTileHandler){ return 'idTileHandler_'+extractId(idTileHandler); }); //extractId -->  custom function that extracts the id
    $('#holderHandler', this.mainHolder).append(tilesHandler);

    for(var tile in data){
        $('#idTile_'+data[tile].idTile, this.mainHolder).css({left: data[tile].position.left, top: data[tile].position.top});
        $('#idTileHandler_'+data[tile].idTile, this.mainHolder).css({left: data[tile].positionHandler.left, top: data[tile].positionHandler.top});
    }
}

Lastly, the returned Json data by tiles.php is as follows:

"data": [{
    "idTile": 5369,
    "position": {
        "left": -62,
        "top": 0
    },
    "positionHandler": {
        "left": -62,
        "top": 0
    }
},
"idTile": 5373,
    "position": {
        "left": -62,
        "top": 0
    },
    "positionHandler": {
        "left": -62,
        "top": 0
    }
},
"idTile": 5377,
    "position": {
        "left": -62,
        "top": 0
    },
    "positionHandler": {
        "left": -62,
        "top": 0
    }
},
"idTile": 5381,
    "position": {
        "left": -62,
        "top": 0
    },
    "positionHandler": {
        "left": -62,
        "top": 0
    }
}]

Although the final line inside the for/in loop functions correctly, the other line fails to set the left and top properties, without displaying any error messages.

Why is this occurring? Could it be because the second batch of divs are dynamically generated, as I suspect? How can this issue be resolved?


Edit:

  • Included the Json object returned by tiles.php
  • Corrected this.tilesHandler to this.mainHolder in the for/in block (typo).

Answer №1

Uncertain if the id of the duplicated elements have been altered in the previous section. It seems like they may have been changed to avoid having two identical id's in the document after using .clone().

I'm also unsure where the variable data is defined. Is tile referring to the elements' DOM style attribute?

Please provide clarification on the purpose of the data and tile variables. Thank you.

Perhaps start by quoting css properties like this:

for(var tile in data){
        $('#idTile_'+data[tile].idTile, this.tilesHandler).css({"left": data[tile].position.left, "top": data[tile].position.top});
        $('#idTileHandler_'+data[tile].idTile, this.tilesHandler).css({"left": data[tile].positionHandler.left, "top": data[tile].positionHandler.top});
    }

Answer №2

After much testing and re-testing, I found the issue within the extractId() function.

The problem was that the function was correctly returning the numeric id from the string, but it was adding an underscore before it. This resulted in duplicate underscores in the cloned div's id.

I apologize for any inconvenience this may have caused, and thank you for your efforts to help resolve the issue.

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

How to implement the onRowClick event in ASP.NET Gridview to show record details without using a Details/Select button

I'm currently working with a gridView and have configured a button within it to display detailed information when clicked. This button calls the DetailsView() function, which executes an SQL command and binds the data to a repeater for a custom detail ...

Modifying an object's value before pushing it into an array in JavaScript

I've been struggling to find the right keyword to search for my issue. I've spent hours trying to figure out what's wrong, but it seems like a simple case of pushing an object into an array. The problem arises when I try to log the values of ...

Bug in jQuery mouse hover effect causes the mouseover event to fire multiple times upon mouseout

I'm experiencing an issue with my gallery grid where a nested span displaying the title is supposed to slide up on mouseover and hide on mouseout. However, whenever the mouse moves down to the title or hovers out of the tile from the bottom, the hover ...

How to Preserve Scroll Position when Toggling a Div using jQuery

I've been struggling to find a solution for maintaining the scroll position of my page after a JQUERY toggle event. I've searched extensively but haven't found a fix yet. <script src="Scripts/_hideShowDiv/jquery-1.3.2.min.js" type="text/ ...

Place a material-ui React component at the center of a footer section

I'm facing a challenge with centering a material-ui Simple Breadcrumbs component within a footer as opposed to having it aligned to the left. Even though I'm new to this, I thought it would be straightforward but I can't seem to figure it ou ...

$scope.apply is triggering both "catch" and "then" handlers

I am trying to ensure that the content of a page in Angular 1.6.2 and UI router is only displayed once it has been confirmed on the server that the user has the appropriate role/permissions. It seems like without using $scope.apply(), the catch() function ...

Creating Location-Specific Customer Data using AngularJS similar to Google Analytics

Looking to create a user registration map similar to Google Analytics without actually using Google Analytics. Can anyone provide assistance with this task? I am utilizing MVC, C#, Sql Server-2014, AngularJS, and jQuery for this project. Despite my efforts ...

The jQuery dropdown selection for only displaying the month and year is not functioning properly when using the select

Currently, I am utilizing a datepicker with only the month and year as options to select from using dropdowns. However, when I apply the following CSS to disable the days of the datepicker, it ends up affecting all datepickers in my JSP file. 1. Is there ...

Show image details on hover?

I have six images displayed full width using a flex grid. I would like the image information (along with a visit button) to appear on hover, and the brightness of the image should decrease. I am struggling to position the information in the center of the i ...

React components need to refresh after fetching data from an API

I am currently working on a React application using TypeScript and integrating JSONPlaceholder for simulating API calls. I have successfully set up everything I need, but I am encountering an issue with re-rendering components that display response data fr ...

Ways to refresh the count of newly added div elements

Currently, I am working on a socket chat program that requires a badge to display the number of users in the chat room every time a new user joins. The code snippet provided below shows a function that adds the name of the new user to the list. The added n ...

Protractor tests succeeding prior to complete page load

Recently, my protractor tests have been failing after updating the node_modules. Strangely, it seems like the tests are initiating before the page is fully loaded: Connecting to the selenium server at http://127.0.0.1:4444/wd/hub [launcher] Running 1 inst ...

How can you automatically adjust the height of a div to be 100% of its parent while maintaining top and bottom margins

http://jsfiddle.net/YumHS/ The page showcased in the provided jsfiddle link includes a sidebar within the content div. <section class="cont"> <div class="sidebar"> <ul> <li> ...

Discover the process of creating a dynamic mailto link using AJAX and HTML

One of my tasks involves extracting email addresses from an XML document using AJAX, and then displaying them on a webpage as clickable links for sending emails. Here is a snippet of JavaScript code I am working with: emailobj = listings[i].getElementsBy ...

The animation isn't loading

I discovered a handy script that displays a waiting message when my form is submitted. I implemented jquery-ui to showcase this message in a dialog box, and it was successful. However, upon customizing the text and adding an animated gif background using C ...

A guide on converting TypeScript to JavaScript while utilizing top-level await

Exploring the capabilities of top-level await introduced with TypeScript 3.8 in a NodeJS setting. Here's an example of TypeScript code utilizing this feature: import { getDoctorsPage } from "./utils/axios.provider"; const page = await getDo ...

Issue with Material UI React JS Select component: Unable to deselect multiple values when more than one item is selected

Implementing a multiselect dropdown in material ui with specific conditions: The dropdown will contain [0 Apples, 1 Oranges, 2 Grapes]. By default, 0 Apples should be selected. None of the options can be unselected. If 0 Apples is selected and the user se ...

Is there a way to modify a button's aspect ratio when it is clicked?

Currently, I am utilizing the MUI v5 AppBar to craft a navigation bar with Tabs. My aim is to have the background of the Tab blend seamlessly with the main page background upon being clicked, as illustrated here: https://i.sstatic.net/e4bDn.png However, a ...

Utilizing Angular.js to nest directives seamlessly without cluttering the markup

Expressing my query might pose some difficulty, but I appreciate your patience. I comprehend that in the realm of Angular.js, directives play a crucial role in driving dynamic markup. What was once achieved through jQuery can now be accomplished using dir ...

What is the best way to switch a Boolean value in React Native?

Struggling with toggling a Boolean state from true to false when the result is undefined. Tried several methods but none seem to work. The boolean state in the constructor is defined like this: class UserInfo extends Component{ constructor(props){ s ...