Change the font of a textarea with onclick in an option

2
<select>
  <option>Arial</option>
  <option>Open Sans</option>
  <option>Roboto</option>
  <option>Calibri</option>
  <option>Helvetica</option>
</select>

<textarea id="text"></textarea>

How can I through an onclick to land the textarea source up according to the option?

Thank you!

    
asked by anonymous 25.08.2016 / 23:05

1 answer

2

I think it would be more organized to have CSS classes for these fonts like this:

.serif {
    font-family: Times, "Times New Roman", Georgia, serif;
}

.sansserif {
    font-family: Verdana, Arial, Helvetica, sans-serif;
}

.monospace {
    font-family: "Lucida Console", Courier, monospace;
}

.cursive {
    font-family: cursive;
}

.fantasy {
    font-family: fantasy;
}

and then with JavaScript add or remove the class. It could be something like this:

var textarea = document.getElementById('text');
var select = document.querySelector('select');
select.addEventListener('change', function() {
    [].forEach.call(select.children, function(opt, i) {
        textarea.classList.toggle(opt.value, i == select.selectedIndex);
    });
});

jsFiddle: link

This code runs through all options and using .classList.toggle() puts or removes the class depending on the index of the option to be iterated is the same as select.selectedIndex , that is the option chosen.

This is based on the assumption you give to each% of% and% of% corresponding to each class. For example: option

    
25.08.2016 / 23:15