Return value of window.innerHeight seem to be wrong? - javascript

I am trying to get a viewport height size with window.innerHeight. But its return value seems to be wrong.
I tried window.outerHeight and window.innerHeight.
I added the viewport meta tag too.
<meta name="viewport" content="height=device-height; width=device-width; initial-scale=1.0; maximum-scale=1.0; user-scalable=no">
console.log("viewport_inner_height: " + window.innerHeight);
console.log("viewport_outer_height: " + window.outerHeight);
and the result is:
viewport_inner_height: 2044
viewport_outer_height: 1047
window.outerHeight seem right.
How can I get exactly the viewport height by javascript?

window.innerHeight is right.
I found the code that gets exactly the viewport height by JavaScript.
Try to run the code following. Good luck.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="height=device-height; width=device-width; initial-scale=1.0; maximum-scale=1.0; user-scalable=no">
<title>Document</title>
</head>
<script>
console.log("viewport_inner_height: " + window.innerHeight);
console.log("viewport_outer_height: " + window.outerHeight);
</script>
<body>
<p class="dimensions">
<span id="w"></span>
×
<span id="h"></span>
</p>
</body>
<script>
!function(t,n,e){"undefined"!=typeof module&&module.exports?module.exports=e():t.verge=e()}(this,0,function(){var t={},e="undefined"!=typeof window&&window,n="undefined"!=typeof document&&document,o=n&&n.documentElement,r=e.matchMedia||e.msMatchMedia,i=r?function(t){return!!r.call(e,t).matches}:function(){return!1},u=t.viewportW=function(){var t=o.clientWidth,n=e.innerWidth;return t<n?n:t},c=t.viewportH=function(){var t=o.clientHeight,n=e.innerHeight;return t<n?n:t};function f(){return{width:u(),height:c()}}function l(t,n){return!(!(t=t&&!t.nodeType?t[0]:t)||1!==t.nodeType)&&function(t,n){var e={};return n=+n||0,e.width=(e.right=t.right+n)-(e.left=t.left-n),e.height=(e.bottom=t.bottom+n)-(e.top=t.top-n),e}(t.getBoundingClientRect(),n)}return t.mq=i,t.matchMedia=r?function(){return r.apply(e,arguments)}:function(){return{}},t.viewport=f,t.scrollX=function(){return e.pageXOffset||o.scrollLeft},t.scrollY=function(){return e.pageYOffset||o.scrollTop},t.rectangle=l,t.aspect=function(t){var n=(t=null==t?f():1===t.nodeType?l(t):t).height,e=t.width;return n="function"==typeof n?n.call(t):n,(e="function"==typeof e?e.call(t):e)/n},t.inX=function(t,n){var e=l(t,n);return!!e&&0<=e.right&&e.left<=u()},t.inY=function(t,n){var e=l(t,n);return!!e&&0<=e.bottom&&e.top<=c()},t.inViewport=function(t,n){var e=l(t,n);return!!e&&0<=e.bottom&&0<=e.right&&e.top<=c()&&e.left<=u()},t});
function updateViewport() {
var newHeight = verge.viewportH();
var newWidth = verge.viewportW();
document.getElementById('w').innerHTML = newWidth;
document.getElementById('h').innerHTML = newHeight;
}
// function updateScreenRes() {
// var newHeight = window.screen.height;
// var newWidth = window.screen.width;
// document.getElementById('screen_w').innerHTML = newWidth;
// document.getElementById('screen_h').innerHTML = newHeight;
// }
function doCalcs() {
requestAnimationFrame(updateViewport);
// requestAnimationFrame(updateScreenRes);
}
window.addEventListener('load', doCalcs, false);
</script>
</html>

Related

How to execute methods from a JS class at the same time using an HTML form

I have a submit button and I want to click it and run first calcArea method, and then printArea but all this just by pressing one time the submit button, so that my console prints:
100
I have this code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Form</title>
</head>
<body>
<form id="nameForm" onclick="square.calcArea()" onclick="square.printArea()">
<input type="submit" value="print area in console" id="btn">
</form>
<script>
class Rectangle {
constructor(height, width) {
this.height = height;
this.width = width;
}
printArea() {
console.log(this.calcArea());
}
calcArea() {
return this.height * this.width;
}
}
const square = new Rectangle(10, 10);
</script>
</body>
</html>
And I tried to do this in the form using two times onclick(), but it doesn´t work because It doesn´t show anything in console.
I hope someone can help, thank you.
This should work:
<button onclick="rectangle('PRINT_AREA')">Print Area</button>
<script>
class Rectangle {
constructor(height, width) {
this.height = height;
this.width = width;
}
printArea() {
console.log(this.calcArea());
}
calcArea() {
return this.height * this.width;
}
}
const square = new Rectangle(10, 10);
function rectangle(type) {
switch(type) {
case "PRINT_AREA":
square.printArea()
default:
console.log("error")
}
}
</script>

