Anna_B
Anna_B

Reputation: 900

jQuery: font-variation-settings based on cursor position

I would like to transform a variable font based on the position of the cursor. If the cursor has a x position of 0px, the wght should be 200, if the cusor position is at the right border of the page, the wght should be 800. The transition has to be fluid.

This is my start:

$(document).on("mouseover", function(e){
if(e.pageX <= 100)
{
$("div").css( "font-variation-settings", "'wght' 200" )
}
if(e.pageX >= 100)
{
$("div").css( "font-variation-settings", "'wght' 800" )
}
});
body {
margin: 0;
padding: 0;
width: 100vw;
height: 100vh;
display: flex;
align-items: center;
justify-content: center;
font-family: 'Muli', sans-serif;
font-size: 5vw;
font-variation-settings: 'wght' 400;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<link href="https://fonts.googleapis.com/css2?family=Muli:[email protected]&display=swap" rel="stylesheet">

<div>Weight based on cursor position</div>

Who can help me? Would be very thankful. :)

Upvotes: 0

Views: 254

Answers (1)

Balastrong
Balastrong

Reputation: 4474

As smooth as possible :P

$(document).on("mousemove", function(e) {
  let factor = e.pageX / $(document).width();
  let wght = 200 + 600 * factor;
  
  $("div").css("font-variation-settings", "'wght' " + wght)
});
body {
  margin: 0;
  padding: 0;
  width: 100vw;
  height: 100vh;
  display: flex;
  align-items: center;
  justify-content: center;
  font-family: 'Muli', sans-serif;
  font-size: 5vw;
  font-variation-settings: 'wght' 400;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<link href="https://fonts.googleapis.com/css2?family=Muli:[email protected]&display=swap" rel="stylesheet">

<div>Weight based on cursor position</div>


UPDATE: Added a delay to optimize it a bit.

let enableHandler = true;

timer = window.setInterval(function() {
  enableHandler = true;
}, 50);

$(document).on("mousemove", function(e) {
  if (enableHandler) {
    let factor = e.pageX / $(document).width();
    let wght = 200 + 600 * factor;

    $("div").css("font-variation-settings", "'wght' " + wght)
    enableHandler = false;
  }
});
body {
  margin: 0;
  padding: 0;
  width: 100vw;
  height: 100vh;
  display: flex;
  align-items: center;
  justify-content: center;
  font-family: 'Muli', sans-serif;
  font-size: 5vw;
  font-variation-settings: 'wght' 400;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<link href="https://fonts.googleapis.com/css2?family=Muli:[email protected]&display=swap" rel="stylesheet">

<div>Weight based on cursor position</div>

Upvotes: 2

Related Questions