Javascript to calculate aqi - javascript

I am trying to write a javascript for calculating the aqi of a place I am using the openweathermap.com api for fetching data like co, 03 and pm2.5 concentration but am not able to get the output for the aqiValue. I am including js, html and css code below:
note: I checked and I am encountering some error in the js when I am calling for the function calculateAQI, could anyone please check that part of the code and tell me what might the issue be?
js:
var input = document.querySelector('.input_text');
var main = document.querySelector('#name');
var temp = document.querySelector('.temp');
var desc = document.querySelector('.desc');
var lat = document.querySelector('.lat');
var long = document.querySelector('.long');
var aqi = document.querySelector('.aqi');
var hum = document.querySelector('.hum');
var co = document.querySelector('.co');
var feels = document.querySelector('.feels');
var clouds = document.querySelector('.clouds');
var button= document.querySelector('.submit');
var tempValue=null;
var nameValue=null;
var latValue=null;
var latValue=null;
var longValue=null;
var aqiValue=null;
var coValue=null;
var o3=null;
var pm25=null;
var aqiv = null;
var IHi = null;
var Ilo = null;
var BPHi = null;
var BPlo = null;
var Cp = null;
var o3Index = null;
var pm25Index = null;
var coIndex = null;
function a()
{
fetch('https://api.openweathermap.org/data/2.5/weather?q='+input.value+'&appid=7031deafbb01e5bded284c1ab5dd580c')
.then(response => response.json())
.then(data => {
var tempValue = data['main']['temp'];
tempValue=parseInt(tempValue-273);
var nameValue = data['name'];
var descValue = data['weather'][0]['description'];
var latValue = data['coord']['lat'];
var longValue = data['coord']['lon'];
var humValue = data['main']['humidity'];
var feelsValue = data['main']['feels_like'];
feelsValue=parseInt(feelsValue-273);
main.innerHTML = nameValue;
desc.innerHTML = "Desc - "+descValue;
temp.innerHTML = "Temp - "+tempValue;
feels.innerHTML = "Feels Like - "+feelsValue;
hum.innerHTML = "Humidity - "+humValue+"%";
lat.innerHTML = "Latitute - "+latValue;
long.innerHTML = "Longitude - "+longValue;
b(latValue,longValue);
})
}
function b(latValue,longValue)
{
var ts = Math.round((new Date()).getTime() / 1000);
fetch('http://api.openweathermap.org/data/2.5/air_pollution?lat='+latValue+'&lon='+longValue+'&appid=7031deafbb01e5bded284c1ab5dd580c')
.then(responset => responset.json())
.then(datat => {
//var aqiValue = datat['list'][0]['main']['aqi'];
var coValue = datat['list'][0]['components']['co']*0.00087;
var o3Value = datat['list'][0]['components']['o3']*0.51;
var pm25Value = datat['list'][0]['components']['pm2_5'];
var aqiValue = calculateAQI(o3Value ,pm25Value, coValue);
aqi.innerHTML = "AQI - "+aqiValue;
co.innerHTML = "CO - "+coValue;
exit(0);
})
}
function calculateAQI(o3, pm25, co) {
var aqiv = null;
var IHi = null;
var Ilo = null;
var BPHi = null;
var BPlo = null;
var Cp = null;
var o3Index = null;
var pm25Index = null;
var coIndex = null;
// Ozone (O3) calculation
if (o3>=0 && o3<=50)
{
IHi=50;
Ilo=0;
BPHi=50;
BPlo=0;
Cp=o3;
o3Index= ((IHi - Ilo) / (BPHi - BPlo))*(Cp - BPlo) + Ilo;
}
else if(o3>=51 && o3<=100)
{
IHi=100;
Ilo=51;
BPHi=100;
BPlo=51;
Cp=o3;
o3Index= ((IHi - Ilo) / (BPHi - BPlo))*(Cp - BPlo) + Ilo;
}
else if(o3>=101 && o3<=168)
{
IHi=200;
Ilo=101;
BPHi=168;
BPlo=101;
Cp=o3;
o3Index= ((IHi - Ilo) / (BPHi - BPlo))*(Cp - BPlo) + Ilo;
}
else if(o3>=169 && o3<=208)
{
IHi=300;
Ilo=201;
BPHi=208;
BPlo=169;
Cp=o3;
o3Index= ((IHi - Ilo) / (BPHi - BPlo))*(Cp - BPlo) + Ilo;
}
else if(o3>=209 && o3<=748)
{
IHi=400;
Ilo=301;
BPHi=748;
BPlo=209;
Cp=o3;
o3Index= ((IHi - Ilo) / (BPHi - BPlo))*(Cp - BPlo) + Ilo;
}
else
{
IHi=500;
Ilo=401;
BPHi=1000;
BPlo=748;
Cp=o3;
o3Index= ((IHi - Ilo) / (BPHi - BPlo))*(Cp - BPlo) + Ilo;
}
aqiv = Math.max(aqiv, o3Index);
// Particulate matter (PM2.5) calculation
if(pm25>=0 && pm<=30)
{
IHi=50;
Ilo=0;
BPHi=30;
BPlo=0;
Cp=pm25;
pm25Index= ((IHi - Ilo) / (BPHi - BPlo))*(Cp - BPlo) + Ilo;
}
else if(pm25>=31 && pm<=60)
{
IHi=100;
Ilo=51;
BPHi=60;
BPlo=31;
Cp=pm25;
pm25Index= ((IHi - Ilo) / (BPHi - BPlo))*(Cp - BPlo) + Ilo;
}
else if(pm25>=61 && pm<=90)
{
IHi=200;
Ilo=101;
BPHi=90;
BPlo=61;
Cp=pm25;
pm25Index= ((IHi - Ilo) / (BPHi - BPlo))*(Cp - BPlo) + Ilo;
}
else if(pm25>=91 && pm<=120)
{
IHi=300;
Ilo=201;
BPHi=120;
BPlo=91;
Cp=pm25;
pm25Index= ((IHi - Ilo) / (BPHi - BPlo))*(Cp - BPlo) + Ilo;
}
else if(pm25>=121 && pm<=250)
{
IHi=400;
Ilo=301;
BPHi=250;
BPlo=121;
Cp=pm25;
pm25Index= ((IHi - Ilo) / (BPHi - BPlo))*(Cp - BPlo) + Ilo;
}
else
{
IHi=500;
Ilo=401;
BPHi=379;
BPlo=250;
Cp=pm25;
pm25Index= ((IHi - Ilo) / (BPHi - BPlo))*(Cp - BPlo) + Ilo;
}
aqiv = Math.max(aqiv, pm25Index);
// Carbon monoxide (CO) calculation
if(co>=0 && co<=1)
{
IHi=50;
Ilo=0;
BPHi=1;
BPlo=0;
Cp=co;
coIndex= ((IHi - Ilo) / (BPHi - BPlo))*(Cp - BPlo) + Ilo;
}
else if(co>=1.1 && co<=2)
{
IHi=100;
Ilo=51;
BPHi=2;
BPlo=1.1;
Cp=co;
coIndex= ((IHi - Ilo) / (BPHi - BPlo))*(Cp - BPlo) + Ilo;
}
else if(co>=2.1 && co<=10)
{
IHi=200;
Ilo=101;
BPHi=10;
BPlo=2.1;
Cp=co;
coIndex= ((IHi - Ilo) / (BPHi - BPlo))*(Cp - BPlo) + Ilo;
}
else if(co>=10.1 && co<=17)
{
IHi=300;
Ilo=201;
BPHi=17;
BPlo=10.1;
Cp=co;
coIndex= ((IHi - Ilo) / (BPHi - BPlo))*(Cp - BPlo) + Ilo;
}
else if(co>=17.1 && co<=34)
{
IHi=400;
Ilo=301;
BPHi=34;
BPlo=17.1;
Cp=co;
coIndex= ((IHi - Ilo) / (BPHi - BPlo))*(Cp - BPlo) + Ilo;
}
else
{
IHi=500;
Ilo=401;
BPHi=69;
BPlo=34.1;
Cp=co;
coIndex= ((IHi - Ilo) / (BPHi - BPlo))*(Cp - BPlo) + Ilo;
}
aqiv = Math.max(aqiv, coIndex);
return aqiv;
}
button.addEventListener('click', function(name){
try{
a();
main.innerHTML = "Place not Found!";
}
catch(err)
{
main.innerHTML = err.message;
}
})
html:
<!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>OpenWeatherMap Api</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<!-- <div class="main">
<div class="header">
<h1>OpenWeatherMap API</h1>
<p>Enter any city name in the input box below to get the data</p>
</div> -->
<div class="input">
<input type="text" placeholder="Enter the city" class="input_text">
<input type="submit" value="Submit" class="submit">
</div>
</div>
<div class="container">
<div class="card">
<h1 class="name" id="name"></h1>
<p class="aqi"></p>
<p class="temp"></p>
<p class="feels"></p>
<p class="hum"></p>
<p class="clouds"></p>
<p class="desc"></p>
<p class="lat"></p>
<p class="long"></p>
<p class="co"></p>
</div>
</div>
<script src="app.js"></script>
</body>
</html>
css:
*{
margin:0;
padding: 0;
box-sizing: border-box;
}
body{
font-family: "Nunito",sans-serif;
background: #f8f8f8;
}
.input{
text-align: center;
margin: 100px auto;
}
input[type="submit"]{
padding: 15px 30px;
background: #e7e7e7;
border: none;
border-radius: 1px;
font-family: "Nunito",sans-serif;
font-weight:bold;
font-size: 20px;
}
.input input[type="text"]{
width: 600px;
height: 55px;
padding: 5px 10px;
background: #e7e7e7;
border: none;
border-radius: 1px;
font-family: "Nunito",sans-serif;
font-weight:bold;
font-size: 20px;
}
.card{
width: 50%;
background: #e7e7e7;
height: 40vh;
margin: 50px auto;
border-radius: 2px;
}
.close{
float: right;
margin-top: -2px;
cursor: pointer;
margin-right: 20px;
}
.card h1{
padding: 5px 0;
text-align: center;
}
.card p{
text-align: center;
margin:40px 40px;
font-size:20px;
}
I am very new to js and am rquesting for suggestions for fixes in my code.

