Time condition not executing byself, need to reload whole page - javascript

I got two conditions in my code. If this condition becomes true (based on currentTime) I would like to change opacity on div element from '0' to '1'.
Second condition works same but it does opposite.
My problem:
Lets say that it supposed to work as Day / Night phase.
So when I would like to set opacity for day '0' and night '1' I need to reload whole page. Why is that not reloading by itself even though I have there setInterval?
Whole code is here : https://jsbin.com/huvoluk/1/edit?html,css,js,output
Just edit those time condition so you can see what I am trying to describe.
window.onload = function() {
// TODO:: Do your initialization job
var cs = new Date();
var hour = cs.getHours();
var minu = cs.getMinutes();
var sec = cs.getSeconds();
var tst = hour +":"+ minu +":"+ sec;
function showTime(){
var date = new Date();
var h = date.getHours(); // 0 - 23
var m = date.getMinutes(); // 0 - 59
var s = date.getSeconds(); // 0 - 59
if(h === 0){
h = 24;
}
h = (h < 10) ? "0" + h : h;
m = (m < 10) ? "0" + m : m;
s = (s < 10) ? "0" + s : s;
var time = h + ":" + m + ":" + s;
document.getElementById("MyClockDisplay").innerText = time;
document.getElementById("MyClockDisplay").textContent = time;
setTimeout(showTime, 100);
}
showTime();
function showdate(){
var d = new Date();
var days = ["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"];
document.getElementById("date").innerHTML = days[d.getDay()];
}
showdate();
// day1 tonight transition
function day1toNight3(){
if('10:00' <= tst&&tst < '20:35:20')
{
document.getElementById("day1").style.opacity = "1";
document.getElementById("night3").style.opacity = "0";
}
setInterval(day1toNight3, 10000);
}
day1toNight3();
function night3toDay1(){
if('20:35:23' <= tst&&tst < '22:58:00')
{
document.getElementById("day1").style.opacity = "0";
document.getElementById("night3").style.opacity = "1";
}
setInterval(night3toDay1, 10000);
}
night3toDay1();
};
html,
body {
width: 100%;
height: 100%;
margin: 0 auto;
padding: 0;
background-color: #000000;
color: #ffffff;
}
.page {
width: 100%;
height: 100%;
display: table;
}
.contents {
display: table-cell;
vertical-align: middle;
text-align: center;
-webkit-tap-highlight-color: transparent;
}
.clock {
position: absolute;
top: 45%;
left: 50%;
transform: translateX(-50%) translateY(-50%);
color: #FFFFFF;
font-size: 30px;
/* font-family: Orbitron; */
letter-spacing: 7px;
}
img {
position: fixed;
top: 0%;
left: 0%;
height: 360px;
width: 360px;
transition: all 5s ease;
}
#day1 {
position: absolute;
width: 360px;
height: 360px;
background-repeat: no-repeat;
}
#night3 {
position: absolute;
width: 360px;
height: 360px;
background-repeat: no-repeat;
}
#components-main {
position: absolute;
width: 100%;
height: 100%;
}
.showsDate {
position: absolute;
top: 55%;
left: 50%;
transform: translateX(-50%) translateY(-50%);
color: #FFFFFF;
font-size: 22px;
/* font-family: Orbitron; */
letter-spacing: 5px;
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0">
<meta name="description" content="test" />
<title>Web Basic Application</title>
<link rel="stylesheet" type="text/css" href="css/style.css" />
<script src="js/main.js"></script>
</head>
<body>
<div id="container">
<img id="day1" src="https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcRXHbfK8xm3PQo4fR9O-Q5_EvGnH3Tsixdm1iUay24SH2lYUIhQWw" style="opacity: 0"/>
<img id="night3" src="https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcSqK7DnhIIS444uMgbgWbPGeOfLmQkZFfvRJU3XkX_z7UBFWzkswQ" style="opacity: 0"/>
<!-- <div id="backgroundNight" style="opacity: 0;"></div>-->
<div id="MyClockDisplay" class="clock" onload="showTime()"></div>
<div id="date" class="showsDate"></div>
<div id="components-main">
<!--<div id="hand-main-hour"></div>-->
<div id="hand-main-minute"></div>
<div id="hand-main-second"></div>
</div>
</div>
<script src="js/main.js"></script>
</body>
</html>
00

Related

How can I make the bar run through in 1 second ? in html css and javascript

I'm working on a progress bar (in Javascript) that cycles through every second and then starts again.
I tried to change value with setInteval() but nothing helped me.
I hope for help, thanks
here's my 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>Document</title>
<style>
.progress {
position: relative;
width: 510px;
height: 60px;
background: #9cbab4;
overflow: hidden;
}
.progress__fill {
width: 0%;
height: 100%;
background: #009579;
transition: all 0.1s;
}
.progress__text{
position: absolute;
top: 50%;
right: 5px;
transform: translateY(-50%);
font: bold 20px 'Quicksand', sans-serif;
color: #ffffff;
}
</style>
</head>
<body>
<div class="progress">
<div class="progress__fill"></div>
<span class="progress__text">0%</span>
</div>
<script>
setInterval(function(){
value++;
}, 1000);
function updateProgressBar(ProgressBar, value){
ProgressBar.querySelector(".progress__fill").style.width = '${value}%'
ProgressBar.querySelector(".progress__text").textContent = '${value}%'
}
</script>
</body>
</html> ```
I tried reproducing your code by changing the progress, progress__fill, and progress__text into id's and changed the <div class="__" /> into <div id="__" />:
<style>
#progress {
position: relative;
width: 510px;
height: 60px;
background: #9cbab4;
overflow: hidden;
}
#progress_fill {
width: 0%;
height: 100%;
background: #009579;
transition: all 0.1s;
}
#progress_text{
position: absolute;
top: 50%;
right: 5px;
transform: translateY(-50%);
font: bold 20px 'Quicksand', sans-serif;
color: #ffffff;
}
</style>
here's the <div /> in my repro code:
<div id="progress">
<div id="progress_fill"></div>
<span id="progress_text">0%</span>
</div>
then on the <script>, You did not have a variable for value so I made one and set the value to zero: let value = 0; then concatenated it with '%'.
I used window.setInterval then changed the querySelector to document.getElementById because of the changes above.
here's what it looks like on the script tag:
<script>
let value = 0;
window.setInterval(function() {
if (value != 100) {
value++;
document.getElementById("progress_fill").style.width = value + '%';
document.getElementById("progress_text").textContent = value + '%';
}
}, 1000);
</script>
I included an if (value != 100) to stop the cycle when it reaches 100.
Hope this helps! here's my code snippet if you want some reference:
https://jsbin.com/xiwiyew/5/edit?html
I have taken you example and played around a bit.
I have changed it up for I think suits better.
Problem one was you did not call the updateProgressBar() in your interval. So it did not work.. I think the code speaks for itself. If you have a question let me know
My code. Note: you could chose to put the two lines in the update function and move them directly in the interval function. Also the function does not have a cap now. and will go above 100% if left running long enough.
Hope this helps
value = 0;
setInterval(function() {
value++;
updateProgressBar(value);
}, 1000);
function updateProgressBar(value) {
document.querySelector(".progress__fill").style.width = value + "%"
document.querySelector(".progress__text").innerHTML = value + "%"
}
Looking at your code I am geussing you are new. Try writing out/ describing what you want in your head and try have your code replicate that. Example: I want a progressbar with a value, that increments every second. (interval function tells that now). Than the logic that looks clunky/reads less easy can be put behind a function
First of all you have to understand that variables have a scope limitations, so what you can do is get value from your innerHTML and update it in each function call. this way you can get realtime value, without storing it somewhere globally.
Here is the working code for the same.
setInterval(function () {
const progress__text = document.querySelector(".progress__text");
const progress__fill = document.querySelector(".progress__fill");
if (progress__text && progress__fill) {
let value = parseInt(progress__text.innerHTML.split("%")[0]);
if (value === 100) {
progress__fill.style.width = "0%";
progress__text.innerHTML = "0%";
} else {
progress__fill.style.width = ++value + "%";
progress__text.innerHTML = ++value + "%";
}
}
}, 100);
.progress {
position: relative;
width: 510px;
height: 60px;
background: #9cbab4;
overflow: hidden;
}
.progress__fill {
width: 0%;
height: 100%;
background: #009579;
transition: all 0.1s;
}
.progress__text {
position: absolute;
top: 50%;
right: 5px;
transform: translateY(-50%);
font: bold 20px "Quicksand", sans-serif;
color: #ffffff;
}
<body>
<div class="progress">
<div class="progress__fill"></div>
<span value="0" class="progress__text">0%</span>
</div>
</body>
This isn't an accurate way of timing a animation, but pretty simple to implement
const animation = {
duration: 2, // animation length in seconds
steps: 60,
counter: 0,
incrementCounter() {
this.counter += ((1 / this.duration) * (this.steps / 1000) * 100);
this.counter = Math.min(this.counter, 100)
}
}
const draw = setInterval(updateAnimation, animation.steps);
function updateAnimation() {
animation.incrementCounter();
document.querySelector(".progress__fill").style.width = animation.counter + '%'
document.querySelector(".progress__text").textContent = animation.counter + '%'
if (animation.counter === 100) {
animation.counter = 0;
clearInterval(draw)
};
}
.progress {
position: relative;
width: 510px;
height: 60px;
background: #9cbab4;
overflow: hidden;
}
.progress__fill {
width: 0%;
height: 100%;
background: #009579;
transition: all 0.1s;
}
.progress__text {
position: absolute;
top: 50%;
right: 5px;
transform: translateY(-50%);
font: bold 20px 'Quicksand', sans-serif;
color: #ffffff;
}
<div class="progress">
<div class="progress__fill"></div>
<span class="progress__text">0%</span>
</div>

The square does not move JavaScript

I'm creating a game, the div with id "playerDiv" when I hit the space bar it should start going up but it doesn't. So I would like when I hit the space bar the div would go up high.
could you help me? could you also report me the mistakes i made?
const player = document.getElementById("playerDiv");
let inc = 0;
let playerTimeOut;
function jump() {
let x = 420 + inc;
player.top = player.top + x;
inc++
playerTimeOut = setTimeout(jump, 50);
}
window.addEventListener("keydown", checkKeyPress, false);
function checkKeyPress(key) {
if (key.key === ' ') {
jump();
}
}
body {
background-color: #222222;
}
#background {
border: solid 2px #dddddd;
width: 800px;
height: 500px;
}
#playerDiv {
background-color: #aaaaaa;
width: 60px;
height: 80px;
position: relative;
top: 420px;
left: 10px;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link href="style.css" rel="stylesheet" type="text/css">
<title>Game</title>
</head>
<body>
<div id="background">
<div id="playerDiv">
</div>
</div>
</body>
<script src="script.js"></script>
</html>
You're not passing the argument in addListener and you're not using correctly the top property, it belongs to style and needs unit , for example px
Also keyCode is deprecated, use key instead
const player = document.getElementById("playerDiv");
let inc = 0;
let playerTimeOut;
function jump() {
let x = 10 + inc;
player.style.bottom = `${x}px`
inc++
console.log(player.style.bottom)
}
//window.addEventListener("keydown", e => e.key === "(Space Character)" ? jump() : '');
//For snippet only
jump()
setTimeout(() => jump(), 1000)
* {
/* demo */
box-sizing: border-box
}
body {
background-color: #222;
}
#background {
border: solid 2px #ddd;
width: 800px;
height: 500px;
position: relative;
/* demo */
max-width: 100%
}
#playerDiv {
background-color: #aaa;
width: 60px;
height: 80px;
position: absolute;
bottom: 0px;
left: 10px;
}
<div id="background">
<div id="playerDiv">
</div>
</div>
Try this:
const player = document.getElementById("playerDiv");
let inc = 0;
let playerTimeOut;
function jump() {
let x = 10 + inc;
let style = window.getComputedStyle(player);
player.style.top = (parseInt(style.getPropertyValue('top'),10) - x) + 'px';
inc++
}
window.addEventListener("keydown", checkKeyPress, false);
function checkKeyPress(key) {
if (key.keyCode == "32") {
jump();
}
}
body {
background-color: #222222;
}
#background {
border: solid 2px #dddddd;
width: 800px;
height: 500px;
}
#playerDiv {
background-color: #aaaaaa;
width: 60px;
height: 80px;
position: relative;
top: 420px;
left: 10px;
}
<div id="background">
<div id="playerDiv">
</div>
</div>

Odd behaivour of clientWidth and offsetWidth, why do they return wrong values?

I am trying to understand why the below code snippet returns the wrong value and it doesn't matter whether I use clientWidth or offsetWidth.
const imgSize = document.querySelector('.slides').children[0].offsetWidth;
console.log(imgSize);
What does matter is where I import my script though. I found out that it will only return the correct value when I import my script at the end of my body tag, in addition, I have to keep the defer attribute!
<script src="../source/js/myJS.js" defer></script>
If I would import this in my head it is not working.
The oddest thing is when I import my script in my head with the defer attribute, then I will get randomly two values (133px or 450px), but only 450 is correct. So where does this effect come from?
I will now past the relevant css in case it is needed to answer my question because I am not sure whether it will be:
* {
box-sizing: border-box;
margin: 0;
}
body {
margin: 0;
font-size: 62.5%;
font-family: 'Rochester';
font-family: 'Open
#gen-info .container-carousel {
overflow: hidden;
width: 450px;
height: auto;
margin: auto;
position: relative;
}
#gen-info .slides {
display: flex;
align-items: center;
align-content: center;
}
#gen-info img {
width: 450px;
height: 300px;
}
#gen-info h3 {
display: none;
font-size: 1.4rem;
text-align: center;
margin: 15px 0 40px 0;
}
#gen-info .current-heading {
display: block;
}
.prevBtn {
position: absolute;
top: 50%;
z-index:2;
left: 5%;
font-size: 30px;
color: white;
opacity: 0.5;
cursor: pointer;
}
.nextBtn {
position: absolute;
top: 50%;
z-index:2;
right: 5%;
font-size: 30px;
color: white;
opacity: 0.5;
cursor: pointer;
}
.nextBtn:hover {
opacity: 1;
}
.prevBtn:hover {
opacity: 1;
}
I also have media queries but in none, is a width of 133px
Edit:
The Html
//head area
<head>
<meta charset="utf-8" />
<title>Home</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<link rel="stylesheet" type="text/css" href="../source/css/style.css" />
<link
href="https://fonts.googleapis.com/css?family=Open+Sans|Rochester&display=swap"
rel="stylesheet"
/>
<script
src="https://kit.fontawesome.com/427c34389f.js"
crossorigin="anonymous"
defer
></script>
<script src="../source/js/myJS.js" defer></script>
</head>
// img area
<section id="gen-info">
<div class="container-carousel">
<i class="fas fa-arrow-left prevBtn"></i>
<i class="fas fa-arrow-right nextBtn"></i>
<div class="slides">
<img src="../source/img/gen-info/information/WinterAlt.jpg" alt="outsideHous">
<img src="../source/img/gen-info/information/feldberg.jpg" alt="Feldberg">
<img src="../source/img/gen-info/information/bspWinter2.jpg" alt="winterTitisee">
<img src="../source/img/gen-info/information/bspWinter1.jpg" alt="snowTrecking">
</div>
</div>
</section>
//complete JS
const btnPrevList = document.querySelectorAll('.prevBtn');
const btnNextList = document.querySelectorAll('.nextBtn');
const slides = document.querySelectorAll('.slides');
const imgSize = document.querySelector('.slides').children[0].offsetWidth;
console.log(document.querySelector('.slides').children[0]);
console.log(imgSize);
const makeCloneSlides = (img, c) => {
const lastClone = img[img.length - 1].cloneNode();
const firstClone = img[0].cloneNode();
lastClone.className = 'last-clone';
firstClone.className = 'first-clone';
slides[c].insertAdjacentElement('beforeend', firstClone);
slides[c].insertAdjacentElement('afterbegin', lastClone);
};
const moveCarouselLeft = () => {
console.log('left');
};
const moveCarouselRight = () => {
console.log('right');
};
for (c = 0; c < slides.length; c++) {
let img = document.querySelectorAll('.slides')[c].children;
makeCloneSlides(img, c);
slides[c].style.transform = 'translateX(' + -imgSize + 'px)';
}
for (c = 0; c < btnPrevList.length; c++) {
btnPrevList[c].addEventListener('click', moveCarouselLeft);
}
for (c = 0; c < btnNextList.length; c++) {
btnNextList[c].addEventListener('click', moveCarouselRight);
}

Website code works fine on Chrome and Firefox, desktop or mobile, but does not work on Safari

A certain piece of my website works fine on Chrome and Firefox, but does not seem to work on Safari. I checked and all the people trying the website on iPhones had Javascript enabled. Is there something about my code that cannot be read by Safari? Are there any tools out there to test how code would be perceived on Safari that I can use with a windows computer?
Below is the code to the piece of my website. I had to replace all images and text with different content because I am forbidden to share the actual content. Essentially, this piece of the website would allow someone to input a certain metric in, via a slider bar, and see what something would look like with said metric. The slider bar seems to be movable, but images are not appearing, nor are they moving when viewing through Safari. As an additional note, I converted this code to https (what Wix refers to as all in one text block) and inserted it into my Wix website as an html element.
I realize that my JavaScript has quite a few redundancies, such as defining the same variable locally twice instead of defining it globally once. I'm looking to fix those later and get this working first (although this could be why it doesn't work on Safari?). I've never developed anything before, so any help at all would be much appreciated.
Update: I had a few people send me screenshots and the slider bar AND javascript are working, the images are just not showing up on Safari.
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">
<!-- The above 3 meta tags *must* come first in the head; any other head content must come *after* these tags -->
<meta name="description" content="">
<meta name="author" content="">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>
<!-- Box-->
<div class="wholething">
<div class="box">
<!-- Dude -->
<img class="img-square img-dude" src="https://i.pinimg.com/474x/ff/5a/74/ff5a741afd59d527f4492c593b329106--free-clipart-downloads-free-clipart-images.jpg" id="dude" </img>
<!-- Banana-->
<img class="img-square img-bn" src=" https://upload.wikimedia.org/wikipedia/commons/0/0a/Candy-clipart.svg" id="flag">
</img>
<div class="whitebox" id="whiteboxID">
</div>
<img class="gorilla" src="https://openclipart.org/download/249534/1464300474.svg" id="gorillaID" </img>
</div>
<h1 class="sliderlabel" id="sliderlabelID">Hunger level</h1>
<h1 class="sliderlabelinfo" id="sliderlabelinfoID">(drag to select)</h1>
<!-- Slider -->
<div class="slidecontainer">
<input type="range" min="3" max="10" value="5" step="0.1" class="slider" id="inchslider">
<output name="rangeVal" id="value"></output>
</div>
</div>
</body>
</html>
CSS
html {
overflow-y: hidden;
}
.wholething {
height: 100%;
width: 100%;
left: 0;
right: 0;
margin-left: auto;
margin-right: auto;
position: absolute;
}
.box {
background-color: #F5F4EF;
height: 60%;
width: 81.25%;
position: absolute;
left: 0;
right: 0;
margin-left: auto;
margin-right: auto;
border-radius: 5%;
}
.img-dude {
position: absolute;
top: 0;
bottom: 0;
margin-top: auto;
margin-bottom: auto;
margin-left: 20px;
height: 90%;
}
.img-bn {
position: absolute;
top: 0;
bottom: 0;
margin-top: auto;
margin-bottom: auto;
z-index: 2;
height: 10.125%;
}
.whitebox {
position: absolute;
background-color: #F5F4EF;
top: 0;
bottom: 0;
height: calc(15% + 15px);
width: calc(15% + 20px);
margin-top: auto;
margin-bottom: auto;
z-index: 1;
}
.gorilla {
position: absolute;
top: 0;
bottom: 0;
right: 0%;
margin-top: auto;
margin-bottom: auto;
z-index: 2;
height: 90%;
display: none;
}
.sliderlabel {
position: absolute;
left: 12.5%;
top: 61%;
font-size: 16px;
font-family: Arial;
font-weight: 900;
}
.sliderlabelinfo {
position: absolute;
left: 12.5%;
top: 66.5%;
font-size: 14px;
font-family: Arial;
font-weight: 500;
}
.slidervalue {
position: absolute;
top: 20px;
left: 28.5%;
}
.slidecontainer {
width: 75%;
position: absolute;
left: 0;
right: 0;
top: 90%;
margin-left: auto;
margin-right: auto;
}
.slider {
-webkit-appearance: none;
-moz-apperance: none;
width: 100%;
height: 10px;
background-image: -webkit-gradient( linear, left top, right top, color-stop(0.15, #4BD1A0), color-stop(0.15, #F5F4EF));
position: absolute;
outline: none;
opacity: 0.7;
-webkit-transition: .2s;
transition: opacity .2s;
border-radius: 5px;
left: 0;
right: 0;
margin-left: auto;
margin-right: auto;
}
.slider:hover {
opacity: 1;
box-shadow: 0 0 0 2px #4BD1A0;
}
.slider::-webkit-slider-thumb:hover+output {
display: block;
transform: translateX(-50%);
box-shadow: 0 0 0 2px #4BD1A0;
}
.slider:active {
opacity: 1;
box-shadow: 0 0 0 2px #4BD1A0;
}
.slider::-webkit-slider-thumb:active {
box-shadow: 0 0 0 2px #4BD1A0;
}
.slider::-webkit-slider-thumb {
-webkit-appearance: none;
appearance: none;
width: 25px;
height: 25px;
background: #F5F4EF;
cursor: pointer;
border-radius: 50%;
}
.slider::-moz-range-thumb {
width: 25px;
height: 25px;
background: #4CAF50;
cursor: pointer;
}
output {
position: absolute;
top: -50px;
left: calc(28.57% + 3.25px);
width: 80px;
height: 30px;
border: 1px solid #e2e2e2;
background-color: #4BD1A0;
border-radius: 10px;
color: white;
font-size: 14px;
line-height: 30px;
text-align: center;
vertical-align: middle;
display: block;
transform: translateX(-50%);
}
input[type=range]:hover+output {
display: block;
transform: translateX(-50%);
}
input[type=range]:active+output {
display: block;
transform: translateX(-50%);
}
input[type=range] {
background-image: -webkit-gradient(linear, left top, right top, color-stop(0.2857, #4BD1A0), color-stop(0.2857, #F5F4EF))
}
output:after {
content: "";
position: absolute;
width: 0;
height: 0;
border-top: 10px solid #4BD1A0;
border-left: 10px solid transparent;
border-right: 10px solid transparent;
top: 100%;
left: 40%;
margin-top: -1px;
}
JavaScript
$(function() {
var element = document.getElementById('dude'),
style = window.getComputedStyle(element),
width = style.getPropertyValue('width'),
height = style.getPropertyValue('height');
var slicedwidth = width.slice(0, -2);
var slicedheight = height.slice(0, -2);
var widthmargarin = ((Number(slicedwidth) * 0.55) + 20).toString() + "px";
var heightmargarin = (Number(slicedheight) * 0.488).toString() + "px";
var whiteboxwidthmargarin = ((Number(slicedwidth) * 0.55) + 25).toString() + "px";
document.getElementById("flag").style.marginLeft = widthmargarin;
document.getElementById("flag").style.marginBottom = heightmargarin;
document.getElementById("value").innerHTML = "5 points";
document.getElementById("whiteboxID").style.marginLeft = whiteboxwidthmargarin;
});
function setIcon(x, y) {
var element = document.getElementById('dude'),
style = window.getComputedStyle(element),
width = style.getPropertyValue('width'),
left = style.getPropertyValue('left'),
height = style.getPropertyValue('height');
var slicedwidth = width.slice(0, -2);
var slicedheight = height.slice(0, -2);
var widthmargarin = ((Number(slicedwidth) * 0.55) + (((x - 5) / 100 * 4.6) * Number(slicedwidth)) + 20).toString() + "px";
var heightmargarin = ((Number(slicedheight) * 0.485) + (((y - 5) / 100 * 0.5) * Number(slicedheight))).toString() + "px";
document.getElementById("flag").style.marginLeft = widthmargarin;
document.getElementById("flag").style.marginBottom = heightmargarin;
document.getElementById("flag").style.transform = "rotate(" + (7 - (x * 1.3)) + "deg)";
document.getElementById("whiteboxID").style.marginLeft = (Number(widthmargarin.slice(0, -2)) + 5).toString() + "px";
document.getElementById("whiteboxID").style.transform = "rotate(" + (7 - (x * 1.5)) + "deg)";
}
var slider = document.getElementById("inchslider");
var output = document.getElementById("value");
output.innerHTML = slider.value;
slider.oninput = function() {
output.innerHTML = this.value;
var positionXslider = 0;
var positionYslider = 0;
if (this.value >= 5) {
positionXslider = output.innerHTML;
positionYslider = output.innerHTML;
document.getElementById("flag").src = "https://upload.wikimedia.org/wikipedia/commons/0/0a/Candy-clipart.svg";
} else if (this.value >= 4 && this.value < 5) {
positionXslider = 5;
positionYslider = 5;
document.getElementById("flag").src = "https://openclipart.org/download/284444/1502025489.svg";
} else if (this.value < 4) {
positionXslider = 5;
positionYslider = 5;
document.getElementById("flag").src = "https://image.shutterstock.com/image-vector/slice-pizza-on-white-background-260nw-597727904.jpg";
} else {
positionXslider = output.innerHTML;
positionYslider = output.innerHTML;
}
setIcon(positionXslider, positionYslider);
};
$('input[type="range"]').on('input', function() {
var val = ($(this).val() - $(this).attr('min')) / ($(this).attr('max') - $(this).attr('min'));
$(this).css('background-image',
'-webkit-gradient(linear, left top, right top, ' +
'color-stop(' + val + ', #4BD1A0), ' +
'color-stop(' + val + ', #F5F4EF)' +
')'
);
});
$('input[type="range"]').on('input', function() {
var control = $(this),
controlMin = control.attr('min'),
controlMax = control.attr('max'),
controlVal = control.val(),
controlThumbWidth = 25;
var range = controlMax - controlMin;
var position = ((controlVal - controlMin) / range) * 100;
var positionOffset = Math.round(controlThumbWidth * position / 100) - (controlThumbWidth / 2) + 2.25;
var output = control.next('output');
var controlValNumber = Number(controlVal)
var controlValLabel = 0;
if (controlValNumber >= 5) {
controlValLabel = controlVal.slice(0, 3);
} else if (controlValNumber >= 4 && controlValNumber < 5) {
controlValLabel = 4;
} else if (controlValNumber < 4) {
controlValLabel = 3;
}
if (controlValNumber >= 10) {
document.getElementById("gorillaID").style.display = "block";
} else {
document.getElementById("gorillaID").style.display = "none";
}
output
.css('left', 'calc(' + position + '% - ' + positionOffset + 'px)')
.text(controlValLabel + " points")
});

HTML Pong attemp not working

I have started a pong game where the guidelines have already been set for me but I have an issue with the ball. It is very early in development but I am stuck on this problem: The X axis will not move up and down. The ball is not meant to bounce off the paddles yet. Here is my code:
Index.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Ping Pong</title>
<link href="pong.css" rel="stylesheet" type="text/css"/>
<script src="js/jquery.js" type="text/javascript"></script>
<script src="js/pong.js" type="text/javascript"></script>
</head>
<body>
<header>
<h1>Ping Pong</h1>
</header>
<!-- Scoreboard goes here -->
<div id="game">
<div id="playground">
<div id="ball"></div>
<div id="paddleA" class="paddle"></div>
<div id="paddleB" class="paddle"></div>
</div>
</div>
<!-- used for debugging -->
<div id="debug">
</div>
<footer>
This is an example of creating a Ping Pong Game.
</footer>
</body>
</html>
Pong.js
var KEY = {
UP:38,
DOWN:40,
W:87,
S:83
};
var directionX = 1;
var directionY = 1;
$(function(){
var timer = setInterval(gameloop,30)
});
//This is where the logic for the game goes.
function gameloop(){
var playground = $("#playground");
var ball = $("#ball");
var width = parseInt (playground.css("width"))
var left = parseInt (ball.css("left"));
if(left >= width){
directionX = -1;
}
else if (left <= 0){
directionX = 1;
}
var height = parseInt (playground.css("height"))
var top = parseInt (ball.css("top"));
if(top >= height){
directionY = -1;
}
else if (top <= 0){
directionY = 1;
}
ball.css("left",left+5 * directionX);
ball.css("top",height+5 * directionY);
}
function debug(text){
$("#debug").text(text);
}
And pong.css
#playground{
background: #e0ffe0 /*url(images/pixel_grid.jpg)*/;
width: 400px;
height: 200px;
position: relative;
overflow: hidden;
}
#ball {
background: #fbb;
position: absolute;
width: 20px;
height: 20px;
left: 150px;
top: 100px;
border-radius: 10px;
}
.paddle {
background: #bbf;
left: 50px;
top: 70px;
position: absolute;
width: 30px;
height: 70px;
}
#paddleB {
left: 320px;
}
#winner{
display:none;
position: relative;
width: 200px;
margin-left: 100px;
top: 30%;
font-size: 20px;
border: 3px solid red;
padding: 20px;
background-color: #FFF;
text-align:center;
font-family: Comic-Sans;
}
Oh and in case you were wondering, the js library was written for me.
You're using the height of the element instead of the offset (top).
It should be
ball.css("top", top + 5 * directionY);
I believe you need to use px when setting the CSS for top and left.
ball.css("left",(left+5 * directionX) + "px");
ball.css("top",(height+5 * directionY) + "px");

Categories

Resources