I’m trying to implement buttons in order to allow users to increase/decrease font size on a website.
This is the website: https://font-size-d27117.webflow.io/
I use REM everywhere, for font and for images. I’d like to change only font sizes, but not images.
I’ve found the script. It seems to be simple but doesn’t work.
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
$('#font-size-plus').on('click', function()
{
var fontSize = $('body').css('font-size');
console.log(fontSize);
var newFontSize = parseInt(fontSize) + 1;
$('body').css('font-size', newFontSize + 'px')
})
$('#font-size-minus').on('click', function()
{
var fontSize = $('body').css('font-size');
var newFontSize = parseInt(fontSize) - 1;
$('body').css('font-size', newFontSize + 'px')
})
$('#_reset').on('click', function() {
$('body').css('font-size', '1')
})
</script>
In the above script I see px instead of rems.
I tried to change PX to REM and step from 1px to 0.1rem
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
$('#font-size-plus').on('click', function()
{
var fontSize = $('body').css('font-size');
console.log(fontSize);
var newFontSize = parseInt(fontSize) + 0.1;
$('body').css('font-size', newFontSize + 'rem')
})
$('#font-size-minus').on('click', function()
{
var fontSize = $('body').css('font-size');
var newFontSize = parseInt(fontSize) - 0.1;
$('body').css('font-size', newFontSize + 'rem')
})
$('#_reset').on('click', function() {
$('body').css('font-size', '1' + 'rem')
})
</script>
None of these scripts work.
Could anyone help?
2
Answers
I've implemented @Lionel Rowe advice. IT seems to work. Final effect: font-size-d27117.webflow.io
You have 2 main problems:
$(() => { ... })
, which causes it to run only once the DOM is loaded.body
, nothtml
.rem
units are based on the root size, which for an HTML document is thehtml
element.There are a few other issues in your code (invalid HTML etc.), but here’s a simplified version that works:
Note that setting the font size on
html
affect all measurements that userem
values, regardless of whether they’re font sizes, images, etc. You can see this difference in thediv
housing the control buttons themselves, which sets its font size inpx
instead so always remains at the same font size.