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 :
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.
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
Related
Is it possible to move text to the next line after a full stop?
For example with a standard h1 header - 'This is a very. Very. Big header.'
But I want my headers to move to the next line after a fullstop -
'This is a very.
Very.
Big header.'
My goal is to have every title h1 fetched from an API to for formatted so the line wraps every time there is a fullstop '.'
Code:
<div className='quote-wrapper'>
<h1 className='quote'>{currentQuote.quote}</h1>
</div>
I don't believe there is a way this can be achieved as a CSS style or HTML property. Look into word-wrap and text-overflow incase they work for you, though.
In JavaScript, this is easy. Just find all the elements you want to change (like all h1's, get their current text with .innerText or .innerHtml, and then set their current text to be their old text but replace all the periods with newlines.
document.querySelectorAll("h1").forEach((x) => {
x.innerText = x.innerText.replace(/\./g, "\n")
})
Here, document.querySelectorAll("h1") gets a list of all h1's on the page. You could make it something like ".quote" to select by class, etc.
forEach(...) takes a function (the (x) => {...} thing) and applies it to each item in the list.
In our function x.innerText is the text inside the h1 element and replace replaces everything matching the first argument (/\./g) with the second argument ("\n"). Here, /\./g is the regular expression for "all periods" and "\n" is the newline character.
Edit:
It looks like you are using React so you don't actually need to do anything with a querySelector. Just perform the replace on currentQuote.quote right before you put it into the DOM
You can do it by using the split method.
Here is how i did it.
https://code.sololearn.com/W85wKQly9I7a/?ref=app
I want to detect and style a special letter .
for example something like this
:
body["p"] /
body["2"]
how can I do this?
thanks
You could do this on a node-by-node basis with a fairly simple replace, but it wouldn't scale very well.
Given the markup:
<p>Peter Rabbit ate all of Potter's pickling cukes.</p>
If you wanted to add a style to all of the letters p in this text, you could select the paragraph node and add spans around any p (assuming a single paragraph):
var graf = document.getElementsByTagName('p')[0];
graf.innerHTML = graf.innerText.replace(/(p)/gi,'<span class="fancy">$1</span>');
That said, this would only work on plain text nodes; if you had, for example, a span tag already in the p tag, it'd get mucked up by the replace.
You cannot with CSS. The only non-element (css-created) pseudo-elements are ::first-line and ::first-letter.
However, you could search with JS through the DOM and create tags around the letters to be highlighted. Check highlight words in html using regex & javascript - almost there for how to do that.
This is a problem I'm running into and I'm not quite sure how to approach it.
Say I have a paragraph:
"This is a test paragraph. I love cats. Please apply here"
And I want a user to be able to click any one of the words in a sentence, and then return the entire sentence that contains it.
You first would have to split your paragraph into elements, as you can't (easily) detect clicks on text without elements :
$('p').each(function() {
$(this).html($(this).text().split(/([\.\?!])(?= )/).map(
function(v){return '<span class=sentence>'+v+'</span>'}
));
});
Note that it splits correctly paragraphs like this one :
<p>I love cats! Dogs are fine too... Here's a number : 3.4. Please apply here</p>
Then you would bind the click :
$('.sentence').click(function(){
alert($(this).text());
});
Demonstration
I don't know if in English : is a separator between sentences. If so, it can be added to the regex of course.
First of all, be prepared to accept a certain level of inaccuracy. This may seem simple on the surface, but trying to parse natural languages is an exercise in madness. Let us assume, then, that all sentences are punctuated by ., ?, or !. We can forget about interrobangs and so forth for the moment. Let's also ignore quoted punctuation like "!", which doesn't end the sentence.
Also, let's try to grab quotation marks after the punctuation, so that "Foo?" ends up as "Foo?" and not "Foo?.
Finally, for simplicity, let's assume that there are no nested tags inside the paragraph. This is not really a safe assumption, but it will simplify the code, and dealing with nested tags is a separate issue.
$('p').each(function() {
var sentences = $(this)
.text()
.replace(/([^.!?]*[^.!?\s][.!?]['"]?)(\s|$)/g,
'<span class="sentence">$1</span>$2');
$(this).html(sentences);
});
$('.sentence').on('click', function() {
console.log($(this).text());
});
It's not perfect (for example, quoted punctuation will break it), but it will work 99% of the time.
Live demo: http://jsfiddle.net/SmhV3/
Slightly amped-up version that can handle quoted punctuation: http://jsfiddle.net/pk5XM/1/
Match the sentences. You can use a regex along the lines of /[^!.?]+[!.?]/g for this.
Replace each sentence with a wrapping span that has a click event to alert the entire span.
I suggest you take a look at Selection and ranges in JavaScript.
There is not method parse, which can get you the current selected setence, so you have to code that on your own...
A Javascript library for getting the Selection Rang cross browser based is Rangy.
Not sure how to get the complete sentense. but you can try this to get word by word if you split each word by spaces.
<div id="myDiv" onmouseover="splitToSpans(this)" onclick="alert(event.target.innerHTML)">This is a test paragraph. I love cats. Please apply here</div>
function splitToSpans(element){
if($(element).children().length)
return;
var arr = new Array();
$($(element).text().split(' ')).each(function(){
arr.push($('<span>'+this+' </span>'));
});
$(element).text('');
$(arr).each(function(){$(element).append(this);});
}
I am sure this is easy but I've looked all over with no luck. I have written a paging jQuery script that animates a list on my page. I have next and previous buttons which I am showing/hiding depending on where you are in the list however it doesnt pick up the position change the first time. Here is my code in jsFiddle:
http://jsfiddle.net/mikeoram/t4787/
I'm sure I'm only missing something simple, all suggestions would be helpful.
Please only answer my question, there are reasons I'm doing it the way I am, and i no it can be done differently.
Thanks,
Mike
First of all, top is a reserved variable that refers to the top window in the hierarchy. Always declare the variables inside functions so it doesn't mess with the rest of your code:
var top = $('.paginate').css('top');
Second, use regex to remove the non digits from the top value, so it will always be a valid integer:
See this http://jsfiddle.net/MaLDK/1/
$('.paginate').css('top'); can return you 0px
If you want to compare numbers do parseFloat( $('.paginate').css('top') );
This will remove non-digits at the end of any string, if there are no characters before the numbers.
I'm trying to get the first letter in a paragraph and wrap it with a <span> tag. Notice I said letter and not character, as I'm dealing with messy markup that often has blank spaces.
Existing markup (which I can't edit):
<p> Actual text starts after a few blank spaces.</p>
Desired result:
<p> <span class="big-cap">A</span>ctual text starts after a few blank spaces.</p>
How do I ignore anything but /[a-zA-Z]/ ? Any help would be greatly appreciated.
$('p').html(function (i, html)
{
return html.replace(/^[^a-zA-Z]*([a-zA-Z])/g, '<span class="big-cap">$1</span>');
});
Demo: http://jsfiddle.net/mattball/t3DNY/
I would vote against using JS for this task. It'll make your page slower and also it's a bad practice to use JS for presentation purposes.
Instead I can suggest using :first-letter pseudo-class to assign additional styles to the first letter in paragraph. Here is the demo: http://jsfiddle.net/e4XY2/. It should work in all modern browsers except IE7.
Matt Ball's solution is good but if you paragraph has and image or markup or quotes the regex will not just fail but break the html
for instance
<p><strong>Important</strong></p>
or
<p>"Important"</p>
You can avoid breaking the html in these cases by adding "'< to the exuded initial characters. Though in this case there will be no span wrapped on the first character.
return html.replace(/^[^a-zA-Z'"<]*([a-zA-Z])/g, '<span class="big-cap">$1</span>');
I think Optimally you may wish to wrap the first character after a ' or "
I would however consider it best to not wrap the character if it was already in markup, but that probably requires a second replace trial.
I do not seem to have permission to reply to an answer so forgive me for doing it like this. The answer given by Matt Ball will not work if the P contains another element as first child. Go to the fiddle and add a IMG (very common) as first child of the P and the I from Img will turn into a drop cap.
If you use the x parameter (not sure if it's supported in jQuery), you can have the script ignore whitespace in the pattern. Then use something like this:
/^([a-zA-Z]).*$/
You know what format your first character should be, and it should grab only that character into a group. If you could have other characters other than whitespace before your first letter, maybe something like this:
/.*?([a-zA-Z]).*/
Conditionally catch other characters first, and then capture the first letter into a group, which you could then wrap around a span tag.