Trying to figure out why balloon pop game is not resetting clickCount

I have followed along with video from video number 76 of the Udemy "last Intro to Programming Course". I have moved code that was included all in one function to another function called "draw" I have reviewed the video multiple times and I cannot see any difference between my code and the video. The goal of the code is to reset the clickCount back to zero. Here is the code. Help would be greatly appreciated everything is working except resetting of the balloon size and clickCount with each timeout:
let startButton = document.getElementById('start-button')
let inflateButton = document.getElementById('inflate-button')
let clickCount = 0
let height = 120
let width = 100
let inflationRate = 20
let maxsize = 300
let popCount = 0
function startGame() {
startButton.setAttribute("disabled", "true")
inflateButton.removeAttribute("disabled")
setTimeout(() => {
console.log("it's been 3 seconds")
inflateButton.setAttribute("disabled", "true")
startButton.removeAttribute("disabled")
clickCount = 0
height = 120
width = 100
draw()
}, 3000)
}
function inflate() {
clickCount++
height += inflationRate
width += inflationRate
if (height >= maxsize) {
console.log("pop the balloon")
popCount++
height = 0
width = 0
}
draw()
}
function draw() {
let balloonElement = document.getElementById("balloon")
let clickCountElem = document.getElementById("click-count")
let popCountElem = document.getElementById('pop-count')
balloonElement.style.height = height + "px"
balloonElement.style.width = width + "px"
clickCountElem.innerText = clickCount.toString()
popCountElem.innerText = popCount.toString()
}
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Balloon Pop</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<div>
<button id="start-button" onclick="startGame()" >START GAME</button>
</div>
<button id="inflate-button" onclick="inflate()" disabled="true">Inflate <span id="click-count"> </span></button>
<div>
<span>Balloons Popped</span>
<span id="pop-count"></span>
</div>
<div id="balloon" class="balloon" ></div>
<script src="main.js"></script>
</body>
</html>
I figured this out by looking at the source tab in dev tools. For whatever reason all of the lines weren't being saved or loaded to Chrome from VSCode. What I did was copy all the code from VSCode and pasted it into Notepad, saved and then refreshed. All is working fine now.

Baffled by NaN - HTML CANVAS JS

I'm trying to create a timer within an object - however when trying to increment the counter by the time that's passed I'm getting a NaN error. The error stops if I replace the deltaTime argument with a constant, but then the jump time would vary depending upon the end users machine and work load.
class Actor {
constructor() {
this.jumpCounter = 0
this.jumpTimer = function (deltaTime) {
console.log(this.jumpCounter);
this.jumpCounter += deltaTime;
console.log(deltaTime)
}
}
}
let canvas = document.getElementById('gameScreen');
let ctx = canvas.getContext("2d");
var lastTime = 0;
const GAME_WIDTH = 600;
const GAME_HEIGHT = 600;
actor = new Actor;
function gameLoop(timestamp) {
let deltaTime = timestamp - lastTime;
lastTime = timestamp;
ctx.fillStyle = 'rgba(155, 200, 155, 0.3)'
ctx.fillRect(0, 0, GAME_WIDTH, GAME_HEIGHT);
actor.jumpTimer(deltaTime)
requestAnimationFrame(gameLoop);
}
gameLoop();
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Game Sandbox</title>
<style>
#gameScreen {
border: 1px solid;
}
</style>
</head>
<body>
<canvas id="gameScreen" width="600" height="600"></canvas>
<script></script>
</body>
</html>
As the error resulted from there being on timestamp on the first run through of the code this fixed the issue:
this.jumpTimer = function (deltaTime) {
if (!deltaTime) return;
console.log(this.jumpCounter);
this.jumpCounter += deltaTime;
console.log(deltaTime)
}

Command fillRect() in Javascript does not work

