Reputation: 187
Based on my previous question seen here: Split word into letter and get data of each letter? I'm trying to work out a way to split the sentence into words as divs beforehand.
The current code is as follows:
const target = document.querySelector('.target');
target.innerHTML = target.textContent
.replace(/\w/g, '<span data-b-text="$&">$&</span>');
The fiddle I've attempted based on other answers I've found: https://jsfiddle.net/xyp3cn37/7/
The result I'm trying to achieve is:
<h1 class="rotate tk-ad">
<span class="target">A Word</span>
</h1>
to:
<h1 class="rotate tk-ad">
<span class="target">
<div>
<span data-glitch="A">A</span>
</div>
<div>
<span data-glitch="W">W</span><span data-glitch="o">o</span><span data-glitch="r">r</span><span data-glitch="d">d</span>
</div>
</span>
</h1>
I'm then rotating each individual letter (this is working, so no real need to include that code) to result in:
However, on smaller screens, this happens due to the HTML only seeing each letter, not each word:
Upvotes: 1
Views: 655
Reputation: 36703
While settinf the html of the .target
you can first split the string based on spaces and then split it on each character and build the string.
$(function() {
$(".target").html(function() {
return $(this).html().split(" ").map(word => {
return '<div>' + word.split("").map(alphabet => {
return '<span data-glitch="'+alphabet+'">' + alphabet + '</span>';
}).join("") + '</div>';
})
})
});
div {
margin: 20px;
}
span {
padding: 0 20px;
color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h1 class="rotate tk-ad">
<span class="target">A Word</span>
</h1>
Upvotes: 0
Reputation: 370699
You can achieve this with two regular expressions - one to match the words, and then use a replacer function to replace each character in the word with a span
. First match \w+
(not just \w
, that'll only match one character) to match all words, then replace each character in the word with /./g
:
const target = document.querySelector('.target');
target.innerHTML = target.textContent
.replace(/\w+/g, (word) => (
'<div>' +
word.replace(/./g, '<span data-glitch="$&">$&</span>') +
'</div>'
));
console.log(target.innerHTML);
div {
border: 1px solid black
}
<span class="target">A Word Here</span>
Upvotes: 1