Dynamically increase font size of CodeMirror editor texts

Updated on July 12, 2022

Question: I have been using the CodeMirror editor for one of my projects to allow users to write Python code. Is it possible to dynamically increase font size of CodeMirror editor texts? – Ravi Kumar.

Dynamically Increase font size of Codemirror editor texts

You need to write a simple JavaScript code to do that. Let us assume that the user will be provided with a control to increase or decrease the font size. For example, a range slider that allows the user to increase or decrease the font size of the texts inside the editor. Upon sliding, a JavaScript function will be called to dynamically set the font size.

Step 1: Create a range slider

<input id="font-slider" type = "range" min="15" max= "30" value='14'>

Step 2: JavaScript code to dynamically set the font size.

$('#font-slider').on('input', function(){
       var v = $(this).val();
       $('.CodeMirror-line span').css('font-size',v + 'px')
});

Update 12/07/2022: The above code will increase the font size, but the line will revert to its original font size when edited (I mean, the active line). Also, the cursor positioning was not consistent. For example, the cursor on the current line still remains small and corrects its size & position after moving it left/right, up/down. The below gif explains the issue.

codemirror font size issue

Well, to fix this issue the code needs to be modified as below:

$('#font-slider').on('input', function(){
var v = $(this).val();
        $('.CodeMirror').css('font-size',v + 'px')
});

Was this article helpful?

Related Articles

Leave a Comment