<span> creating a line break after the second sentence

Link to Code: http://jsfiddle.net/MuHvy/

Javascript:

    $(document).ready(function () {
    $(".addTag").click(function () {
        $('.questao').html($('.questao').html() + '&nbsp;<span contentEditable="false" class="tagResp">&nbsp;</span>&nbsp;');
        $('.questao').focus();
    });
    });

Span Css:

border:2px solid #dadada;
border-color:#9ecaed;
border-radius:7px;
display: inline-block;
height: 10px;
width: 50px;
padding:5px;
margin-top:3px; 
box-shadow:0 0 10px #9ecaed;
white-space:nowrap;

This code snippet is designed to create a tag on the same line when a button is clicked.

Issue: The created tag by jQuery jumps to a new line after the second line, instead of staying in the same line.

Example:

~INCORRECT~

 randomtext randomtext <span>tag</span> <br>
 randomtext <br>
 <span>tag</span>

Should look like this:

 randomtext randomtext <span>tag</span> <br>
 randomtext <span>tag</span>

Another question is:

Is it possible to focus on the last line? The .focus() function in jQuery goes to the start of the text, but ideally should go to the end.

Appreciate any help or suggestions!

Answer №1

It appears that there may be a problem with how contentEditable is implemented in HTML5

If you visit this link http://jsfiddle.net/MuHvy/10/ and click the test button, you will notice that when you add text to the box and then click the test button again, an extra <br> tag is added due to the box losing focus.

I couldn't find any specific information about the handling of focus loss in http://www.w3.org/TR/2008/WD-html5-20080610/editing.html

One potential workaround is to create a function that removes trailing <br> tags before adding the next element, although this solution may vary depending on the browser being used

Answer №2

While Jason P was examining your HTML, I took a look as well. I hope this adjustment meets your requirements. I included a display : inline in your CSS for any div within your contentEditable area. This ensures that even after pressing enter and creating a new div element, it will remain inline.

Check out the updated fiddle here: http://jsfiddle.net/MuHvy/4/ (Successfully tested on Chrome 23 and IE10)

Similarly, for Firefox and Safari, you may consider replacing the <br> with '' and then inserting a span when a click event occurs.

In regard to IE9, the appearance of the div itself might be unconventional, so we can disregard that issue.

If the focus presents an problem, take a look at the following question: jQuery Setting cursor position in contenteditable div. This resource provides what you're looking for. I hope this information proves beneficial!

Answer №3

If you want to resolve the issue, some postprocessing will be necessary. HTML does not pay attention to whitespace, so in the eyes of an HTML document (and jQuery when writing to one), the following code snippets are essentially the same:

randomtext randomtext <span>tag</span>
randomtext
<span>tag</span>

And this:

randomtext randomtext <span>tag</span>
randomtext <span>tag</span>

They perform the same functionally. If you are particular about whitespace, consider using text() over html(), and writing to a textarea instead of a div.

As for your last query, the solution can be located here: jQuery Set Cursor Position in Text Area

Edit:

Following @Gorfl's mention that the newline is actually a linebreak, I conducted further investigation. It appears that the issue stems from how browsers handle contentEditable. In Firefox, each line ends with a <br>, regardless of hitting enter or not. On the other hand, Chrome wraps every line in a div. To ensure a consistent solution across different browsers, it might be best to avoid using contentEditable altogether. Instead, attach a listener for keydown or keypress events, and have it replicate the keystrokes in the div body for full control of display.

Answer №4

The issue with the extra break line was resolved by using this solution:

   $('br[type="_moz"]').remove();

It seems that the div was adding a br element with type _moz at the end every time.

Here is the Jquery code snippet that fixed the problem:

 $(document).ready(function () {
    $(".addTag").click(function () {
        $('br[type="_moz"]').remove();
        $('.questao').html($('.questao').html() + '&nbsp;<span contentEditable="false" class="tagResp">&nbsp;</span>&nbsp;');
        $('.questao').focus();
    });
});

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

Incorporating date formatting to the existing documents

