The line break is being disregarded by jQuery's insertBefore function

In my simple HTML, I have a div with a limited width. Inside are several span tags styled with nowrap. Here is the CSS:

.content {
    width: 50%;
    margin: 10px;
    padding: 10px;
    border: 1px solid black;
}
.adder {
    color: blue;
    cursor: pointer;
}
.added {
    position: relative;
    white-space: nowrap;
}

Here is the corresponding HTML:

<div class="content">
    <span class="added">A slightly long text 1.</span>
    <span class="added">A slightly long text 2.</span>
    <span class="added">A slightly long text 3.</span>
    <span class="added">A slightly long text 4.</span>
    <span class="added">A slightly long text 5.</span>
    <span class="adder">Add</span>
</div>

When clicking on the 'Add' button, a new span is added before it each time:

$(function() {
    $(".adder").click(function() {
        $(document.createElement("span"))
            .addClass("added")
            .html("Custom text to be added,")
            .insertBefore(this);
    });
});

The issue arises when multiple spans are added and they start overlapping the edge of the div instead of breaking into new lines. How can this be prevented?

This behavior is observed in Google Chrome version 42.0.2311.135.
The full HTML code can be found at this JSFiddle link.

Answer №1

Your initial inventory of "added" <span> elements contains spaces in between them. However, the ones added using JavaScript lack this spacing. As a result, the browser is unable to add line breaks between them - it will only do so at points where there is whitespace present.

To address this issue, there are a few solutions available. One straightforward method is to include the following code within your "click" handler:

$("<span/>", { text: " " }).insertBefore(this);

An alternative fix involves utilizing pure CSS:

.added::after {
  white-space: normal;
  content: "\00200B";
}

Using this approach eliminates the need for any changes to be made to the JavaScript code.

Answer №2

When utilizing the insertBefore method, there won't be any space automatically added between your elements. To achieve the desired wrapping effect, simply insert a space manually:

$(function() {
    $(".adder").click(function() {
        $(document.createElement("span"))
            .addClass("added")
            .html("A custom text to be add,")
            .insertBefore(this)
            .after(" ");  // include a single space
    });
});

http://jsfiddle.net/gtoh8hzp/

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

Using JQuery's match() function with underscore character

I am currently facing an issue where my input validation is supposed to match only letters, but for some reason underscores are also being considered as acceptable symbols. $(document).ready(function() { $('#first_name').bind('input ...

Having an issue with my Wordpress theme where the footer doesn't remain at the bottom of the page

Having trouble with my custom Wordpress theme that I can't seem to fix. Despite extensive research, the footer on my website refuses to stay at the bottom of the page and instead floats in the middle of posts and static pages. I've tried all sol ...

"Resetting count feature in AngularJS: A step-by-step guide

I have a list consisting of four items, each with its own counter. Whenever we click on an item, the count increases. I am looking to reset the counter value back to zero for all items except the one that was clicked. You can view the demonstration here. ...

Guide on smoothly transitioning between 2 points within a requestAnimationframe iteration

Would it be possible to acquire a library for this task, or does anyone have any suggestions for my psuedocode API? Inquiry: How can I create a function that accepts 4 parameters interpolate(start, end, time, ease) and smoothly transition between the sta ...

What is the best way to transfer the value of a radio button, retrieved from a database, to a textbox?

Greetings, I am trying to figure out how to pass the value of a radio button to a textbox using jQuery and PHP. The radio buttons are generated dynamically based on rows from my database, so I set the row ID as the ID for each radio button. However, the co ...

Seeking Answers About jQuery UI Themeroller

After designing a unique theme using http://jqueryui.com/themeroller/ and saving it, I have the theme downloaded. What is the next step to begin implementing the CSS for the theme? ...

Is there a way for me to design a button that includes an image?

I'm looking to create a button on my webpage using an image that will link to other pages. I want the flexibility to use both small and large text on this button. The specific image I want to use is: So far, I've attempted some coding but haven ...

Setting the position of a tooltip relative to an element using CSS/JS

I'm struggling to make something work and would appreciate your help. I have a nested list of items that includes simple hrefs as well as links that should trigger a copy-to-clipboard function and display a success message in a span element afterwards ...

Encountering a 500 internal server error while attempting to submit data to a Laravel project through Axios in Vue.js

I encountered an issue while attempting to send data to my Laravel application using Axios in Vue. The error I received was: Error: Request failed with status code 500 at e.exports (axios.min.js:8) at e.exports (axios.min.js:8) at XMLHttpReque ...

Having trouble verifying a phone number using the awesome-phonenumber npm package?

I recently developed some JavaScript using the awesome-phonenumber npm package. index.js const yargs = require('yargs'); var PhoneNumber = require( 'awesome-phonenumber' ); const argv = yargs .usage('Usage: $0 -n [num]' ...

Explaining Vue.js actions and mutations in detail

Can someone help clarify the relationship between these functions for me? I'm currently learning about Vue.js and came across an action that commits a mutation. The Action: updateUser({commit}, user) { commit('setUser', {userId: user[&ap ...

Enhancing WordPress Menu Items with the 'data-hover' Attribute

Looking for a solution to add "data-hover" to menu items on Wordpress, like: Wanting to insert: data-hover="ABOUT US" into <a href="#">ABOUT US</a> without manually editing the link's HTML to make it: <a href="#" data-hover="ABOU ...

Utilizing a jQuery hint plugin with ASP.NET MVC3's client-side validation feature

What I mean by a jQuery hint plugin is one that displays guiding text like "Please enter your name here..." inside an input field. However, when using such a plugin with jQuery ASP.NET MVC client-side validation, it may end up validating the input against ...

Is there a way to incorporate an array into an array of arrays with jQuery?

I am working with an array shown below: var cString = [ ['1','Techdirt','www.techdirt.com'], ['2','Slashdot','slashdot.org'], ['3','Wired&apos ...

I'm encountering an issue with Regex.test

When working with the following JavaScript code... $.post(url, data, function (json) { var patt = new RegExp('/^\[{"dID":/'); if (patt.test(json)) { //output json results formatted } else { //error so o ...

Restricting the subscribe to fire on initialization for a dropdown with a value bound on page load

It is well known that Subscribe does not trigger on page load as per the documentation. However, my situation is slightly different and I will attempt to explain it. In my create page, I have a dropdown list and a set of other controls. The dropdown list ...

Unable to invoke any fineUploader functions within a callback function

My autoUpload is currently set to false because I prefer uploading the images manually to my backend. To achieve this, I need the file object first. In the onSubmitted event callbacks, I am attempting to pass the image's ID to the getFile method to re ...

What You Need to Know About Hovering and Highlighting Buttons Using CSS

As a beginner in CSS, I decided to practice padding and margin mechanics by creating two buttons. Now, I'm trying to make the buttons larger without one button pushing the other out of place. I managed to achieve this for the save button, but I'm ...

Having difficulties with DIV elements

Having some difficulty creating a webpage with divs. The site I'm working on is similar to the old Myspace, so CSS can't be used in the code. Attempting to create tables using DIV elements but facing some issues. This is what my page currently l ...

The problem with the first item title in the Jquery slider is causing

I've been working on setting up a Jquery slider (caroufredsel) in which I want certain elements to be displayed above the slider itself, outside of the wrapper. Everything is working fine except for the first slide! After spending several days trying ...