The style
property of an element only returns style information that has been set on the style
attribute in the HTML. If the style
has been set via a class
or through JavaScript, you will get undefined
. Instead, use getComputedStyle()
, which will return the current style information, regardless of how it was set.
Also, you probably don't want to increase the font size with:
currentSize + .1 + "em"
Since em
is a unit that is relative to the size of the parent element. If say, an element has parent element with a font size of 16px
(the default size of normal text in most browsers) and you strip off the px
and then add .1em
to it, you'll have a new size of 16.1em
, which means 16.1 times the parent element size (16 x 16.1 = 257.6px). If you really want to use em
, you should just make it 1.1
for a slight size increase, otherwise stick with px
and just bump it up by 1
(shown below).
// Instead of the function only being able to work when an element
// id is passed to it, have the function work as long as an element
// reference itself is passed to it. This is more flexible, since
// not all elements will have an id.
function increaseFontSize(element) {
console.clear();
currentSize = parseFloat(getComputedStyle(element).fontSize);
console.log("Original size of: " + element.nodeName + ": " + currentSize);
element.style.fontSize = ++currentSize + "px"; // Bump up the font size by 1 and concatenate "px" to the result
console.log("New size of: " + element.nodeName + ": " + getComputedStyle(element).fontSize);
}
// Set a click event on the entire document
document.addEventListener("click", function(event){
// Run the callback and pass a reference to the actual element that was clicked
increaseFontSize(event.target);
});
<p>A long time ago</p>
<div>In a galaxy far far away</div>
<h1><div>STAR WARS</div></h1>