The mongoose schema I have created is structured in the following way. mongoose.Schema({ "url": String, "translations": [ { "targetLang": String, "source": String, ...

Save the contents of a file within an HTML table using jQuery

I needed to insert multiple files into the database by uploading and adding each file's content to a table. Once all files were added to the table, I included the table's values along with the file content in form data which was then passed to aj ...

I am having trouble with the browser detection not accurately identifying the browser I am currently using

Currently, I am working on a JavaScript code that will simply display the name of the browser being used to view the web page. Despite me using Safari, none of the navigators seem to recognize it as the current browser. The information displayed in my brow ...

Issue with array filter not functioning correctly upon page refresh when utilizing vue-router

I have a method (shown below) that functions perfectly when I'm directed from a <router-link>. selectedSpaceObj() { if (!this.selectedSpace) { return {}; } else { return th ...

The iPad Overlay fails to fully extend across the screen

I have implemented a modal div as an overlay to disable the background page while the overlay DIV is open. Below is the code I am using: #TB_overlay { height: 100%; left: 0; position: fixed; top: 0; width: 100%; z-index: 100; } Al ...

Is there a way to delete cookies upon browser closure, but retain them while moving between pages?

Hello, I am looking for a way to clear all cookies and local storage when the browser is closed, while still retaining them while navigating between pages in Next.js. I have tried using the window.onbeforeunload event, but this also triggers when navigat ...

The length parameter for geometry.vertices in Three.js is not defined

Greetings, fellow members of the StackOverflow community. I have embarked on a journey to learn three.js, and for my learning project, I decided to recreate an 80's style retro hills scene reminiscent of this. Initially, everything was progressing smo ...

Is it possible to use two onChange functions in a single text field with ReactJS?

Is it possible to have two onChange functions in a single Textfield? In my code, "onChange={ showDiv}" is a handler that shows "Direct 2" when clicked and hides upon selecting option1. The second onChange={(e) => exhandleChange(e)} is used for another ...

How is it possible to receive a TRUE value when the API returns an error message indicating that the requested photo does not exist?

I am currently in the process of learning Angular and Typescript, but I am facing some challenges. I am working on an application that involves displaying a list of photos, as well as allowing users to create, edit, and delete existing photos. However, whe ...

What is the best way to line up the two stacked elements with a shared background image to give the appearance of a single cohesive image?

The layout of the header on my website's homepage is as follows: <header> <div class="navbar-lock"></div> <div class="hero"></div> </header> In this setup, div.navbar-lock represents a fixed navigation bar wit ...

When attempting to call a function from a separate JavaScript file in Vue, the returned value is showing

My goal is to trigger my notification function from another JS file, but I keep getting an undefined error. The code snippet for the notification function in notification.js is as follows: function notification(message, level = 'success') { ...

Encountering a 404 error when attempting to access static files within a directory using Express Js

Organizing my static files has been a breeze with multiple directories. I have some static files in the client directory, while dashboard-related files are nested within the src directory. Here is how my directory structure looks: / | client //housing sta ...

Spinning an object smoothly in the opposite direction of the OrbitControls camera's y rotation in three.js

Is there a way to use OrbitControls in three.js to make a planeMesh always remain facing the camera? I've attempted some code but it's not quite working as expected. I want the planeMesh to slowly readjust its orientation only when the camera mov ...

What is the best way to create sourcemaps in nextjs?

Incorporating Next.js into my application has been a smooth process overall, but I encountered an issue when trying to generate sourcemaps to analyze bundle sizes. Initially, I followed the guidelines provided on Next.js: How to use source-map-explorer wit ...

Steps for swapping a term with a hyperlink

I am looking to substitute a word with a link instead, here's how I plan to accomplish it: const text = "Edit src/App.js and save to reload." return ( <div className="App"> <header className="App-header"&g ...

Exploring the JSON data received from PHP script via jQuery AJAX

In my program, I have created a web page with 5 radio buttons for selection. The goal is to change the picture displayed below the buttons each time a different button is chosen. However, I am encountering an issue during the JSON decoding phase after rec ...

Converting JavaScript code for Angular: A step-by-step guide

I have been working on integrating a feature similar to the one demonstrated in this Angular project: https://codepen.io/vincentorback/pen/NGXjda While the code compiles without any issues in VS code, I encountered two errors when attempting to preview it ...

Error: The reference to "google" has not been defined within the context of the Google Maps

Having trouble with Java script even though everything seems to be working fine. I am unable to run the code that follows, specifically the Google function which is crucial. Is there a way to remove this error or find another solution? //Error occurs on ...

Utilize images inputted via an HTML DOM file uploader within p5.js

I'm facing a challenge with allowing users to upload their image file through a DOM file uploader (<input type="file"></input>). Once the image is uploaded, I'm unsure of how to transfer it to JavaScript and process it using p5.js. Ho ...

methods for testing private functions outside of react component

When it comes to testing a private function outside of a component, it seems more convenient to test the function on its own rather than within the component itself. However, since the function is private and not exported, this presents a challenge. funct ...