Skip to content
Advertisement

html set title attribute to display line break

How can I display line-breaks for a hover event using title on a simple html-element? / What is the proper code to be used?

I am trying to set the title attribute like so:

.setAttribute('title', 'line1 &amp;#013; <br />-  /n /n /r line2')

..That does not work. Is does not break anywhere.

enter image description here

……………….. enter image description here

— Code sample —

const box = document.querySelector('.box');

// set `id` attribute on element
box.setAttribute('title', 'line1 
 <br />-  /n /n /r line2');
<div class="box" style="background-color: pink; width: 20px; height: 20px"> </div>

<br><br>
this works with "&amp;#013;"
<div style="background-color: blue; width: 20px; height: 20px" title="line1 
 <br />-  /n /n /r line2"> </div>

Advertisement

Answer

You were close, but used a slash instead of a backslash in n. HTML code, on the other hand, will not get parsed, so <br> or entities will not work from JavaScript.

From the HTML Standard:

If the title attribute’s value contains U+000A LINE FEED (LF) characters, the content is split into multiple lines. Each U+000A LINE FEED (LF) character represents a line break.

As per JavaScript Escape sequences, n maps to that character.

You also can add unicode characters to a string like this:

box.setAttribute('title', "line1u{000A}line2");

Plus, instead of using a regular string as the attribute value, you can use a template literal, which allow you to add line breaks to the string:

box.setAttribute('title', `line1
line2`);

Please beware the following remark from the HTML specification. You should not rely on the title attribute to provide information that is not provided by other means.

Relying on the title attribute is currently discouraged as many user agents do not expose the attribute in an accessible manner as required by this specification (e.g., requiring a pointing device such as a mouse to cause a tooltip to appear, which excludes keyboard-only users and touch-only users, such as anyone with a modern phone or tablet).

// set by means of Unicode
document.querySelector('.box1').setAttribute('title', "line1u{000A}line2");

// set `title` attribute on element by means of template literal
document.querySelector('.box2').setAttribute('title', `line1
line2`);

// simple with n
document.querySelector('.box3').setAttribute('title', `line1nline2`);
<p class="box1" style="background-color: blue; width: 20px; height: 20px"></p>

<p class="box2" style="background-color: pink; width: 20px; height: 20px"></p>

<p class="box3" style="background-color: green; width: 20px; height: 20px"></p>
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement