0

I currently have a problem related to jQuery.

For the whole story, I'm creating some tooltips, I center them right under the desired trigger using css.

Everything is working, but here is the problem : I have a <p> tag with some text in it.

The tooltip is generated by the first word of the string, and because of the alignment, the first half of the tooltip is outside of the viewport.

So it looks like this : Tooltip is outside the viewport

And I want to be able to target the first-word with jQuery, in order to write something like :

if( isFirstWord == true ) {
    tooltip.css('left','xx%')
}

That will let me position the tooltip properly, only if it belongs to the first word.

I hope you guys got my question, if not, just drop a comment, I'll be glad to give you more informations about it.

LukyVj
  • 1,495
  • 2
  • 11
  • 18

1 Answers1

1

One way:

$('something').each(function(){
     var me = $(this);
     me.html(me.html().replace(/^(\w+)/, '<span>$1</span>'));
});

Basically, for each match (something) you replace the first word with itself ($1) wrapped in tags. The character class \w matches letters, digits, and underscores (thus defining what a "word" is - you may need another definition).

The solution already exist here: First Word in String with jquery

Community
  • 1
  • 1
MartaGom
  • 501
  • 6
  • 27
  • Well, thank you for your prompt response, I tried your solution, but it seems that it wrap only the first word of the first `p` tag, even if there is more than 1 `p` tag. I would like to get all the first words, of all the `p` tags. But your solution is helping me, I will work around it to find the proper function to apply. Thank you ! – LukyVj Dec 08 '14 at 12:46
  • ¡Ah! I understand you now... Ok. – MartaGom Dec 08 '14 at 12:51