Reputation: 189
I'm new to JavaScript and wanted to make a simple "hello world" program with changing text based on the width on the screen. If the width of the window (of the index file) is 400 or more pixels, show text, and if the window is smaller then 400px show other text. I do not know why my code does not work. Can somebody please explain this to me, thanks in advance
this is my code (HTML and JavaScript )
HTML =
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>JavascriptResponsive</title>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<h1>Hello world </h1>
<script src="Morris.js"></script>
</body>
</html>
JavaScript =
var currentWidth = window.innerWidth;
if (currentWidth > 400) {
document.write(" <h1>Hello big world </h1>");
}
else if (currentWidth < 400) {
document.write( "<h1>Hello small world </h1>");
}
Upvotes: 1
Views: 1504
Reputation: 207557
When JavaScript code is run the variables do not keep updating and running. So you need to write code to detect when things change. So you need to listen to the resize event. So you bind an event listener and you can rerun the code. You also can not use document.write to output the message after the page loads since it will remove all the page content. So you want to update the DOM.
function updateMessage() {
var currentWidth = window.innerWidth;
var message = "Hello small world";
if (currentWidth > 400) {
message = "Hello big world";
}
document.getElementById("msg").innerHTML = message
}
window.addEventListener("load", updateMessage)
window.addEventListener("resize", updateMessage)
<h1 id="msg">Hello world </h1>
Upvotes: 1