Change font using a button
SolvedCaetera Posted messages 234 Registration date Status Member Last intervention -
Hello,
I would like to code a button on my site, a button that would allow me to switch the chosen font (Tongari) to a secondary one (OpenDyslexic - designed for dyslexic individuals). I would like that when this button is clicked, the text on the page, written in Tongari, changes to OpenDyslexic and vice versa; if the button is clicked again, the text returns to Tongari.
I have no coding training; usually, I fumble around with the developer console, but here I don't know how to proceed.
I was planning to use the onclick event (I don't know if we can call it an event here) and the FontFaceSet attribute, but without success so far.
Thank you in advance.
7 answers
-
Hello,
Yes, you can use a function on an onclick event to change the style of an element or the entire document
document.body.style.fontFamily = "courier" // or to select a specific element document.querySelector('.ta-classe')
-
Hello,
Thank you for the response, unfortunately it doesn't work, I don't understand why.
Maybe it's because I set the Tongari font in CSS and there's a conflict somewhere?
I also tried:document.getElementsByTagName("p")Without success either, by writing it this way:
document.getElementsByTagName('p').style.fontfamily = 'OpenDyslexic' -
Here is my CSS:
@font-face { font-family: 'Tongari'; src: url('https://static1.squarespace.com/static/5d6ffee77121db00017382cf/t/5fadb1f5dd1d4d0520e6013f/1605218805377/tongari-regular.woff') }; h1, h2, p { font-family: 'Tongari'; color: white; }I'd like to point out that I use Squarespace
I have correctly integrated and defined the OpenDyslexic font as follows:@font-face { font-family: 'OpenDyslexic'; src: url('https://static1.squarespace.com/static/5d6ffee77121db00017382cf/t/63642c053e07f53779e987b8/1667509253648/OpenDyslexic-Regular.otf') };And regarding the button itself, I used the onclick event like this:
onclick="document.getElementsByTagName('p').style.fontFamily = 'OpenDyslexic'"-
Ok thanks!
So for the font usage, I recommend this:
body { font-family: 'Tongari'; } h1, h2, p { color: white; }That way you only have one element to target with your JS
onclick="document.querySelector('body').style.fontFamily = 'OpenDyslexic'"because your getElementsByTagName returns an array of elements, you would need to apply the .style to each of them!
I hope it's clearer now.
(and it's fontFamily with a capital)
-
-
Oh great! It works very well, thank you very much
I would like to go a little further, is it possible to click again to return to the original font?
Perhaps I need to write a function for that?
For now, I have defined onclick like this: (ID being AdaptFont)onclick="document.querySelector('body').style.fontFamily = 'OpenDyslexic' ; document.getElementById('AdaptFont').innerHTML = 'Read with Tongari' ; document.getElementById('AdaptFont').style.fontFamily = 'Tongari'"I was wondering if it's possible to add something to reset the button, a kind of "click again" or "unclick"
Is it possible to add "temporality" to onclick? Could the following line reset the event?
document.getElementById('AdaptFont').onclick = null -
I attempted a function but without success, I am not comfortable, I don't really know how to parameterize them however I tried this, without success, the error that is returned to me is "script disabled":
<script type="text/javascript"> function FonctionFont('AdaptFont') { if (document.querySelector('body').style.fontFamily = 'Tongari') { document.querySelector('body').style.fontFamily = 'OpenDyslexic' ; document.getElementById('AdaptFont').innerHTML = 'Lire avec Tongari' ; document.getElementById('AdaptFont').style.fontFamily = 'Tongari'; } else { document.querySelector('body').style.fontFamily = 'Tongari' ; document.getElementById('AdaptFont').innerHTML = 'Lire avec OpenDyslexic' ; document.getElementById('AdaptFont').style.fontFamily = 'OpenDyslexic'; } } </script>Having set the onclick event like this:
onclick="FonctionFont('AdaptFont')"-
Two things about your code:
- In the "if" statement, you need to do a comparison (== or ===) and not an assignment (=)
- You have included a parameter in the function but you are not using it:
onclick="maFonction('truc')" // and retrieve it with function maFonction(variableTruc) { element.blabla.fontFamily = variableTruc }// or more simply a toggle onclick="toggle()" function toggle() { if font == A: assign font B else assign font A } // and another function to reset onclick="reset()" // in which you set the default font
-
-
Thank you very much, it works, everything is fine! Great
I used the toggle with onclick=toggle()
In the if is there a difference between == and ===? Roughly speaking, is it the same thing?
Ok, I understand the unused parameter in the function, thank you for all these clarifications and the time you dedicated to me :)-
Hello,
the difference between == (checks for equality) and === (checks for strict equality) is that equality with == is more lenient than strict equality.
For example, with a "simple" equality, if both sides (on the left and right of the double equal) are equal but with some tolerance in the comparison:
'0' == 0 //-- compares the string '0' and the number 0 ==> returns true
whereas
'0' === 0 //-- a string is different from a number ==> returns false
This is just an example illustrating the difference between "simple" equality and strict equality, but there are many other cases where double equals is more permissive and triple equals requires that both terms of the comparison be strictly identical. So both have their usefulness depending on the context (being more permissive for testing or requiring strict equality of terms).
The parameter is what is in brackets. It should be a variable and not a string. It is unnecessary if not used.
<span>FonctionFont('AdaptFont')</span>Instead of naming your functions FontionsFont, give names that mean something; a function is easily recognizable at creation since it is preceded by the keyword "function" and when used, the name is followed by parentheses with or without parameters: FonctionFont(); or FonctionFont('string');
For example, here:
function changerFont(){
//-- what the function does ...
}
and upon rereading even in several months (or by someone else) it is easy to understand what the function does. It's a simple and practical habit that makes the code easily readable and understandable, so why not take advantage of it.
Example of a function using a parameter correctly (and explicitly by the way):
function remplacerFont(nouvellePolice){ document.querySelector('body').style.fontFamily=nouvellePolice } //-- used like this: remplacerFont('arial')/** assigns to the body the style font-family='arial' and replaces or supersedes the previous one */Note: it's better to use .addEventListener (rather than the onclick attribute) and to use classes to change the style, as already indicated by Grandasse_
Both are more flexible, clearer, and easier to change.
Use addEventListener because the code is not separated into 2 parts (one in the script tags and the other as an HTML tag attribute); moreover, by using a named function, you can change or remove what the button does, for example, by replacing the function with another in the addEventListener (it seems to me that using a toggle was your first idea before). This is not really feasible in HTML element attributes (unless you want to complicate things).
By using one class for one font and another for the other, you only need to change the CSS to change the font, and you can also add other CSS properties.
Also note that it is important, if you use exotic or unconventional fonts (like here), to add fallback fonts.
If the user does not have the Tongari or OpenDyslexic fonts on their computer, it is completely useless since they won't see any of the fonts.
Therefore, by changing the CSS class, it becomes simpler:
.policeBase{
font-family: tongari, arial;
}
.policeAlternative{
font-family: OpenDyslexic, times;
}
And so the expression in the function becomes:
document.querySelector('body').className=policeAlternative;
And to revert (and in a toggle):
document.querySelector('body').className=policeBase;
It's simpler (and faster to type) than having to rewrite the 2 fonts each time using .style.fontFamily=...
-
-
Thank you for all these details, it is very much appreciated.