I am trying to use this script to run a function on the page load. Can anyone see what's wrong? Stupid error, I'm sure - just can't work it out.
Code:
<script>
var text = document.getElementById("myText");
function changeFontSize(){
if (window.innerWidth < 600) {
text.style.fontSize = "70px";
} else {
text.style.fontSize = "100px";
}
}
window.onresize = changeFontSize;
</script>
<script>
setTimeout(function() changeFontSize, 3000);
</script>
-
Try to use window.onload = changeFontSize;JGV– JGV2015年07月13日 17:21:21 +00:00Commented Jul 13, 2015 at 17:21
5 Answers 5
window.onload = changeFontSize;
window.onresize = changeFontSize;
alternatively, you can use
window.addEventListener("onload", changeFontSize, false);
window.addEventListener("onresize", changeFontSize, false);
5 Comments
var text = document.getElementById("myText");
function changeFontSize() {
if (window.innerWidth < 600) {
text.style.fontSize = "70px";
} else {
text.style.fontSize = "100px";
}
}
window.onresize = changeFontSize;
setTimeout(changeFontSize, 3000);
<p id="myText">Test</p>
Basically you had a syntax error in:
setTimeout(function() changeFontSize, 3000);
You don't need the function()
1 Comment
To start with, setTimeout() isn't used the way you wrote it, it should be setTimeout(changeFontSize, 3000); instead. That being said this would work:
<script>
var text = document.getElementById("myText");
function changeFontSize() {
if (window.innerWidth < 600) {
text.style.fontSize = "70px";
} else {
text.style.fontSize = "100px";
}
}
window.onresize = changeFontSize;
changeFontSize();
</script>
As was also said by jperelli, window.onload = changeFontSize would also work.
2 Comments
<script> block in the <head> tags or at the end of the body (after the elements you want to re-size)? What's the behavior that you're seeing?If you want absolutely use onresize instead onload (I suppose that you want to achieve something responsive), you need to wait the page is loaded, otherwise the object myText will not the object will not yet been initialized in the variable text ('cause it's not yet available in the DOM).
Note that in this case the use of a setTimeout (you wrong the syntax anyway) is not necessary.
This works:
<script>
function changeFontSize(){
if (window.innerWidth < 600) {
document.getElementById("myText").style.fontSize = "70px";
} else {
document.getElementById("myText").style.fontSize = "100px";
}
}
window.onresize = changeFontSize;
</script>
1 Comment
var text = document.getElementById("myText");
function changeFontSize(){
if (window.innerWidth < 600) {
text.style.fontSize = "70px";
} else {
text.style.fontSize = "100px";
}
}
window.onload = changeFontSize;
window.onresize = changeFontSize;
<div id="myText">Test</div>