JS Font Animation Fix

User
<script>
(function($) {

$(document).ready(function () {
    var maxDist;
    var mouse = { x: 0, y: 0 };
    var cursor = {
        x: window.innerWidth,
        y: window.innerHeight
    };

    Math.dist = function(a, b) {
        var dx = b.x - a.x;
        var dy = b.y - a.y;
        return Math.sqrt(Math.pow(dx, 2), Math.pow(dy, 2));
    }

    window.addEventListener("mousemove", function(e) {
        
        cursor.x = e.clientX;
        cursor.y = e.clientY;
    });

    window.addEventListener("touchmove", function(e) {
        var t = e.touches[0];
        cursor.x = t.clientX;
        cursor.y = t.clientY;
    }, {
        passive: false
    });

    var Char = function(container, char) {
        var span = document.createElement("span");
        span.setAttribute('data-char', char);
        span.innerText = char;
        container.appendChild(span);
        this.getDist = function() {
            this.pos = span.getBoundingClientRect();
            return Math.dist(mouse, {
                x: this.pos.x + (this.pos.width / 1.75),
                y: this.pos.y
            });
        }
        this.getAttr = function(dist, min, max) {
            var wght = max - Math.abs((max * dist / maxDist));
            return Math.max(min, wght + min);
        }
        this.update = function(args) {
            var dist = this.getDist();
            this.wdth = args.wdth ? ~~this.getAttr(dist, 5, 200) : 100;
            this.wght = args.wght ? ~~this.getAttr(dist, 100, 800) : 400;
            this.alpha = args.alpha ? this.getAttr(dist, 0, 1).toFixed(2) : 1;
            this.ital = args.ital ? this.getAttr(dist, 0, 1).toFixed(2) : 0;
            this.draw();
        }
        this.draw = function() {
            var style = "";
            style += "opacity: " + this.alpha + ";";
            style += "font-variation-settings: 'wght' " + this.wght + ", 'wdth' " + this.wdth + ", 'ital' " + this.ital + ";";
            span.style = style;
        }
        return this;
    }

    var VFont = function() {
        this.scale = false;
        this.flex = false;
        this.alpha = false;
        this.stroke = false;
        this.width = true;
        this.weight = true;
        this.italic = false;
        var title, str, chars = [];

        this.init = function() {
            title = document.getElementById("titlefont2");
            str = title.innerText;
            title.innerHTML = "";
            for (var i = 0; i < str.length; i++) {
                var _char = new Char(title, str[i]);
                chars.push(_char);
            }
            this.set();
            window.addEventListener("resize", this.setSize.bind(this));
        }

        this.set = function() {
            title.className = "";
            title.className += this.flex ? " flex" : "";
            title.className += this.stroke ? " stroke" : "";
            this.setSize();
        }

        this.setSize = function() {
            var fontSize = window.innerWidth / (str.length / 2.7);
            var fontSize = "<?php echo $font_size ?>";
            title.style = "font-size: " + fontSize;
            if (this.scale) {
                var scaleY = (window.innerHeight / title.getBoundingClientRect().height).toFixed(2);
                var lineHeight = scaleY * 0.8;
                title.style = "font-size: " + fontSize + "px; transform: scale(1," + scaleY + "); line-height: " + lineHeight + "em;"
            }
        }

        this.animate = function() {
            mouse.x += (cursor.x - mouse.x) / 4;
            mouse.y += (cursor.y - mouse.y) / 4;
            requestAnimationFrame(this.animate.bind(this));
            this.render();
        }

        this.render = function() {
            maxDist = title.getBoundingClientRect().width / 2;
            for (var i = 0; i < chars.length; i++) {
                chars[i].update({
                    wght: this.weight,
                    wdth: this.width,
                    ital: this.italic,
                    alpha: this.alpha
                });
            }
        }
        this.init();
        this.animate();
        return this;
    }

    var txt = new VFont();
});

})(jQuery);
</script>

above effect not working correctly

Assistant
To help fix the issue, let's go over some **critical problems** and possible **fixes** in your JavaScript logic. From what I see, your variable font interactive effect might not be working due to:

### ❌ Common Issues Detected:

1. **Incorrect `Math.dist` function**:

return Math.sqrt(Math.pow(dx, 2), Math.pow(dy, 2));

This will not compute distance correctly.

2. **`title.style =` overrides previous styles**:
You're overriding the full style string multiple times (`font-size` then `transform`, etc.), which wipes out previous values.

3. **`fontSize` assignment conflict**:
You define `fontSize` from `window.innerWidth` but overwrite it with PHP immediately.

4. **Missing Units on `font-size`**:
If “ is just a number, it lacks the `"px"` unit in:

title.style = "font-size: " + fontSize;

5. **Potential for jQuery conflicts with `document.createElement` flow**:
You're using vanilla JS inside jQuery, which is okay, but make sure nothing is blocking jQuery's `$`.

### ✅ Let's Fix the Key Issues:

#### ✅ 1. Correct the `Math.dist` Function:

Math.dist = function(a, b) {
    var dx = b.x - a.x;
    var dy = b.y - a.y;
    return Math.sqrt(Math.pow(dx, 2) + Math.pow(dy, 2));
}

#### ✅ 2. Fix `fontSize` Setting and Styles:

this.setSize = function() {
    let fontSize = "<?php echo $font_size ?>"; // should be number or include "px"
    if (!isNaN(fontSize)) fontSize += "px";
    title.style.fontSize = fontSize;

    if (this.scale) {
        const scaleY = (window.innerHeight / title.getBoundingClientRect().height).toFixed(2);
        const lineHeight = scaleY * 0.8;
        title.style.transform = `scale(1, ${scaleY})`;
        title.style.lineHeight = `${lineHeight}em`;
    }
}

#### ✅ 3. Don't Wipe Styles in `.draw()`:

this.draw = function() {
    span.style.opacity = this.alpha;
    span.style.fontVariationSettings = `'wght' ${this.wght}, 'wdth' ${this.wdth}, 'ital' ${this.ital}`;
}

#### ✅ 4. Optional: Make Sure You Use a Variable Font:
Ensure the font you’re using (via CSS) supports variable axes `wght`, `wdth`, `ital`, etc.

@font-face {
  font-family: 'YourVariableFont';
  src: url('your-variable-font.woff2') format('woff2');
  font-weight: 100 900;
  font-stretch: 75% 125%;
  font-style: normal italic;
}
#titlefont2 {
  font-family: 'YourVariableFont';
}

### ✅ Final Notes:
– Check console for JS errors (`F12 > Console`).
– Ensure `$text` and `$font_size` are set properly in PHP and output safely.
– Confirm `jQuery` is loaded before this script.

If you want, I can also give you a cleaned-up working version of the entire script using the correct JavaScript and styles. Want that?

Leave a Comment

Your email address will not be published. Required fields are marked *