I'm currently undergoing the development of a game, but I've stumbled across a problem where the fillRect() command will not work onto the HTML5 canvas, using Javascript. I do not know why this is happening, after trying to do research on it and checking my code. The HTML code is shown below:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Cube Quest</title>
<style>
#game {
border: 1px dashed black;
}
</style>
</head>
<body>
<canvas id="game" width='1280' height='720'>Your browser does not support the canvas element in HTML5.</canvas>
<script>
var clicked = false; // Mouse handling event
var mouseX = event.cilentX; // Mouse X coordinate
var mouseY = event.cilentY; // Mouse Y coordinate
var canvas = document.getElementById("game"); // For canvas
var ctx = canvas.getContext("2d"); // For canvas
ctx.fillStyle = 'black'; // rectangle color selection
ctx.fillRect(10, 10, 150, 80);
</script>
</body>
</html>
I'm not the best expert on Javascript, so there is little that I know which could help me understand the reason why no rectangle shows when the code is correct.
I appreciate the help on this specific question in advance. :)
You will need to look addEventListener function in JS to made better view of situation.
Here working example :
// globals
var canvas = document.getElementById("game");
var clicked = false; // Mouse handling event
var mouseX = 0;
var mouseY = 0;
// yuor application parameters
var app = {
clearCanvas: true,
title: 'HELLO'
};
canvas.addEventListener('click' , function (event){
mouseX = event.pageX; // Mouse X coordinate
mouseY = event.pageY; // Mouse Y coordinate
console.log("Mouse x : " + mouseX + " Mouse y :" + mouseY );
drawAgain();
});
// Initial draw
var ctx = canvas.getContext("2d"); // For canvas
ctx.fillStyle = 'black'; // rectangle color selection
ctx.fillRect(mouseX, mouseY, 350, 65);
ctx.font="30px Arial";
ctx.fillStyle = 'lime';
ctx.fillText(app.title + "X:" + mouseX + " Y:" + mouseY , mouseX + 35, mouseY + 40, 250)
// Draw when you need
function drawAgain () {
if (app.clearCanvas == true){
ctx.clearRect(0, 0, canvas.width, canvas.height);
}
ctx.fillStyle = 'black'; // rectangle color selection
ctx.fillRect(mouseX, mouseY, 350, 65);
ctx.fillStyle = 'lime';
ctx.fillText(app.title + " X:" + mouseX + " Y:" + mouseY , mouseX + 35, mouseY + 40, 400)
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Cube Quest</title>
<style>
#game {
border: 1px dashed black;
}
</style>
</head>
<body>
<canvas id="game" width='1280' height='720'>Your browser does not support the canvas element in HTML5.</canvas>
<script>
</script>
</body>
</html>
Suggestion: Also learn to use removeEventListener , lot of web
developers have trouble with event conflict situation when they use
lot of lib's. For dynamic app flow methodology use removeEventListener
before setting a flags.
Having error in event.cilentX because event is not available at this moment so that is not moving to next lines of code to execute. If you want to play with event you need to attache any event listener like canvas.addEventListener('click' , function (event){//here you will get the event});. I just commented the two line now it working fine to draw rectangle.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Cube Quest</title>
<style>
#game {
border: 1px dashed black;
}
</style>
</head>
<body>
<canvas id="game" width='1280' height='720'>Your browser does not support the canvas element in HTML5.</canvas>
<script>
var clicked = false; // Mouse handling event
// var mouseX = event.cilentX; // Mouse X coordinate
// var mouseY = event.cilentY; // Mouse Y coordinate
var canvas = document.getElementById("game"); // For canvas
var ctx = canvas.getContext("2d"); // For canvas
ctx.fillStyle = 'black'; // rectangle color selection
ctx.fillRect(10, 10, 150, 80);
</script>
</body>
</html>
It's your mouse event listeners that are breaking the program.
Comment them out and it works just fine.
Here is a code snippet I use for small JavaScript games I test out.
//Mouse Events ==================
document.onmousemove = mousePos;
document.onmousedown = function() { mouse.clicked = true; };
document.onmouseup = function() { mouse.clicked = false; };
//MOUSE
var mouse = {
x: 0,
y: 0,
clicked: false
};
function mousePos (e) {
mouse.x = e.pageX - canvas.offsetLeft;
mouse.y = e.pageY - canvas.offsetTop;
}

Create Element with id and styles using pure JS

I build a small function appending an element with an id and styles.
And know my question why does this code not work?
window.addEventListener("load",function(e){
var inButton = document.createElement("DIV"),
body = document.body;
inButton.id = "button";
inButton.style = function (){
height = "200px";
width = "400px";
position = "fixed";
top = "50%";
left = "50%";
marginLeft = -1*(this.width / 2);
marginTop = -1*(this.height / 2);
};
body.appendChild(inButton);
}, false);
I use the following html:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"/>
<meta name="description"/>
<meta name="viewport" content="width=device-width, initial-scale=1" />
<meta http-equiv="x-ua-compatible" content="ie=edge" />
<script type="text/javascript" src="js/vendor/modernizr-.8.3.min.js"></script>
</head>
<body>
<script type="text/javascript" src="js/plugins.js"></script>
<script type="text/javascript" src="js/main.js"></script>
</body>
</html>
The Js Code is inside the main.js.
I checked the path again and again, but the path is totally correct.
You are not setting style property correctly. Rest of code is correct.
Here's an example
window.addEventListener("load", function(e) {
var inButton = document.createElement("DIV"),
body = document.body;
inButton.id = "button";
inButton.innerHTML = "Yahooooooooooooooo"; //For example
inButton.style.height = "200px";
inButton.style.width = "400px";
inButton.style.position = "fixed";
inButton.style.top = "50%";
inButton.style.left = "50%";
inButton.style.marginLeft = -1 * (this.width / 2);
inButton.style.marginTop = -1 * (this.height / 2);
body.appendChild(inButton);
}, false);

Categories