Reputation: 3
I'm new here and trying to found a solution for a small part of my exercise with JS/jQuery. I'm trying to change the font size of the whole page and could implement that with the following code. What I'd like to do is not to change the font size of the clicked elements itself, in my case these are: #size1, #size2, #size3 and actually the text in span "Text size" also. I've seen some answers in another topics on how to change parent elements without affecting children, but it was about altering text and I could not apply it for my needs. Any help would be appreciated.
//HTML
<span>Text size :</span>
<a id="small" href="#" style="font-size: 0.8em" onclick="textgr(0.8)">A</a>
<a id="middle" href="#" style="font-size: 1em" onclick="textgr(1)">A</a>
<a id="large" href="#" style="font-size: 1.2em" onclick="textgr(1.2)">A</a>
//This works fine to change the font size on the whole page
function textgr(gr){
document.body.style.fontSize = gr + "em";
}
//I've tried to pack this piece of code in the function above, but it would not do anything at all
function textgr2(){
document.getElementById(small).style.fontSize = 0.8 + "em";
document.getElementById(middle).style.fontSize = 1 + "em";
document.getElementById(large).style.fontSize = 1.2 + "em";
}
Upvotes: 0
Views: 1021
Reputation: 9782
document.getElementById("text-size-controls").addEventListener("click", function(evt) {
var sz;
var target = evt.target;
if (evt.target.hasAttribute('data-size')) {
sz = evt.target.getAttribute('data-size');
document.getElementById("text-area").setAttribute("class",sz);
}
});
#text-size-controls {
cursor: pointer;
list-style-type: none;
padding: 0;
margin: 0;
}
#text-size-controls li {
display: inline-block;
}
.small {
font-size: 10px;
}
.medium {
font-size: 16px;
}
.large {
font-size: 20px;
}
h1 {
font-size: 2.0em;
}
.text {
font-size: 1.0em;
}
<ul id="text-size-controls">
<li data-size="small">Small</li>
<li data-size="medium">Medium</li>
<li data-size="large">Large</li>
</ul>
<div id="text-area">
<h1>
Header
</h1>
<p class="text">
This is some text
</p>
</div>
Notice that small, medium and large set the font size in pixels, but that the h1 and .text class adjust the size in ems. This ensure the base size of the text is set and then proportionately adjusted.
This solution does not require jQuery. I omitted it because the code in your question is JavaScript, not jQuery.
Upvotes: 1