Changing the font of a textarea with onclick in an option

Asked

Viewed 65 times

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 land the above textarea source according to option?

Thank you!

1 answer

2

I think it would be more organized to have CSS classes for those sources 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: https://jsfiddle.net/m5yev3ez/

This code traverses all options and using the .classList.toggle() sets or removes the class according to the index of the option to be iterated is the same as select.selectedIndex, or is the option chosen.

This from the presuposto that you give each option the value corresponding to each class. For example: <option value="fantasy">Fantasy</option>

  • Thanks in the case text being the textarea is pulled by the element I can confirm a source for it and then it changes? Example textarea { font-family: Arial; }

Browser other questions tagged

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