Home > Net >  remove previous link triggered by js
remove previous link triggered by js

Time:10-04

I wrote the code below, to change the font, however, I'm still seeing old fonts in the console:

let font = document.getElementById("font");
if (font) {
  font.addEventListener("change", function () {
    let font = this.value;
    let link = document.createElement("link");
    link.rel = "stylesheet";
    link.href = `assets/css/fonts/${font}.css`;
    document.head.appendChild(link);

    console.log(font);
  });
} else {
  let link = document.querySelector("link[href*='assets/css/fonts/']");
  if (link) {
    link.remove();
  }
}

The HTML code

        <select  id="font" name="font">
            <option value="Arial">Arial</option>
            <option value="Arial Black">Arial Black</option>
            <option value="Comic Sans MS">Comic Sans MS</option>
            <option value="Courier New">Courier New</option>
            <option value="Georgia">Georgia</option>
            <option value="Impact">Impact</option>
            <option value="Lucida Console">Lucida Console</option>
            <option value="Lucida Sans Unicode">Lucida Sans Unicode</option>
            <option value="Palatino Linotype">Palatino Linotype</option>
            <option value="Tahoma">Tahoma</option>
            <option value="Times New Roman">Times New Roman</option>
            <option value="Trebuchet MS">Trebuchet MS</option>
            <option value="Verdana">Verdana</option>
        </select>
    </div>

Console:

enter image description here

my 2 questions:

  • 1- How to remove the previous font when choosing a new one
  • 2- How to save the font into local storage (until the user changes another font)

CodePudding user response:

It may be unnecessary to remove the link and create a new one on every selection, you can just reuse the first created link and then only change its href, like this:

const font = document.getElementById("font");
const setFont = (link, font) => {
  link.href = `https://fonts.googleapis.com/css?family=${font}`;
}
if (font) {
  const link = document.head.appendChild(document.createElement("link"));
  link.rel = "stylesheet";
  // setFont(link, localStorage.getItem('font-family') ?? 'Sans');
  font.addEventListener("change", function () {
    setFont(link, this.value);
    // localStorage.setItem('font-family', this.value);
  });
}
div {
  font-family: Oswald, Silkscreen, Peralta, sans;
  font-size: 2em;
}
<select  id="font" name="font">
  <option value="Sans">Sans</option>
  <option value="Peralta">Peralta</option>
  <option value="Silkscreen">Silkscreen</option>
  <option value="Oswald">Oswald</option>
</select>
<div>Example</div>

Also, the selection value can be saved and retrieved from localStorage as in the comments, it is commented because the localStorage is not available in the sandbox here.

  • Related