Developer Strange
Developer Strange

Reputation: 2198

Increase and Decrease font size of selected/Highlighted text inside the iframe tag using jquery in google chrome browser

I used the execCommand() to increase and decrease the font size of selected/highlighted text (while we click the increment or decrement button the selected text font size is increased or decreased by 2px).

execCommand() is working perfectly in Mozilla Firefox, but it is not working in Google Chrome. How can I "Increase and Decrease font size of selected/Highlighted text inside the iframe tag using jquery in google chrome browser"?

Upvotes: 1

Views: 2972

Answers (1)

Alexander Dayan
Alexander Dayan

Reputation: 2924

By definition, FontSize is limited by the standard values from 1 to 7 intepreted as 'xx-small', 'x-small', 'small', 'medium', 'large', 'x-large' and 'xx-large' consequently:

$(document).ready(function(){
  
  var fontSize = 3;
  
  $('#decrease').click(function(){
    if (fontSize > 1)
      fontSize--;
    document.execCommand("fontSize", false, fontSize);
  });
  
  $('#increase').click(function(){
    if (fontSize < 7)
      fontSize++;
    document.execCommand("fontSize", false, fontSize);
  });
})
div{
  margin-top: 16px;
  padding: 4px;
  border: solid 1px gray;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id='decrease' type="button" value="Decrease Font">
<input id='increase' type="button" value="Increase Font">
<div contenteditable="true">Hello, this is some editable text</div>

You can customize this functionality by using a hacky method which calls document.execCommand("fontSize", false, "1"), finds the elements and changes it:

$(document).ready(function(){
  
  var fontSize = 16;
  
  $('#decrease').click(function(){
    if (fontSize > 6)
      fontSize-=2;
    document.execCommand("fontSize", false, "1");
    resetFont();
  });
  
  $('#increase').click(function(){
    if (fontSize < 64)
      fontSize+=2;
    document.execCommand("fontSize", false, "1");
    resetFont();
  });
  
  function resetFont(){
    $("font[size=1]").removeAttr("size").css("font-size", fontSize + "px");
  }
})
div{
  margin-top: 16px;
  padding: 4px;
  border: solid 1px gray;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id='decrease' type="button" value="Decrease Font">
<input id='increase' type="button" value="Increase Font">
<div contenteditable="true">Hello, this is some editable text</div>

Remark: the above code samples are written for contenteditable div, but conceptually it;s no difference with iframe-based editor.

Upvotes: 3

Related Questions