Reputation: 69
How can I change the font size of the left-column
using JavaScript?
<div id="left-column">
<a href="">1</a><br>
<a href="">2</a><br>
<a href="">3</a><br>
<a href="">4</a><br>
<a href="">5</a><br>
<a href="">6</a><br>
</div>
This is what I have so far:
<script>
document.write(document.body.clientWidth);
if (document.body.clientWidth > 400)
document.getElementById('left-column').style.letterSpacing="0px";
}
</script>
Upvotes: 0
Views: 3338
Reputation: 65853
You use the same property name that you would in CSS (minus the hypen and with camel casing) against the style
object. Now, font-size
is an "inherited" property, which means that when it is applied, the value is also applied to descendant elements as well. So, while can apply this to each <a>
element if you like, you don't need to. You can just apply it to the parent element of them. Keep in mind though that ALL descendant elements will be affected in that case and you would have to then reset the font on elements that you didn't want affected.
document.querySelector("button").addEventListener("click", function(){
var iw = window.innerWidth;
document.getElementById("outputArea").textContent = "The usable width of the page is: " + iw + "px";
if(iw > 400){
// Get all the <a> elements that are children of the div
var a = document.querySelectorAll("#leftcol > a");
// loop through the colleciton of them and change their font size
for(var i = 0; i < a.length; i++){
a[i].style.fontSize = "3em";
}
// We could avoid getting all the <a> elements and looping through them one by one
// and just do this:
// document.getElementById("leftcol").style.fontSize = "3em";
// And that would affect the the elements within the #leftcol element.
}
});
<div id="outputArea"></div>
<div id="leftcol">
<a href="">1</a><br>
<a href="">2</a><br>
<a href="">3</a><br>
<a href="">4</a><br>
<a href="">5</a><br>
<a href="">6</a><br>
</div>
<button>Click Me</button>
Also, document.write()
should not be used unless you are dynamically writing an entire document's DOM (usually into a new window). Instead, inject the content you want to output into an element already in the DOM.
Upvotes: 1
Reputation: 6577
You should use CSS as oppose to javascript to control your font size based on page width. The best way to do that is using media queries. See this page for more details. https://www.w3schools.com/css/css3_mediaqueries_ex.asp
Example:
#leftcol{
font-size: 20px;
}
@media screen and (max-width: 400px) {
#leftcol {
font-size: 12px;
}
}
With the above example, the font size will be 20px by default. When the page is 400 pixels or less, it will be reduced to size of 12.
Upvotes: 1