Search code examples
javascriptjqueryruby-on-railslimitfont-size

Limit the amount of times font size can be increased and decreased


In my ruby on rails application I am using the following javascript in the application.js to increase and decrease the text size:

function resizeText(multiplier) {
var elem = document.getElementById("sizeable");
var currentSize = elem.style.fontSize || 1;
elem.style.fontSize = ( parseFloat(currentSize) + (multiplier * 0.2)) + "em";
}

And this is called by these pieces of code in the view:

<img id="plustext" alt="INCREASE TEXT SIZE" src="images/makeTextBigger.jpg" onclick="resizeText(1)" /> | 
<img id="minustext" alt="DECREASE TEXT SIZE" src="images/makeTextSmaller.jpg" onclick="resizeText(-1)" />

The code then makes the text with the id sizeable bigger or smaller depending on what was clicked:

<tr id='sizeable'>
    <td><%= certificate.age_rating %></td>
    <td>
        <%= link_to 'Edit', edit_certificate_path(certificate) %>
        <%= link_to 'Show', certificate_path(certificate) %>
        <%= link_to 'Destroy', certificate_path(certificate), method: :delete, data: { confirm: 'Are you sure?' } %>
    </td>
</tr>

But what I want to do is restrict the amount of times the font size can be increased and decreased to 2 clicks.

I have tried this, and replaced my previous java script so my application.js now looks like this:

$(function(){
 $('#film_release_date').datepicker({
    dateFormat: 'dd-mm-yy', altFormat: 'yy-mm-dd', 
    changeYear: true, maxDate: "5Y", minDate: "0D", changeMonth: true
  });
 });

var minSize = 1;
var maxSize = 5;

function resizeText(multiplier) {
    var elem = document.getElementById("sizeable");
    var newSize = parseFloat(elem.style.fontSize) + multiplier * 0.2;
    if (newSize < minSize) newSize = minSize;
    if (newSize > maxSize) newSize = maxSize;
    elem.style.fontSize = newSize + "em";
}

But this appears not to work.

How can I adapt my code to do this? I do not have much knowledge of java script.


Solution

  • After adapting the answer provided by @Andrei Nikolaenko, adding this into my application.js worked:

    var minSize = 1;
    var maxSize = 1.5;
    
    function resizeText(multiplier) {
      var elem = document.getElementById("sizeable");
      var currentSize = elem.style.fontSize || 1;
      var newSize = parseFloat(currentSize) + multiplier * 0.2;
      if (newSize < minSize) newSize = minSize;
      if (newSize > maxSize) newSize = maxSize;
      elem.style.fontSize = newSize + "em";
    }
    

    The main difference is that I'm using the variable currentSize in the line var newSize = parseFloat(currentSize) + multiplier * 0.2;

    Thank you to everyone who helped.