Related

Draw a line from one element to multiple elements on click

I'm trying to draw a line from an element [.identifier] to the clicked element [ A, B, C series ]. I'm able to display the line but in the other direction, not sure why it is displaying in such a direction.
Here is my fiddle: https://jsfiddle.net/SampathPerOxide/u2afymxs/11/
Can someone help me to display a line between ".identifier" and the respective series element?
Expected result on clicking A series:
on clicking B series:
$('.seriesli').click(function() {
function adjustLine(from, to, line) {
var fT = from.offsetTop + from.offsetHeight / 2;
var tT = to.offsetTop + to.offsetHeight / 2;
var fL = from.offsetLeft + from.offsetWidth / 2;
var tL = to.offsetLeft + to.offsetWidth / 2;
var CA = Math.abs(tT - fT);
var CO = Math.abs(tL - fL);
var H = Math.sqrt(CA * CA + CO * CO);
var ANG = 180 / Math.PI * Math.acos(CA / H);
if (tT > fT) {
var top = (tT - fT) / 2 + fT;
} else {
var top = (fT - tT) / 2 + tT;
}
if (tL > fL) {
var left = (tL - fL) / 2 + fL;
} else {
var left = (fL - tL) / 2 + tL;
}
if ((fT < tT && fL < tL) || (tT < fT && tL < fL) || (fT > tT && fL > tL) || (tT > fT && tL > fL)) {
ANG *= -1;
}
top -= H / 2;
line.style["-webkit-transform"] = 'rotate(' + ANG + 'deg)';
line.style["-moz-transform"] = 'rotate(' + ANG + 'deg)';
line.style["-ms-transform"] = 'rotate(' + ANG + 'deg)';
line.style["-o-transform"] = 'rotate(' + ANG + 'deg)';
line.style["-transform"] = 'rotate(' + ANG + 'deg)';
line.style.top = top + 'px';
line.style.left = left + 'px';
line.style.height = H + 'px';
}
adjustLine(
document.getElementById('div1'),
document.getElementById('div2'),
document.getElementById('line')
);
});
.identifier {
width: 10px;
height: 10px;
background-color: red;
position: absolute;
right: 45%;
top: 50%;
}
.series-div {
position: absolute;
right: 5%;
bottom: 30%;
}
.series-ul li {
list-style: none;
color: grey;
font-size: 1em;
font-weight: 600;
border: 2px solid grey;
display: table;
padding: 0.3em 0.1em;
text-align: center;
margin: 0.5em;
cursor: pointer;
}
#line {
position: absolute;
width: 2px;
margin-top: -1px;
background-color: red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div style="position;relative;">
<div class="identifier" id="div2"></div>
<div class="series-div">
<ul class="series-ul">
<li class="seriesli" id="div1">A series</li>
<li class="seriesli">B series</li>
<li class="seriesli">C series</li>
</ul>
</div>
<div id="line"></div>
<img src="https://stat.overdrive.in/wp-content/odgallery/2020/06/57263_2020_Mercedes_Benz_GLS.jpg" class="img-responsive firstcar-detail" style="width: 100%;">
</div>
I fixed your fiddle: https://jsfiddle.net/c4ju6a0p/
Code changes:
// Get actual position relative to viewport.
// See https://stackoverflow.com/a/11396681/117030
fromBCR = from.getBoundingClientRect();
toBCR = to.getBoundingClientRect();
var fT = fromBCR.top + from.offsetHeight / 2;
var tT = toBCR.top + to.offsetHeight / 2;
// Don't add offsetWidth. This connects to the middle, not the left edge.
var fL = fromBCR.left //+ from.offsetWidth / 2;
var tL = toBCR.left + to.offsetWidth / 2;
The problem was the line was being calculated with the incorrect position due to relative positioning. This can be seen more clearly when the relative CSS is commented out: https://jsfiddle.net/vust5nxf/
Also, don't add the offsetWidth if you want the line to go to the left edge.
update: didn't notice the code snippet... applied changes there, too. I also made one more change:
You need to pass the element that was clicked to adjustLine(), otherwise currently the line is drawn between the same two elements every time because the elements are hardcoded with ids.
As a style note: I would move the definition of function adjustLine() outside the click handler. This will make the code easier to read, and the function will only be created once, instead of every time a click is handled.
adjustLine(
this, // Element that was clicked.
document.getElementById('div2'),
document.getElementById('line')
);
$('.seriesli').click(function() {
function adjustLine(from, to, line) {
// Get actual position relative to viewport.
// See https://stackoverflow.com/a/11396681/117030
fromBCR = from.getBoundingClientRect();
toBCR = to.getBoundingClientRect();
var fT = fromBCR.top + from.offsetHeight / 2;
var tT = toBCR.top + to.offsetHeight / 2;
// Don't add offsetWidth. This connects to the middle, not the left edge.
var fL = fromBCR.left //+ from.offsetWidth / 2;
var tL = toBCR.left + to.offsetWidth / 2;
var CA = Math.abs(tT - fT);
var CO = Math.abs(tL - fL);
var H = Math.sqrt(CA * CA + CO * CO);
var ANG = 180 / Math.PI * Math.acos(CA / H);
if (tT > fT) {
var top = (tT - fT) / 2 + fT;
} else {
var top = (fT - tT) / 2 + tT;
}
if (tL > fL) {
var left = (tL - fL) / 2 + fL;
} else {
var left = (fL - tL) / 2 + tL;
}
if ((fT < tT && fL < tL) || (tT < fT && tL < fL) || (fT > tT && fL > tL) || (tT > fT && tL > fL)) {
ANG *= -1;
}
top -= H / 2;
line.style["-webkit-transform"] = 'rotate(' + ANG + 'deg)';
line.style["-moz-transform"] = 'rotate(' + ANG + 'deg)';
line.style["-ms-transform"] = 'rotate(' + ANG + 'deg)';
line.style["-o-transform"] = 'rotate(' + ANG + 'deg)';
line.style["-transform"] = 'rotate(' + ANG + 'deg)';
line.style.top = top + 'px';
line.style.left = left + 'px';
line.style.height = H + 'px';
}
adjustLine(
this, // Element that was clicked.
document.getElementById('div2'),
document.getElementById('line')
);
});
.identifier {
width: 10px;
height: 10px;
background-color: red;
position: absolute;
right: 45%;
top: 50%;
}
.series-div {
position: absolute;
right: 5%;
bottom: 30%;
}
.series-ul li {
list-style: none;
color: grey;
font-size: 1em;
font-weight: 600;
border: 2px solid grey;
display: table;
padding: 0.3em 0.1em;
text-align: center;
margin: 0.5em;
cursor: pointer;
}
#line {
position: absolute;
width: 2px;
margin-top: -1px;
background-color: red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div style="position;relative;">
<div class="identifier" id="div2"></div>
<div class="series-div">
<ul class="series-ul">
<li class="seriesli" id="div1">A series</li>
<li class="seriesli">B series</li>
<li class="seriesli">C series</li>
</ul>
</div>
<div id="line"></div>
<img src="https://stat.overdrive.in/wp-content/odgallery/2020/06/57263_2020_Mercedes_Benz_GLS.jpg" class="img-responsive firstcar-detail" style="width: 100%;">
</div>

