Skip to content Skip to sidebar Skip to footer

Change Font Size With Javascript

Hello i have this code to change the font size of a paragraph with 3 buttons, i would like to know wich method can i use to not repeat the same lines and make this code more compac

Solution 1:

Try something like this

window.addEventListener('load', inicio, false);

functioninicio(){
var boton1 = document.getElementById('boton1');
var boton2 = document.getElementById('boton2');
var boton3 = document.getElementById('boton3');

boton1.addEventListener('click', function() { setFont("10px");}, false);
boton2.addEventListener('click', function() { setFont("13px");}, false);
boton3.addEventListener('click', function() { setFont("20px");}, false);
} 

functionsetFont(value){
   var parrafo = document.getElementById('parrafo');
   parrafo.style.fontSize= value;
}

Update A different approch (not tested, but should work)

window.addEventListener('load', inicio, false);
functioninicio() {
    var fontDetails = {"boton1" : "10px" , "boton2" : "13px" , "boton3" : "20px"};
    var parrafo = document.getElementById('parrafo');
    var domElement  = "";
    var element  = "";

    for (element in fontDetails)
    {
        domElement = document.getElementById(element);
        domElement.addEventListener('click', function() { parrafo.style.fontSize= fontDetails[element]; }, false);
    }
}

You can also remove the window load event handler and function inicio and try self executing function like this

(function() { //your code here } )();

Solution 2:

Maybe this change can help you:

window.addEventListener('load', inicio, false);

    var boton;

    functioninicio()
    {
        modificar('boton1', 10);
        modificar('boton2', 13);
        modificar('boton3', 20);
    }

    functionmodificar(id, size)
    {
        boton = document.getElementById(id);
        boton.onclick=function(){fuente(size)};
        console.log(boton);
    }

    functionfuente(size)
    {
        var parrafo = document.getElementById('parrafo');
        parrafo.style.fontSize=size+'px';
    }

Post a Comment for "Change Font Size With Javascript"