cosmo cosmo - 4 months ago 26
CSS Question

Select option onclick change font-family

I have a plain

contenteditable
with the id 'editor1' that allows users to input whatever text they want. I also have a
select
tag that contains the different
options
, where each option is a different font family.

What I did was, I called a function when the user clicks an option, which wraps the selected text in
span
and changes its font-family accordingly. Unfortunately it doesn't work; anyone have a working solution? (Preferably pure javascript)

HTML:

<select>
<option onselect="usecomicsans()" style="font-family: 'Comic Sans MS'">Comic Sans MS</option>
<option onselect="usearial()" style="font-family: Arial">Arial</option>
</select>


JS:

function usecomicsans(){
{
var selection= window.getSelection().getRangeAt(0);
var selectedText = selection.extractContents();
var span = document.createElement("span");
span.style.fontFamily = "Comic Sans MS";
span.appendChild(selectedText);
selection.insertNode(span)
}
}

function usearial(){
{
var selection= window.getSelection().getRangeAt(0);
var selectedText = selection.extractContents();
var span = document.createElement("span");
span.style.fontFamily = "Arial";
span.appendChild(selectedText);
selection.insertNode(span);
}
}


EDIT: I read somewhere that using
onclick
with
option
wouldn't work; rather I should be using
onchange
inside
select
. Any ideas on how I could go about doing this?

Answer

I think this is the easy way :)

HTML

<div id="output-text">
  Hello Bros, welcome to the world
</div>
     <select id="input-font" class="input"  onchange="changeFont (this);">
      <option value="Arial">Arial</option>
      <option value="Comic Sans MS">Comic Sans MS</option>
    </select>
<br>

Javascript

<script>
    function changeFont(font){
        document.getElementById("output-text").style.fontFamily = font.value;
    }
</script>
Comments