How to create buttons to increase/decrease font?

Asked

Viewed 6,529 times

8

I would like to implement accessibility functions on the website of the company I work with.

I was able to implement the contrast button, but I’m having difficulty doing the increase/decrease and standard font size.

Doing tests on new projects the scripts I created/found on the internet work, but on the site no, I don’t know if something is interfering, but it doesn’t work. Can someone help me?

Below the code I made for contrast:

if (localStorage.getItem('accessibility') == 'on') {
  $("body").addClass("accessibility");
}
$(".contrasteOn").click(function() {
  localStorage.setItem('accessibility', 'on');
  $("body").addClass("accessibility");
});
$(".contrasteOff").click(function() {
  localStorage.setItem('accessibility', null); 
  $("body").removeClass("accessibility");
});

To change the colors I include in the CSS all the classes I wanted to change with the .accessibility before.

  • Post here the code you made for the contrast.

  • if (localStorage.getItem('Accessibility') == 'on') { $("body"). addClass("Accessibility"); } $(".contrasteOn"). click(Function() { localStorage.setItem('Accessibility', 'on'); $("body").addClass("Accessibility"); }); $(".contrasteOff"). click(Function() { localStorage.setItem('Accessibility', null); $("body").removeClass("Accessibility"); }); To change the colors I include in css all classes q I wanted to change with . Accessibility before

  • To add code or add information to your question click on Edit to edit your question, ;)

  • Poessoal how I put this script on the site

5 answers

9

I’m using the previous answer and adapting it to a script that works for all tags, including those belonging to a Parent within the element itself.

In this case, one should only choose a parent element where changes in font size should happen, in my example is the #content:

var $btnAumentar = $("#btnAumentar");
var $btnDiminuir = $("#btnDiminuir");
var $elemento = $("body #content").find("*"); //encontra todos os elementos dentro do #content
var fonts = [];

function obterTamanhoFonte() {
  for (var i = 0; i < $elemento.length; i++) {
    fonts.push(parseFloat($elemento.eq(i).css('font-size')));
  }
}
obterTamanhoFonte();
$btnAumentar.on('click', function() {
  for (var i = 0; i < $elemento.length; i++) {
    ++fonts[i];
    $elemento.eq(i).css('font-size', fonts[i]);
  }
});

