Is there a way to manipulate the css properties of individual characters within a text string based on their proximity to the mouse cursor?
If you're interested, check out this Codepen: https://codepen.io/NewbCake/pen/qYXvoo
The concept involves taking a text string and enclosing each character in a span with a general class of 'single-char' along with a distinctive class.
Initially, the text appears like this:
<p class='sample-text hover-letter'>This sample text turns red, character by character, when you hover over it with your mouse.</p>
Then, it gets divided into individual characters as follows:
<span class=“single-char char-0”> T</span>
<span class=“single-char char-1”> h</span>
<span class=“single-char char-2”> i</span>
<span class=“single-char char-3”> s</span>
Javascript Function
function arrayMe(string) {
// Loop through all matching elements
$(string).each(function() {
// Get content of element
var myStr = $(this).html();
// Split myStr into an array of characters
myStr = myStr.split("");
// Construct an html string containing characters wrapped in span tags with classes
var myContents = "";
for (var i = 0, len = myStr.length; i < len; i++) {
myContents += '<span class="single-char char-' + i + '">' + myStr[i] + '</span>';
}
// Replace original content with new constructed html string
$(this).html(myContents);
console.log(i)
});
(function() {
var mX, mY, distance,
$distanceSpan_red = $('#distance_blue span'),
$distanceSpan_blue = $('#distance_red span'),
$element0 = $('.char-0'),
$element1 = $('.char-1');
$element2 = $('.char-2');
$element3 = $('.char-3');
$element4 = $('.char-4');
function calculateDistance(elem, mouseX, mouseY) {
return Math.floor(Math.sqrt(Math.pow(mouseX - (elem.offset().left + (elem.width() / 2)), 2) + Math.pow(mouseY - (elem.offset().top + (elem.height() / 2)), 2)));
}
$(document).mousemove(function(e) {
mX = e.pageX;
mY = e.pageY;
distance0 = calculateDistance($element0, mX, mY);
distance1 = calculateDistance($element1, mX, mY);
distance2 = calculateDistance($element2, mX, mY);
distance3 = calculateDistance($element3, mX, mY);
distance4 = calculateDistance($element4, mX, mY);
$element0.css({'font-size': distance0 + 'px'});
$element1.css({'font-size': distance1 + 'px'});
$element2.css({'font-size': distance2 + 'px'});
$element3.css({'font-size': distance3 + 'px'});
$element4.css({'font-size': distance4 + 'px'});
});
})();
}
// Invoke arrayMe function on page load, targeting elements with "sample-text" class
$('document').ready(function() {
var myStringType = $('.sample-text');
arrayMe(myStringType);
});
I'm looking for ways to make the code adaptable and responsive. Regardless of the amount of text, it should be capable of calculating the distance from the mouse pointer to each letter's unique class and then translating that distance into a corresponding css property value.
Your input and suggestions would be highly valued!