Customizing individual characters within HTML text using the mouse's current location

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!

Answer №1

After restructuring your code, I've provided a working example for you. Instead of hard-coding the quantity of characters, create an array based on your class single-char and then loop through it.

I've left a comment on your calculateDistance() function regarding the slightly funky math. However, this example will demonstrate how all characters are affected.

$(document).mousemove(function(e) {
  var mX = e.pageX;
  var mY = e.pageY;
  $('.single-char').each(function(){
    $(this).css({'font-size': calculateDistance(this, mX, mY) + 'px'});
  });                    
});

You can target all the characters with $('common-class') and then loop through them using .each().

I hope this explanation is helpful :)

This additional code snippet has been included to further assist you based on a follow-up comment.

function arrayMe(string){
$(string).each(function() {
var myStr = $(this).html();
myStr = myStr.split("");
var myContents = "";
for (var i = 0, len = myStr.length; i < len; i++) {
myContents += '<span class="single-char char-' + i + '">' + myStr[i] + '</span>';
}
$(this).html(myContents);
console.log(i);
});
}

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)));
return mouseX;
}


$('document').ready(function() {
var myStringType = $('.sample-text');
arrayMe(myStringType);

$('.single-char').hover(function(e) {
var charNumber = $(this).attr('class').split('-')[2];
$('.single-char').each(function(){
$(this).css({'font-size': 12 + 'px'});
}); 
$(this).css({'font-size': 36 + 'px'});           
});
});
.single-char:hover {
color:red;
cursor:pointer;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p class='sample-text hover-letter'>This sample text turns red, character by character, when you hover over it with your mouse.</p>

This second follow-up snippet is provided to showcase the intricacies of the math involved.

function arrayMe(string){
$(string).each(function() {
var myStr = $(this).html();
myStr = myStr.split("");
var myContents = "";
for (var i = 0, len = myStr.length; i < len; i++) {
myContents += '<span class="single-char char-' + i + '">' + myStr[i] + '</span>';
}
$(this).html(myContents);
console.log(i);
});
}

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').ready(function() {
var myStringType = $('.sample-text');
arrayMe(myStringType);

$('.single-char').hover(function(e) {
var mX = e.pageX;
var mY = e.pageY;
var charNumber = $(this).attr('class').split('-')[2];
$('.single-char').each(function(){
$(this).css({'font-size': calculateDistance($(this), mX, mY) + 'px'});
});      
});
});
.single-char:hover {
color:red;
cursor:pointer;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p class='sample-text hover-letter'>This sample text turns red, character by character, when you hover over it with your mouse.</p>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Using jQuery's .remove() function removes all of the children from the container, rather than just one at

For my latest project, I am focused on creating a seamless full-page transition using AJAX calls. The challenge I'm facing is removing content from the DOM when loading in a new page. Despite adding a unique class or ID to the element, the .remove() f ...

To ensure that new tabs are opened directly within jQuery UI tabs, the tab should be created within the jQuery UI tabs interface

I have integrated jquery-UI to create a dynamic Tab panel. When I click on the "Add Tab" button, a new tab is created. However, the new tab does not open automatically. It only opens when clicked on. $(function() { var tabTitle = $( ...

Locate the Next Element Based on its Tag Name

CSS <div> <a href=''> Red </a> </div> <div> <div> <a href=''> Blue </a> </div> </div> <a href=''>Green</a> JavaScript $(document).ready(f ...

Responsive YouTube video player with adjustable width and fullscreen functionality

I am currently attempting to embed a YouTube video on my website bearblog. My objective is to make the video adaptable in width for both mobile and computer viewing, while also enabling the YouTube fullscreen feature. I have followed the guidelines provid ...

Error: The function initMap() is not recognized in the Google Maps API

I have been experimenting with the Flickr API and I'm currently working on asynchronously loading images along with their metadata. To accomplish this, I have a script that utilizes three AJAX calls: $(document).ready(function() { var latLon = { ...

Do AJAX requests hinder performance and how long do they typically last?

Even though I have experience in web development, I still find myself feeling a bit uneasy asking these basic questions. However, I believe it's always good to verify my assumptions... In my application, I am working on recording unique image views. ...

The Javascript function fails to trigger during the OnKeyPress and OnKeyDown events

I have encountered an issue while trying to call a function called validateQty on both the onkeypress and onkeydown events of a text input field. When I was passing only one parameter, which is the event itself, everything was working perfectly fine. Howev ...

How do I trigger a click event on an autocomplete search bar in Vue with a router link enabled?

I'm working on an app that is similar to Github, and I want to create a search bar functionality just like Github's. However, I'm facing an issue with my search bar located in the navbar option section as it doesn't seem to register any ...

Creating a dynamic dropdown menu that changes based on the selection from another dropdown menu

I'm working on a project that requires users to make specific selections in dropdown menus that are interconnected. Does anyone know how to set up a form so that the options in dropdown menu #2 change based on what the user selects in dropdown menu #1 ...

Executing PHP code within the .html() jQuery function

Are you trying to update a link's text content dynamically using jQuery? <a id="btnExistReceiver" class="btn btn-app"> <i class="fa fa-user"></i> <?= __('Existing Receiver') ?> ...

What are some tips to speed up image loading times?

Is there a way to optimize the loading speed of these images? In my loop that displays profile pictures, the photos take between 1 to 2.5 seconds to load all at once. I attempted resizing with PHP, but it had minimal impact on the load time. How can I prel ...

The ng-controller (dropdown menu) is functioning properly when tested locally and on JSFiddle, however, it is not working on

My HTML website with ng-app is functioning properly when tested locally and on certain coding platforms like JSFiddle and CodePen. However, it seems to encounter issues when deployed on Google Sites, Github, W3, and similar websites. The main functionalit ...

An error has been noticed: "Unexpected token o" - Syntax is not

I'm currently developing a web application and have encountered an issue: $("#post").click(function () { var u = $('#u').val(); var j = $('#j').val(); $.post("http://www.myweb.php", { u: u, j: ...

Uploading and Editing Images Using the DropZone Plugin in Laravel JS

Looking to enhance my project by implementing dropzone for image CRUD operations. I've successfully handled image creation, but struggling with editing existing images. Below is the code snippet where I fetch and upload existing images. Dropzone.autoD ...

When adding values, they remain in their original positions

I am populating a select dropdown with options using AJAX. These options are added based on the selection made in another dropdown. The first function that appends the data: var appendto_c = function(appendto, value, curcode) { appendto.append("& ...

Troubles with flexibility in image placement

I am working on adjusting my design to accommodate smaller screen sizes where elements may shift to a second line. I want these elements to align to the left instead of being centered. The image below illustrates my goal: https://i.sstatic.net/CzX5V.png C ...

Having trouble getting drag and drop functionality to work in Firefox with my current solution

I have successfully added drag and drop functionality to my website for images. The drag and drop feature is working well, but now I need to save the dropped images to the server. I have included image data as hidden elements in the view so that I can acce ...

Can a javascript variable be accessed after loading an iframe and returning to the page?

Using a jquery plugin known as colorbox, my colorbox simply opens an iframe on the screen. This detail may not be relevant, as the core issue at hand is that I have 3 variables on my parent window that are retrieved from an AJAX call using jquery: data.re ...

How can the target pseudo-class be utilized to replace the 'active' state on navigation across several pages effectively?

Within a large application, I am managing a micro site and looking to implement tertiary navigation with an active state for pages. This involves inserting a single html blob into multiple pages. My goal is to use an active class to highlight the page in ...

Why does the appearance of my PHP spreadsheet change when I attempt to print it?

After using a CSS stylesheet to position my textboxes correctly, I noticed that in Chrome everything appeared fine. However, when attempting to print the site (Ctrl+P), each sentence and textbox shifted. How can I ensure they remain in place? <!-- #cap ...