$btnDiminuir.on('click', function() {
  for (var i = 0; i < $elemento.length; i++) {
    --fonts[i];
    $elemento.eq(i).css('font-size', fonts[i]);
  }
});
h3{
  font-size: 24pt;
}
p{
  font-size: 14pt;
}
a{
  font-size: 10pt;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src=""></script>

<button type="button" id="btnAumentar">Aumentar fonte</button>
<button type="button" id="btnDiminuir">Diminuir fonte</button>

<div id="content">
  <h3>Neque porro quisquam</h3>
  <p>Neque porro quisquam est qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit...
    <a>Neque porro quisquam est qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit...</a>
  </p>
</div>

3

As I saw that you are using jQuery in your code I made an example:

You can get the font size of the element you want, class or whatever, and at the click of the button increase or decrease the font.

var $btnAumentar = $("#btnAumentar");
var $btnDiminuir = $("#btnDiminuir");
var $elemento = $("body p");

function obterTamnhoFonte() {
  return parseFloat($elemento.css('font-size'));
}

$btnAumentar.on('click', function() {
  $elemento.css('font-size', obterTamnhoFonte() + 1);
});

$btnDiminuir.on('click', function() {
  $elemento.css('font-size', obterTamnhoFonte() - 1);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<button type="button" id="btnAumentar">Aumentar fonte</button>
<button type="button" id="btnDiminuir">Diminuir fonte</button>
<p>Neque porro quisquam est qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit...</p>

  • then but and to get all the fonts ? I’ll have q fzr this for all the tags on my page ?

  • @Herculesmacedo in case this code will change the source of all tags <p>. To also change tags <blockquote> for example, you can use it like this: var $elemento = $("body p, blockquote");. But testing with h1 and h2 for example did not work... it ends up transforming the source of h1 equal to that of the p. I even set a font-size pro value h1 by CSS, but it didn’t. Do you know why Pedro? You can also change the h's with this script? + 1

  • 1

    @Pedro , I ask license to use your answer and adapt it to a script that works for all tags.

  • @Hercullesmacedo, look at the answer and see if it suits you.

  • then @Samirbraga, I tested on the site and some tags n changed tbm, then talking to a teacher of an EAD course I managed to do with another code q I will post below

1

$(document).ready(function () {
    var section = new Array('span', 'li', 'b', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'p', 'table', 'div');
    section = section.join(',');

    // Reset Font Size
    var originalFontSize = $(section).css('font-size');
    $(".resetFont").click(function () {
        $(section).css('font-size', originalFontSize);
    });

    // Increase Font Size
    $(".increaseFont").click(function () {
        var currentFontSize = $(section).css('font-size');
        var currentFontSizeNum = parseFloat(currentFontSize, 5);
        if (currentFontSizeNum < 20) {
            var newFontSize = currentFontSizeNum * 1.2;
            $(section).css('font-size', newFontSize);
        }
        return false;
    });

    // Decrease Font Size
    $(".decreaseFont").click(function () {
        var currentFontSize = $(section).css('font-size');
        var currentFontSizeNum = parseFloat(currentFontSize, 5);
        if (currentFontSizeNum > 10) {
            var newFontSize = currentFontSizeNum * 0.8;
            $(section).css('font-size', newFontSize);
        }
        return false;
    });
});

His problem is that the reset is not bringing the pattern back to the site

Then I thought to use the reset to reload the CSS file

But n know mt well as fzr this, oq tried Aki n worked mt well

0

I’d settle it this way. - Javascript to add a class to your body/html to be used as the master selector that determines the font - Css controlling affected elements.

// css
body.fontSize10 {
  h1 {
    font-size: 10px;
  }
}

body.fontSize11 {
  h1 {
    font-size: 11px;
  }
}

body.fontSize12 {
  h1 {
    font-size: 12px;
  }
}

// js /jquery
$(function ($) {

  $('body').data('fontSize', 0)

  function UpdateFontSize() {
    var $body = $('body')
    var fz = $body.data('fontSize')
    var bodyClass = 'fontSize'+ fz ? fontSize.toString() : ''
    if (fz > 0){
      $body.addClass(bodyClass)
    }
  }

  $('#incrementFontSize').on('click', function (e) {
    var $body = $('body')
    var fz = $body.data('fontSize')
    $body.removeClass('fontSize'+fz).data('fontSize', fz + 1)
    UpdateFontSize()
    e.preventDefault()
  })

  $('#decrementFontSize').on('click', function (e) {
    $body.removeClass('fontSize'+fz).data('fontSize', fz - 1)
    UpdateFontSize()
    e.preventDefault()
  })

})()

in this way, vc can more easily control the elements affected by the source increment/decrease.

Doing all this only with js can be very slow, and you may need to do several Ifs in the middle of the code. Maintenance will be much more boring, besides when adding a new element in html, you will have to change your javascript.

Through css you can control all elements only with css.

-1

I had to do it once on a project, see if it fits you:

function strReplace(haystack, needle, replacement) {
    var temp = haystack.split(needle);
    return temp.join(replacement);
}

 $(document).ready(function(){

    var div = '#content',
        contador = 0,
        obj_tratados = [
                        div,
                        div + ' p',
                        div + ' h1'
                       ],
        reset_fonte = [],
        reset_linha = [];

    setDefaultZoom(obj_tratados, reset_fonte, reset_linha, contador);

    $('#a_mais,#a_menos,#a_reset').on('click', function() {
       var id = $(this).attr('id');
        var min = 9;
        var max = 28;

        for (var i in obj_tratados) {

            var tratados = $(obj_tratados[i]);
            var tamanho_fonte = strReplace(tratados.css('fontSize'), 'px', '');
            var tamanho_entrelinha = strReplace(tratados.css('lineHeight'), 'px', '');

            switch (id) {
                case 'a_mais':
                    if (tamanho_fonte <= max) {
                        tamanho_fonte++;
                         // tamanho entrelinha aumento
                         tamanho_entrelinha = (tamanho_fonte * 1.8);
                         tamanho_entrelinha++;
                        contador++;

                    }
                    break;
                case 'a_menos':
                    if (tamanho_fonte >= min) {
                        tamanho_fonte--;
                       // tamanho entrelinha redução;
                        var val = tamanho_entrelinha - (tamanho_entrelinha * 3 / 100);
                       // tamanho_entrelinha = arredondarValor(val);
                       tamanho_entrelinha = (tamanho_fonte * 1.8);
                        tamanho_entrelinha--;
                        contador++;

                    }
                    break;
                case 'a_reset':
                default:
                    // resetar 
                    tamanho_fonte = reset_fonte[i];
                    tamanho_entrelinha = reset_linha[i];
                    break;
            }
            tratados.css({'fontSize': tamanho_fonte + 'px', 'lineHeight': tamanho_entrelinha + 'px'});
        }
       //cancel a click event
        return false;
    });

    function setDefaultZoom(obj_tratados, reset_fonte, reset_linha, contador) {
        for (var i in obj_tratados) {

            var tratados = $(obj_tratados[i]);
            if (contador == 0) {
                reset_fonte[i] = strReplace(tratados.css('fontSize'), 'px', '');
                reset_linha[i] = strReplace(tratados.css('lineHeight'), 'px', '');
            }
        }
    }
});

HTML:

<span id="controle_zoom">
   <a href="javascript:void(0);" id="a_reset">A</a> | <a href="javascript:void(0);" id="a_mais">A+</a> | <a href="javascript:void(0);" id="a_menos">A-</a>
</span>

<div id="content">
  <h1>Título</h1>
    <p>O texto vem aqui</p>
</div>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.