Chris
Chris

Reputation: 19

Increase/Decrease Font Size Script - How Add Default Text Size Function?

Does anybody know how to modify the below script so that, in addition to the two current functions (changeFontSize( id, true); //Increases the font size - changeFontSize( id ); // Decreases size), I can add a third function whereby the font size will be reset to a default setting?

Thank you, Chris

SCRIPT

function changeFontSize( objId, doIncreaseSize ) { //Define your variables before use, or they will become global. var currentSize = 0, obj = document.getElementById( objId ), newVal = 0, limitMax = 10, limitMin = 0.5, unit = 0.1;

if( !obj ){
 return false; //Avoids errors if obj isn't found.
}
currentSize = parseFloat( obj.style.fontSize );
if( doIncreaseSize ){
    unit = -unit; // unit becomes negative. This turns subtractions into addition.
}
newVal = currentSize - unit;
if( limitMax >= newVal && limitMin <= newVal ){
    obj.style.fontSize = newVal + "em";
}

};

Upvotes: 0

Views: 2786

Answers (2)

googletorp
googletorp

Reputation: 33275

Taking what you have made, what you could do is that instead of using doIncreaseSize as a boolean, you could instead call that variable action and do

...
if (action == 'sub') {
    unit = -unit;
}
newVal = currentSize - unit;
if (action == 'def') {
    newVal = some_default_value;
}
...

But the real question here is why are you doing this in the first place? It would probably be a lot easier just setting the value instead of increasing and decreasing, unless you plan to make a button that the user can click to increase and decrease the text size of your webpage. But like posted in the comments, that can be done in the browser directly.

Upvotes: 0

Sinan Taifour
Sinan Taifour

Reputation: 10805

You will need to save the original font size (assuming it is not 1em) somewhere, like on the object itself or in an external array.

Something like this:

function changeFontSize(objId, doIncreaseSize) { 
  var currentSize = 0, obj = document.getElementById(objId), newVal = 0, limitMax = 10, limitMin = 0.5, unit = 0.1;
  if(!obj){
    return false;
  }
  currentSize = parseFloat( obj.style.fontSize );
  if (!obj.originalSize) { obj.originalSize = currentSize; }
  if(doIncreaseSize){
    unit = -unit;
  }
  newVal = currentSize - unit;
  if(limitMax >= newVal && limitMin <= newVal){
    obj.style.fontSize = newVal + "em";
  }
  return true;
}

function resetDefaultSize(objId) { 
  var obj = document.getElementById(objId);
  if(!obj){
   return false;
  }
  if (obj.originalSize) { obj.style.fontSize = obj.originalSize + "em"; }
  return true;
}

Notice your code will only work if the element has an explicitly defined font-size with units of em.

Upvotes: 1

Related Questions