How to detect events on a border of a div element [VUEJS]?

I would like to detect events on a border of an div element in vue.js.
Is there a way? that could look like this:
<div #borderMouseDown="someMethod"></div>
The Solution that worked for my use-case:
borderHandler(event){
var x = event.offsetX;
var y = event.offsetY;
if(
(x < 0 || x > this.width)
||
(y < 0 || y > this.height)
)
{
alert("Border Pressed");
}
},
What you can do is try to calculate using some math and click event parameters if the mouse is inside the border.
Try clicking the borders in the example below, and you'll see this in actions by the element changing color, and logging some text below it.
Vue.component('my-component', {
template: "#my-component",
data() {
return { messages: [], color: "red" }
},
methods: {
handleClick(ev) {
const x = ev.clientX;
const y = ev.clientY;
const borderSize = this.borderSize(this.$refs.box);
const rect = this.$refs.box.getBoundingClientRect();
if ( (x >= rect.x && x <= rect.x + borderSize) ||
(x >= rect.x + rect.width - borderSize
&& x <= rect.x + rect.width) ||
(y >= rect.y && y <= rect.y + borderSize) ||
(y >= rect.y + rect.height - borderSize &&
y <= rect.y + rect.height)) {
this.handleInsideBorders();
}
},
borderSize(box) {
return parseInt(getComputedStyle(box).getPropertyValue('border-left-width'));
},
handleInsideBorders() {
this.messages.push("I'm inside borders");
if (this.color === 'red') {
this.color = 'yellow';
} else {
this.color = 'red';
}
}
}
});
new Vue({
template: "<my-component>></my-component>"
}).$mount("#app");
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
.my-box {
width: 100px;
height: 100px;
margin: 5rem auto;
background: red;
border: 10px solid green;
transition: background 500ms ease;
}
.red {
background: red;
}
.yellow {
background: yellow;
}
.d-block {
display: block;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<script type="text/x-template" id="my-component">
<div>
<div
ref="box"
#click="handleClick"
:class="['my-box', color]">
</div>
<span class="d-block" v-for="message in messages">{{ message }}</span>
</div>
</script>
<div id="app"></div>

JavaScript: array values are automatically getting deleted

I am making an image slider/ carousel. If you drag it, the images will get momentum and will keep on moving for sometime. There are few issues, one of them is getting the following error frequently: "glide.js:104 Uncaught TypeError: Cannot read property '1' of undefined". JavaScript here is supposed to access a value that is inside an array, but since the array is empty, i'm getting this error. However, the array shouldn't be empty, as the code that empties the array, comes later. Project
var projectContainer = document.querySelector(".project-container")
var projects = document.querySelectorAll(".project")
// exProject is declared so that every project has same transalte to refer to instead of referring to their individual transalations
var exProject = projects[0]
var style = window.getComputedStyle(exProject)
exProject.currentTranslationX = (new WebKitCSSMatrix(style.webkitTransform)).m41
// after dragging, do not add force if mouse has not been moved for pauseTime milliseconds
pauseTime = 40
lastMousePositions = []
//this will set margin to 80, i thought this is better than hardcoding
elementAOffset = projects[0].offsetLeft;
elementBOffset = projects[1].offsetLeft;
elementAWidth = parseInt(getComputedStyle(projects[0]).width)
margin = (elementBOffset - (elementAOffset + elementAWidth))
//projects will teleport to other side if they hit either of the boundary
LeftSideBoundary = -(elementAWidth)
RightSideBoundary = (elementAWidth * (projects.length)) + (margin * (projects.length))
RightSidePosition = RightSideBoundary - elementAWidth;
//how often to update speed (in milliseconds)
intervalTime = 15
//how much speed is lost at every interTime milliseconds
frictionPerMilliseconds = (20 / 1000);
frictionPerMilliseconds *= intervalTime * 5;
mouseInitialPosition = 0;
mouseIsDown = false
startTime = 0;
speed = 0;
mousemoving = false
projectContainer.addEventListener("mousedown", e => {
mouseInitialPosition = e.clientX
mouseIsDown = true;
startDate = new Date();
startTime = startDate.getTime();
lastMousePositions.push(e.clientX)
speed = 0
})
projectContainer.addEventListener("mousemove", e => {
if (!mouseIsDown) return;
distanceTravelled = e.clientX - mouseInitialPosition
if (speed === 0) {
projects.forEach(project => {
project.style.transform = 'translateX(' + ((exProject.currentTranslationX) + ((distanceTravelled))) + 'px)';
shiftPosition(project, distanceTravelled)
})
}
if ((new Date()).getTime() - lastMousePositions[lastMousePositions.length - 1][1] > 50) {
lastMousePositions = []
}
pushToMousePositions(e.clientX)
})
projectContainer.addEventListener("mouseup", e => {
dragEnd(e);
})
projectContainer.addEventListener("mouseleave", e => {
dragEnd(e);
})
function dragEnd(e) {
finalPosition = e.clientX;
distanceTravelled = finalPosition - mouseInitialPosition
endDate = new Date();
endTime = endDate.getTime();
timeElapsed = (endTime - startTime) / 1000
mouseIsDown = false;
tempSpeed = distanceTravelled / timeElapsed
tempSpeed = (tempSpeed / 1000) * 15
if (tempSpeed < 0 && speed < 0) {
if (tempSpeed < speed) {
speed = tempSpeed
}
} else if (tempSpeed > 0 && speed > 0) {
if (tempSpeed > speed) {
speed = tempSpeed
}
} else {
speed = tempSpeed
}
if (lastMousePositions.length === 0) {
console.log("error gonna pop up")
}
if (endTime - (lastMousePositions[lastMousePositions.length - 1])[1] >= pauseTime) {
speed = 0
}
mouseExit(e)
intervalFunction = setInterval(move, intervalTime)
}
function mouseExit(e) {
mouseIsDown = false
lastMousePositions = []
var style = window.getComputedStyle(exProject)
exProject.currentTranslationX = (new WebKitCSSMatrix(style.webkitTransform)).m41
projects.forEach(project => {
project.style.transform = 'translateX(' + (exProject.currentTranslationX) + 'px)'
shiftPosition(project, 0)
})
}
function move() {
if (speed === 0) {
clearInterval(intervalFunction)
} else if (Math.abs(speed) <= frictionPerMilliseconds) {
style = window.getComputedStyle(exProject)
exProject.currentTranslationX = (new WebKitCSSMatrix(style.webkitTransform)).m41
projects.forEach(project => {
project.style.transform = 'translateX(' + ((exProject.currentTranslationX) + (speed)) + 'px)'
shiftPosition(project, 0)
})
speed = 0
} else {
style = window.getComputedStyle(exProject)
exProject.currentTranslationX = (new WebKitCSSMatrix(style.webkitTransform)).m41
projects.forEach(project => {
project.style.transform = 'translateX(' + ((exProject.currentTranslationX) + (speed)) + 'px)'
shiftPosition(project, 0)
})
speed < 0 ? speed += frictionPerMilliseconds : speed -= frictionPerMilliseconds;
}
}
function pushToMousePositions(positionToPush) {
if (lastMousePositions.length < 50) {
lastMousePositions.push([positionToPush, (new Date()).getTime()])
} else {
lastMousePositions.shift();
lastMousePositions.push([positionToPush, (new Date()).getTime()])
}
}
function shiftPosition(project, mouseMovement) {
//projectVisualPosition is relative to the left border of container div
projectVisualPosition = project.offsetLeft + (exProject.currentTranslationX + mouseMovement)
tempStyle = window.getComputedStyle(project)
if (projectVisualPosition < LeftSideBoundary) {
project.style.left = ((parseInt(tempStyle.left) + RightSidePosition + 350) + 'px')
}
if (projectVisualPosition > RightSidePosition) {
project.style.left = ((parseInt(tempStyle.left)) - (RightSidePosition + elementAWidth)) + 'px'
}
}
*,
*::before,
*::after {
margin: 0px;
padding: 0px;
box-sizing: border-box;
font-size: 0px;
user-select: none;
font-size: 0;
}
body {
position: relative;
}
.project-container {
font-size: 0px;
position: relative;
width: 1500px;
height: 400px;
background-color: rgb(15, 207, 224);
margin: auto;
margin-top: 60px;
white-space: nowrap;
overflow: hidden;
padding-left: 40px;
padding-right: 40px;
}
.project {
font-size: 100px;
margin: 40px;
display: inline-block;
height: 300px;
width: 350px;
background-color: red;
border: black 3px solid;
user-select: none;
position: relative;
}
<div class="project-container">
<div class="project">1</div>
<div class="project">2</div>
<div class="project">3</div>
<div class="project">4</div>
<div class="project">5</div>
<div class="project">6</div>
<div class="project">7</div>
<div class="project">8</div>
</div>
The problem is this:
projectContainer.addEventListener("mouseleave", (e) => {
dragEnd(e);
});
You're calling dragEnd(e) when the cursor leaves projectContainer. That can happen while the lastMousePositions array is still empty.
Option 1: Don't call dragEnd(e) on the mouseleave event
Option 2: Inside the dragEnd(e) function, check that the array is not empty before you try to access its elements:
if (lastMousePositions.length !== 0) {
if (
endTime - lastMousePositions[lastMousePositions.length - 1][1] >=
pauseTime
) {
speed = 0;
}
}

How can i implement a simple menu for my game made with HTML?

i'm making a simple game with HTML only, more or less it works... My question is if i can make a simple menu /with "click to start" or something similar/ with an image at the background and 1 button to start the game. And if i can make it in the same archive.
Thanks.
<canvas id="ctx" width="1024" height="800" style="border:3px solid #000000;"></canvas>
<script>
var Height = 800;
var Width = 1024;
var timeElapset = Date.now();
var ctx = document.getElementById("ctx").getContext("2d");
ctx.font = '30px Consolas';
var frameCount = 0;
var score = 0;
var player = {
x:50,
spdX:30,
y:40,
spdY:30,
name:'P',
hp:10,
width:20,
height:20,
color:'green',
};
var enemyList = {};
getDistance = function (Obj1,Obj2){
var vx = Obj1.x - Obj2.x;
var vy = Obj1.y - Obj2.y;
return Math.sqrt((vx*vx)+(vy*vy));
}
checkCollision = function (Obj1,Obj2){
var rect1 = {
x: Obj1.x - Obj1.width/2,
y: Obj1.y - Obj1.height/2,
height: Obj1.height,
width: Obj1.width,
}
var rect2 = {
x: Obj2.x - Obj2.width/2,
y: Obj2.y - Obj2.height/2,
height: Obj2.height,
width: Obj2.width,
}
return testCollisionRectRect(rect1,rect2); //true o false
}
Enemy = function (id,x,y,spdX,spdY,width,height){
var enemy = {
x:x,
spdX:spdX,
y:y,
spdY:spdY,
name:'E',
id:id,
width:width,
height:height,
color:'black',
};
enemyList[id] = enemy;
}
document.onmousemove = function(mouse){
var mouseX = mouse.clientX - document.getElementById('ctx').getBoundingClientRect().left;
var mouseY = mouse.clientY - document.getElementById('ctx').getBoundingClientRect().top;
if(mouseX < player.width/2)
mouseX = player.width/2;
if(mouseX > Width-player.width/2)
mouseX = Width - player.width/2;
if(mouseY < player.height/2)
mouseY = player.height/2;
if(mouseY > Height - player.height/2)
mouseY = Height - player.height/2;
player.x = mouseX;
player.y = mouseY;
}
updateEntity = function (Z){
updatePosition(Z);
drawPlayer(Z);
}
updatePosition = function(Z){
Z.x += Z.spdX;
Z.y += Z.spdY;
if(Z.x < 0 || Z.x > Width){
Z.spdX = -Z.spdX;
}
if(Z.y < 0 || Z.y > Height){
Z.spdY = -Z.spdY;
}
}
testCollisionRectRect = function(rect1,rect2){
return rect1.x <= rect2.x+rect2.width &&
rect2.x <= rect1.x+rect1.width &&
rect1.y <= rect2.y + rect2.height &&
rect2.y <= rect1.y + rect1.height;
}
drawPlayer = function(Z){
ctx.save();
ctx.fillStyle = Z.color;
ctx.fillRect(Z.x-Z.width/2,Z.y-Z.height/2,Z.width,Z.height);
ctx.restore();
}
update = function(){
ctx.clearRect(0,0,Width,Height);
frameCount++;
score++;
if(frameCount % 100 == 0)
randomGenerateEnemy();
for(var key in enemyList){
updateEntity(enemyList[key]);
var isColliding = checkCollision(player, enemyList[key]);
if(isColliding){
player.hp = player.hp -1;
}
}
if(player.hp <= 0){
var timeSurvived = Date.now() - timeElapset;
console.log("Has ganado Kappa, Tiempo vivo " + timeSurvived + " ms.");
ctx.fillText(" You Lose! ", Width/2, Height/2);
GameEngine();
}
drawPlayer(player);
ctx.fillText(player.hp + " Hp",20,30);
ctx.fillText('Puntuacion: ' + score/10,700,30);
}
GameEngine = function(){
player.hp = 13;
timeElapset = Date.now();
frameCount = 0;
score = 0;
enemyList = {};
randomGenerateEnemy();
randomGenerateEnemy();
randomGenerateEnemy();
randomGenerateEnemy();
}
randomGenerateEnemy = function(){
var x = Math.random()*Width;
var y = Math.random()*Height;
var height = 10 + Math.random()*70;
var width = 10 + Math.random()*70;
var id = Math.random();
var spdX = 5 + Math.random() * 5;
var spdY = 5 + Math.random() * 5;
Enemy(id,x,y,spdX,spdY,width,height);
}
GameEngine();
setInterval(update,30);
</script>
That's what i have.
The code also contains javascript.For proper gaming function .js file has to be called on your html page.Also use css to make it attractive.Consider this example
enter code here
<html>
<head>
<title>Your game title</title>
<script type="text/javascript" src="src/Common.js"></script>
<script type="text/javascript" src="src/Perlin.js"></script>
<script type="text/javascript" src="src/ChaikinCurve.js"></script>
<script type="text/javascript">
var app = null;
window.onload = function() {
utils.loadShaderXml("src/render/shaders.xml", null, function(shaders) {
if (shaders instanceof Exception) {
app = shaders;
} else {
try {
app = new App('canvas', shaders, null);
} catch (e) {
app = e;
}
}
});
document.onselectstart = function () {
return false;
};
};
function application() {
if (app == null) {
alert("Application is absent");
throw "no application";
} else if (app instanceof Exception) {
alert("An exception occured while creating the application:\n" + app.message);
throw app;
} else {
return app;
}
}
</script>
<style type="text/css">
body{
margin: 0px; padding: 0px; overflow: hidden;
background: #000;
}
#canvas-holder.active {
position: absolute;
padding: 0px;
left: 50%;
top: 50%;
}
#canvas-holder.inactive {
position: absolute;
top:50%;
width: 100%;
text-align: center;
}
#canvas {
padding: 0px;
width: 100%;
height: 100%;
color: #fff;
font-family: Allan, Arial;
font-size: 40px;
}
</style>
</head>
<body>
<div id="canvas-holder" class="inactive">
<div id="canvas">Your game` is loading...</div>
</div>
<div style="font-family: Lobster; visibility: hidden">one</div>
<div style="font-family: Allan; visibility: hidden">two</div>
<div style="font-family: Meddon; visibility: hidden">three</div>
<div style="font-family: Cuprum; visibility: hidden">four</div>
</body>
</html>

Button in update panel will not fire from javascript

If the function is called and the button is inside an update panel it will not fire (although it works if clicked directly) - place it outside the update panel and the script works.
Any ideas?
<div>
<asp:UpdatePanel ID="UpdatePanel2" runat="server">
<ContentTemplate>
<asp:Button ID="GridViewLBClicked" runat="server" />
</ContentTemplate>
<%--
<Triggers>
<asp:AsyncPostBackTrigger ControlID="GridViewLBClicked" EventName="Click" />
</Triggers>--%>
</asp:UpdatePanel>
</div>
<script>
function RaiseEvent_Click() {
document.getElementById('<%=GridViewLBClicked.ClientID%>').click();
alert('It was clicked');
}
</script>
Re Joce
I suspect that some other loaded javascript may be causing the problem as I have had the same thing working before - here is the other loaded script
function LinkButtonClick(){ alert('This was clicked'); __doPostBack('ContentPlaceHolder1_GridViewLBClicked', ''); } var sessionTimeoutWarning = '18'; var sessionTimeout = '20'; var timeOnPageLoad = new Date(); var sessionWarningTimer = null; var redirectToWelcomePageTimer = null; var sessionWarningTimer = setTimeout('SessionWarning()', parseInt(sessionTimeoutWarning) * 60 * 1000); var redirectToWelcomePageTimer = setTimeout('RedirectToWelcomePage()', parseInt(sessionTimeout) * 60 * 1000); function SessionWarning() { var minutesForExpiry = (parseInt(sessionTimeout) - parseInt(sessionTimeoutWarning)); var message = 'Your session will expire in another ' + minutesForExpiry + ' mins. Do you want to extend the session?'; $('#SessionModal').modal('show'); var currentTime = new Date(); var timeForExpiry = timeOnPageLoad.setMinutes(timeOnPageLoad.getMinutes() + parseInt(sessionTimeout)); if (Date.parse(currentTime) > timeForExpiry) { window.location = 'http://localhost:53818/Logout_Landing/SessionEnded'; } } function RedirectToWelcomePage() { window.location = 'http://localhost:53818/Logout_Landing/SessionEnded'; } $(document).ready(function(){ var divWidth = document.getElementById('imageHeader').clientWidth; var imagePadding = 75; var imageOneWidth = document.getElementById('TopImage_1').width; var imageTwoWidth = document.getElementById('TopImage_2').width; var imageThreeWidth = document.getElementById('TopImage_3').width; var imageFourWidth = document.getElementById('TopImage_4').width; var imageFiveWidth = document.getElementById('TopImage_5').width; var totalImageWidth = imagePadding + imageOneWidth + imageTwoWidth + imageThreeWidth + imageFourWidth + imageFiveWidth; var widthDifference = divWidth - totalImageWidth; var percentDifference = Math.round(widthDifference / divWidth * 100); var imageOne = document.getElementById('TopImage_1'); var imageTwo = document.getElementById('TopImage_2'); var imageThree = document.getElementById('TopImage_3'); var imageFour = document.getElementById('TopImage_4'); var imageFive = document.getElementById('TopImage_5'); var currentHeight = imageOne.height; imageOne.style.height = Math.round(currentHeight + (currentHeight / 100 * percentDifference)) + "px"; imageTwo.style.height = Math.round(currentHeight + (currentHeight / 100 * percentDifference)) + "px"; imageThree.style.height = Math.round(currentHeight + (currentHeight / 100 * percentDifference)) + "px"; imageFour.style.height = Math.round(currentHeight + (currentHeight / 100 * percentDifference)) + "px"; imageFive.style.height = Math.round(currentHeight + (currentHeight / 100 * percentDifference)) + "px"; }); window.onresize = function () { var divWidth = document.getElementById('imageHeader').clientWidth; var imagePadding = 75; var imageOneWidth = document.getElementById('TopImage_1').width; var imageTwoWidth = document.getElementById('TopImage_2').width; var imageThreeWidth = document.getElementById('TopImage_3').width; var imageFourWidth = document.getElementById('TopImage_4').width; var imageFiveWidth = document.getElementById('TopImage_5').width; var totalImageWidth = imagePadding + imageOneWidth + imageTwoWidth + imageThreeWidth + imageFourWidth + imageFiveWidth; var widthDifference = divWidth - totalImageWidth; var percentDifference = Math.round(widthDifference / divWidth * 100); var imageOne = document.getElementById('TopImage_1'); var imageTwo = document.getElementById('TopImage_2'); var imageThree = document.getElementById('TopImage_3'); var imageFour = document.getElementById('TopImage_4'); var imageFive = document.getElementById('TopImage_5'); var currentHeight = imageOne.height; imageOne.style.height = Math.round(currentHeight + (currentHeight / 100 * percentDifference)) + "px"; imageTwo.style.height = Math.round(currentHeight + (currentHeight / 100 * percentDifference)) + "px"; imageThree.style.height = Math.round(currentHeight + (currentHeight / 100 * percentDifference)) + "px"; imageFour.style.height = Math.round(currentHeight + (currentHeight / 100 * percentDifference)) + "px"; imageFive.style.height = Math.round(currentHeight + (currentHeight / 100 * percentDifference)) + "px"; }; $(document).ready(function(){ $('body').append("<style>#media (max-width: 1025px) { .navbar-header { float: none; } .navbar-left, .navbar-right { float: none !important; } .navbar-toggle { display: block; } .navbar-collapse { border-top: 1px solid transparent; box-shadow: inset 0 1px 0 rgba(255,255,255,0.1); } .navbar-fixed-top { top: 0; border-width: 0 0 1px; } .navbar-collapse.collapse { display: none !important; } .navbar-nav { float: none !important; margin-top: 7.5px; } .navbar-nav > li { float: none; } .navbar-nav > li > a { padding-top: 10px; padding-bottom: 10px; } .collapse.in { display: block !important; } .navbar-collapse.in { overflow-y: auto !important; } .navbar-nav .open .dropdown-menu { position: static; float: none; width: auto; margin-top: 0; background-color: transparent; border: 0; box-shadow: none; } .navbar-nav .open .dropdown-menu > li > a, .navbar-nav .open .dropdown-menu .dropdown-header { padding: 5px 15px 5px 25px; } .navbar-inverse .navbar-nav .open .dropdown-menu > li > a { color: #999; } .navbar-inverse .navbar-nav .open .dropdown-menu > li > a:hover, .navbar-inverse .navbar-nav .open .dropdown-menu > li > a:focus { color: #fff; background-color: transparent; background-image: none; } } </style>"); });
UPDATE
This is odd - if I run this
Dim SB As New StringBuilder
SB.Append("function LinkButtonClick(){ ")
SB.Append("$get('" & GridViewLBClicked.ClientID & "').click(); ")
SB.Append("} ")
ScriptManager.RegisterStartupScript(Me, Me.GetType(), "LoadLinkButton", SB.ToString, True)
It won't work - but if I add an alert it runs fine
Dim SB As New StringBuilder
SB.Append("function LinkButtonClick(){ ")
SB.Append("$get('" & GridViewLBClicked.ClientID & "').click(); ")
SB.Append("alert('it was clicked'); ")
SB.Append("} ")
ScriptManager.RegisterStartupScript(Me, Me.GetType(), "LoadLinkButton", SB.ToString, True)
FURTHER UPDATE
This works - I tried document.ready but that didn't - don't like using setTimeout as who knows what will happen out in the wild, so I would welcome a more robust solution
Private Sub LoadLinkButtonClick()
Try
Dim SB As New StringBuilder
SB.Append("function LinkButtonClick(){ ")
SB.Append("setTimeout(function() { ")
SB.Append("$get('" & GridViewLBClicked.ClientID & "').click(); ")
SB.Append(" }, 300); ")
SB.Append("} ")
ScriptManager.RegisterStartupScript(Me, Me.GetType(), "LoadLinkButton", SB.ToString, True)
Catch ex As Exception
Dim vError As New SendError
vError.MailError("1229", PageName, ex)
End Try
End Sub
You could try to call __doPostBack() by sending the UniqueID of the button.
function RaiseEvent_Click() {
__doPostBack('<%=GridViewLBClicked.UniqueID%>', '');
alert('It was clicked');
}
Edit:
I tried this code snippet and it works fine:
<input type="button" id="btnClickMe" value="Click me" />
<asp:UpdatePanel runat="server" ID="uPanel1">
<ContentTemplate>
<asp:TextBox runat="server" ID="txtInside"></asp:TextBox>
<asp:Button runat="server" ID="btnPostInside" />
</ContentTemplate>
</asp:UpdatePanel>
<script type="text/javascript">
$("#btnClickMe").on("click", function() {
$get("<%=btnPostInside.ClientID %>").click();
});
</script>
Can you give us more of your code?

Categories