Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamically load external css resources model side

Tags:

css

aurelia

I need to dynamically load external css resource to change font family of the page.

In my SPA the user chooses the font family he prefers for the UI. So he copy/paste the font family from https://fonts.google.com into an input tag and I need to change accordingly the page font-family property.

In order to do this, I need to load the external resource of the font such as <link href="https://fonts.googleapis.com/css?family=<FONTFAMILYNAME>" rel="stylesheet"> and then change the css assigning font-family: 'Indie Flower', cursive; to the page, that is not a problem using css binding.

How can I do this from the model side?

UPDATE

The app is developed with Aurelia js framework, so I mean the Aurelia model, but (still in client-side)

like image 938
somejhereandthere Avatar asked Feb 27 '26 07:02

somejhereandthere


1 Answers

Hope It is what you expected

let btn = document.getElementById("btn");
let inpt = document.getElementById("inpt");
let fontsLink = document.getElementById("fontsLink");
btn.addEventListener('click', function() {
    let font = inpt.value;
    font = font.trim();
    font = font.replace(/ /g, '+');
    let link = `
        https://fonts.googleapis.com/css?family=${font}
    `
    fontsLink.href = link;
    document.querySelector('body').style.fontFamily = `${inpt.value}`;
});
* {
    box-sizing: border-box;
    font-family: inherit;
}

html {
    font-size: 62.25%;
}

body {
    font-family: sans-serif;
    font-size: 1.6rem;
}
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Hello World From Gaurav</title>
    <link rel="stylesheet" href="" id="fontsLink">
</head>
<body>
    <h1 id="demo" contenteditable="true">Change Text</h1>
    <input id="inpt" type="" placeholder="Type Font Name">
    <button id="btn">Load</button>
</body>
</html>
like image 67
Gaurav Bhardwaj Avatar answered Mar 01 '26 20:03

Gaurav Bhardwaj



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!