Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript: how can I tell if a <span> is broken over 2 lines?

I display a bubble help for some short span elements. The bubbles are centered below that span and look great as long as the span isn't broken over two lines.

Looks good:

tell <span>irregular: told, told</span>

Looks bad:

tell <span>irregular: told,
told</span>

It looks bad, because the bubble isn't centered under the span anymore. Is there some way using JavaScript or jQuery to tell, if that span is broken over two lines?

like image 641
iGEL Avatar asked Jan 01 '11 21:01

iGEL


2 Answers

9000's comment is correct. The trick is having access to a <span> that you know will be rendered on a single line. You can do that by wrapping the first word of your block in a span with a specific id, you could also use the last word or some other single word; there are cases where a single word will cross lines but the first word should be safe.

Once you have something that is only on one line you can compare its height to the height of the <span> that will get the tooltip. If the <span> that is getting the tooltip is taller than the single-line <span> then it has wrapped to multiple lines.

Try this jsfiddle:

http://jsfiddle.net/ambiguous/JbMhZ/1/

Adjust the size of the right panes until the red text wraps but the green text doesn't. Then hit Run in the toolbar at the top and it should say this at the bottom of the Result pane:

#has-break spans more than one line
#no-break spans only one line

I'm not exactly proud of this hack but it should work.

I'm left wondering if a better positioning algorithm for your tooltip would be a better idea. Maybe pull the mouse coordinates out of the hover event and use that to position the tooltip rather than positioning it based on the <span>.

like image 138
mu is too short Avatar answered Nov 15 '22 12:11

mu is too short


I think the nicer way to do this would be with white-space: nowrap in CSS:

CSS:

span.bubble {
    white-space: nowrap;
}

HTML:

tell <span class="bubble">irregular: told, told</span>
like image 1
lonesomeday Avatar answered Nov 15 '22 11:11

lonesomeday