When jQuery adds new elements, their CSS may not be applied accurately

One issue I encountered is using jQuery to dynamically add new elements, only to find that the CSS isn't being applied correctly to the newly added element.

To illustrate this problem, I created a jsFiddle. In the example, there are differences in spacing between the newly added input text boxes.

Here's a snippet of the HTML code:

<fieldset>
    <div class="control-group custom">
        <label class="input-mini" for="first">Start</label>
        <label class="input-mini" for="first">End</label>
        <label class="input-mini" for="first">Share</label>
    </div>
    <div class="control-group custom">
        <input type="text" class="input-mini">
        <input type="text" class="input-mini">
        <input type="text" class="input-mini">
    </div>
    <div>   
     <a id="plus_time_button" class="btn plus" href="#">
      <i class="icon-plus-sign"></i>
     </a>
    </div>
</fieldset> 

Below is a portion of the JS code used:

 $("#plus_time_button").live("click", function () {
    var new_row = "<div class=\"control-group custom\"><input type=\"text\" class=\"input-mini\"><input type=\"text\" class=\"input-mini\"><input type=\"text\" class=\"input-mini\"></div><div><a id=\"plus_time_button\" class=\"btn plus\" href=\"#\"><i class=\"icon-plus-sign\"></i></a></div>";
    $("fieldset div:last-child").remove();
    $("fieldset").append(new_row);
});

And here is some of the CSS code utilized:

.custom label {
    padding: 4px 6px;
    margin-right: 20px;
    display: inline-block;
    text-align: center !important;
}
.custom input {
    margin-right: 20px;
}

I did come across a similar question, but unfortunately, it didn't provide a solution to my specific problem.

Answer №1

Spacing matters.

Your initial HTML utilizes code similar to this:

<input ...>
<input ...>

The new HTML you added looks like this:

<input ...><input ...>

The difference lies in the whitespace between tags, where the first example results in a small space between tags, while the added rows do not have any extra space.

To avoid this whitespace interference, one approach is to format your code like so:

<input type=text class=input-mini
><input type=text ...

In this formatting, the closing angle bracket wraps to the next line to eliminate unwanted spaces.

However, a better practice is to reuse the same DOM elements in each row to maintain consistency across all rows.

One method I often use is creating a template for a single row with an id of "T":

<div id=T class="control-group custom">
  <input type=text class=input-mini>
  <input type=text class=input-mini>
  <input type=text class=input-mini>
</div>

You can then clone this template whenever you need to add a new row, ensuring that the original HTML structure is preserved:

var plus = $('#plus_time_button').closest('div');
var T = $('#T');
T[0].id = '';

for(var i = 0; i < 3; i++)
    plus.before(T.clone());

$('#plus_time_button').click(function () {
    plus.before(T.clone());
});

In my original response, I used the .live() event syntax. While it may not be necessary if you are using jQuery 1.7 or 1.8, the above code eliminates the need for live since the targeted element remains in the DOM. For guidance on converting .live() calls for jQuery 1.9, refer to the jQuery documentation here:

http://api.jquery.com/live/#entry-longdesc

Answer №2

Relocated plus_time_button from within fieldset to outside

$("#plus_time_button").on("click", function () {
    $("fieldset").find('div:last').clone().appendTo('fieldset');
    //scrollToBottom("create_table");
});

Fiddle in action -- http://jsfiddle.net/SSPRJ/

Answer №3

To ensure proper spacing between the inputs, I have included "&nbsp" in between them

$("#plus_time_button").on("click", function () {
    var new_row = "<div class=\"control-group custom\"><input type=\"text\" class=\"input-mini\">&nbsp<input type=\"text\" class=\"input-mini\">&nbsp<input type=\"text\" class=\"input-mini\"></div><div><a id=\"plus_time_button\" class=\"btn plus\" href=\"#\"><i class=\"icon-plus-sign\"></i></a></div>";
    $("fieldset div:last-child").remove();
    $("fieldset").append(new_row);
    scrollToBottom("create_table");
});

JSFIDDLE

Answer №4

Your initial HTML code is being affected by the spaces within it.

Simple solution

Check out this demo

To resolve this issue, eliminate the spaces in your HTML code:

...
<input type="text" class="input-mini">
<input type="text" class="input-mini">
...

The problem arises from a carriage return between the two lines which the browser interprets as an actual space.

Make sure to keep your elements without any spaces:

<input type="text" class="input-mini"><input type="text" class="input-mini">

Why does this happen?

When using display: inline-block, the browser applies text interpretation rules including respecting spaces between HTML elements.

If you are generating dynamic elements with JavaScript, string concatenation does not include additional spaces.

An alternative approach would be to use the following CSS:

.custom label {
  padding: 4px 6px;
  margin-left: 20px;
  display: block;
  float: left;
}

.custom label:first-child { margin-left: 0; }

Answer №5

After adding a new node to my accordion, I make it update by using the following code:

$('#accordion').accordion( "refresh" );

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

Confusing jQuery Selector Problem

Here is an example I have What this example should do: Check if there is a .box-wrapper in the document If there is, and if there is a click event on .tabs li a Locate .selected and remove the class Find the parent of the clicked link and add the class ...

Why is the responseText of an AJAX request empty on Chrome?

Why does this simple AJAX request work in IE but not Chrome? Check out the code below: var x = new XMLHttpRequest(); x.open("GET","style.php",true); x.send(); alert(x.responseText); The last line triggers an empty 'alert' window. Here's ...

When a click event triggers the list to close, an incorrect element

Here is the code snippet I am currently working with: http://jsfiddle.net/xFxD3/1/ However, I have encountered an issue where clicking on the "li" elements causes the list to close. The intended behavior is for the list to only close when one of the "span ...

I'm looking to design a navbar similar to the one in the provided link, and I'd like it to appear when scrolling

I'm struggling to figure out how this particular navbar was created. How can I add a navlist for Videos and make the navbar visible upon scrolling? Are there any resources, articles, or hints to help me get started with this? LINK - ...

javascript if condition not executing properly

I am struggling with my random number generator that should generate numbers between 5 and 15. I am trying to change the position of the 'chest' div based on the number generated by the computer, but for some reason it is not working as expected. ...

The function window.open has been disabled on codepen.io site

My dilemma involves a button designed to open a random Wikipedia page. While the code works perfectly in the CodePen editor, I encounter issues when opening it in full-page view. The problem arises when the log displays 'window.open is disabled'. ...

Creating a custom Angular 2 component with specified HTML template content

I am currently working with Angular 2 and @ng-bootstrap. In my project, I have a modal dialog set up as follows: <template #editDialog let-c="close" let-d="dismiss"> <div class="modal-header"> <button type="button" class="close" ...

To ensure secure access to a file, restrict it to only be accessed through Jquery Ajax requests

Hey guys, I've run into a little problem... I just finished creating two PHP files. CreateAdmin.php ----------> Contains a Form to Fill Out Save.php ----------------> Called using jQuery Ajax to insert data into the database. Everything seem ...

Designing Checkboxes and Radio Buttons

I am seeking a way to customize the appearance of checked and unchecked checkboxes using images without modifying the HTML structure. I would prefer not to add labels, classes, or IDs to the elements. The provided example only works in Webkit browsers, s ...

Switch the class on a specific div section

As you scroll to the top, a class named "blue" is added to the element with the ID of "div". However, when the scroll returns to the bottom, the "blue" class remains without being removed. Fiddle Link: http://jsfiddle.net/5d922roc $(window).scroll(fu ...

Store the value returned by the function(data) from the $.post method in a variable

Hello Fellow Developers! I'm currently working on a coding project with the following objective: My goal is to extract URLs of files stored in a specific folder and then store them in an array using JavaScript. Here's how I envision the proces ...

Hovering over an element will change its background color along with adjusting the background

I encountered a situation with the following code: CSS: <style> div.testy { border:1px solid black; } div.testy:hover { background-color:red; } </style> HTML: <div class="testy" style="height:100px; back ...

Alignment issue with text in Vuetify Datatables cells

I'm experimenting with Vuetify on my Laravel Vue application, and everything seems to be working fine except for the DataTables styles. The padding of the cells is not vertically center aligned as expected. Here's a screenshot https://i.sstatic.n ...

The issue of CSS transitions flickering in Internet Explorer

Can someone help me troubleshoot an issue with this code in Internet Explorer? CSS: .nav-fillpath a { width: 100px; height: 100px; position: absolute; display: block; bottom: 0%; left:0; right:0; color: #3e3e3e; margin ...

The search feature on mobile devices is currently malfunctioning

The jQuery code below is used to search for products. It works perfectly in desktop view, but the responsive mobile view does not seem to be functioning correctly. Can someone assist me with fixing this issue? $("#search-criteria").keyup(function() { ...

Strange behavior of dropdown submenu

I've encountered an issue where my child's ul li elements are not behaving as expected, despite following advice from other sources. After days of debugging with no success, I am unable to pinpoint the problem. The image showcases the issue perfe ...

Stand out with Bootstrap's wide card design

Does anyone know how I can correct the image display issue within this card using Bootstrap 4? I am attempting to adjust the picture so that it is perfectly scaled to fit within a fixed height card. Currently, the image appears stretched and I am explorin ...

Jquery-ajax fails to accomplish its task

I am just starting to learn about ajax and recently created a simple page on my local server to practice sending and receiving data from/to a JSON file in the same directory. Although the GET method is working perfectly fine, I am having trouble understan ...

Floating and scrolling navigation bar not functioning properly in bootstrap framework

I've been dabbling in coding for a while now, practicing at my current job. I managed to create a floating and scrolling navigation bar on the right side of my website using bootstrap. However, after taking a 3-week break and returning to my site, I n ...

I'm seeking a way to access the input element within the InputGroup component of BlueprintJs in my

The BluePrintJS React InputGroup component offers a convenient user interface for modern applications. However, it does not provide direct access to the internal <input> element. There are two primary reasons why I need to access the input element: ...