Search code examples
javascriptdom-events

Change font size with JavaScript


I have this code to change the font size of a paragraph with 3 buttons. I would like to know which method can I use to not repeat the same lines and make this code more compact.

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

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

boton1.addEventListener('click', fuente10, false);
boton2.addEventListener('click', fuente13, false);
boton3.addEventListener('click', fuente20, false);
} 

function fuente10(){
var parrafo = document.getElementById('parrafo');
parrafo.style.fontSize='10px'
}

function fuente13(){
var parrafo = document.getElementById('parrafo');
parrafo.style.fontSize='13px'
}

function fuente20(){
var parrafo = document.getElementById('parrafo');
parrafo.style.fontSize='20px'
}

I was thinking in a for loop but I can't figure it out how to do it :/


Solution

  • Try something like this

    window.addEventListener('load', inicio, false);
    
    function inicio(){
    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);
    } 
    
    function setFont(value){
       var parrafo = document.getElementById('parrafo');
       parrafo.style.fontSize= value;
    }
    

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

        window.addEventListener('load', inicio, false);
    function inicio() {
        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 } )();