Simple Basketball Motion Javascript - javascript

What happens: When I press space button the ball moves up and stops; when press again the ball moves down.
What I need: When I press space button the ball should move up then move down!
I want to some how repeat this function twice with one click ... Its looks simple; I tried to loop twice upon the press of the space button, but it doesn't work as I expected. Any suggestions?
var body = document.getElementById('body');
var basketball = document.getElementById('basketball');
var x = 0;
var y = 0;
var counter = 0;
var inc = Math.PI / 100 ;
body.addEventListener('keydown',function(e){
var ek = e.which;
if(ek==32){
for( var i = 0; i<=1 ;i+=0.01){
x+=i;
y+= Math.sin( counter );
counter+=inc;
basketball.style.left=x;
basketball.style.bottom=y;
}
}
});
*
{
transition: all 1s;
}
#basketball
{
width: 75px;
position: absolute;
bottom: 0;
left: 10;
}
<html>
<head>
<link rel="stylesheet" href="css/index_style.css">
<title>Basket</title>
</head>
<body id="body">
<img src="https://thumbs.dreamstime.com/b/basketball-ball-transparent-checkered-background-realistic-vector-illustration-91566559.jpg" id="basketball">
<script src="js/mine.js"></script>
</body>
</html>

Try this (the function calls itself):
var body = document.getElementById('body');
var basketball = document.getElementById('basketball');
var x = 0;
var y = 0;
var counter = 0;
var inc = Math.PI / 100 ;
function bounce(e, norecall){
var ek = e.which;
console.log('keydown');
if(ek==32){
for( var i = 0; i<=1 ;i+=0.01){
x+=i;
y+= Math.sin( counter );
counter+=inc;
basketball.style.left=x;
basketball.style.bottom=y;
}
}
if (!norecall) { //only runs the first time (when norecall == undefined)
bounce(e, true)
}
}
body.addEventListener('keydown',bounce); //call bounce on keypress
*
{
transition: all 1s;
}
#basketball
{
width: 75px;
position: absolute;
bottom: 0;
left: 10;
}
<html>
<head>
<link rel="stylesheet" href="css/index_style.css">
<title>Basket</title>
</head>
<body id="body">
<img src="https://thumbs.dreamstime.com/b/basketball-ball-transparent-checkered-background-realistic-vector-illustration-91566559.jpg" id="basketball">
<script src="js/mine.js"></script>
</body>
</html>
What this does is the function bounce gets called with norecall being undefined. !norecall is then true, so the function calls itself, this time with norecall being true, so the function doesn’t get called again, therefore mimicing the mouse being pressed twice, which solves the problem.

No need for loops and stuff, you can just use css and add a class that changes the bottom from 0, and use setTimeout to remove it after some time (you need to click on the example so it will get the focus and the key events).
var body = document.getElementById('body');
var basketball = document.getElementById('basketball');
body.addEventListener('keydown',function(e){
basketball.classList.add('up');
setTimeout(function(){
basketball.classList.remove('up');
}, 300);
});
#basketball
{
transition: all 1s;
width: 75px;
position: absolute;
bottom: 0;
left: 10;
}
#basketball.up {
bottom: 25px;
}
<html>
<head>
<link rel="stylesheet" href="css/index_style.css">
<title>Basket</title>
</head>
<body id="body">
<img src="https://thumbs.dreamstime.com/b/basketball-ball-transparent-checkered-background-realistic-vector-illustration-91566559.jpg" id="basketball">
<script src="js/mine.js"></script>
</body>
</html>

Related

Cycle Through Web Pages with Start and Stop Buttons

I have a few URLs that each show the status of some industrial equipment. I'm trying to create an HTML/Javascript solution that, on load, cycles through each of the websites at a set interval, with two buttons to stop the cycle (to take a closer look at something) and restart the cycle (either from the beginning or where it left off, I'm not picky). I'm REALLY rusty, but I got what I think is a good start. Unfortunately, it doesn't work. Here are the CSS and HTML:
html,
body {
height: 100vh;
width: 100vw;
}
#btStart {
position: absolute;
width: 50px;
height: 40px;
left: 20px;
top: 50px;
}
#btStop {
position: absolute;
width: 50px;
height: 40px;
left: 20px;
top: 120px;
}
#infoFrame {
width: 100%;
height: 100%;
}
.holder {
width: 100%;
height: 100%;
position: relative;
}
<!DOCTYPE HTML>
<html>
<head>
<title>Info Cycle</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<link href="main.css" rel="stylesheet">
</head>
<body>
<div class="holder">
<iframe src="" id="infoFrame" frameborder="0" allowfullscreen>
<script type="text/javascript">
var urlArray = ['url1.com',
'url2.com',
'url3.com',
'url4.com',
'url5.com'];
var count = 0;
var i = document.getElementById('infoFrame');
var u = document.getElementById('url');
var timer = setInterval(cycleTimer, 5000);
function nextUrl() {
url = urlArray[++count];
count = (count >= urlArray.length - 1)? -1 : count;
return url;
}
function cycleTimer() {
u.innerHTML = '';
i.src = nextUrl();
i.onload = function(){
u.innerHTML = i.src;
}
}
</script>
</iframe>
<button type="button" id="btStart" onclick="var timer = setInterval(cycleTimer, 5000);">Start</button>
<button type="button" id="btStop" onclick="clearInterval(timer)";>Stop</button>
</div>
</body>
<footer>
</footer>
</html>
Before I added the buttons it would load, then 5 seconds later it would cycle correctly, and so on. Now it only shows the buttons. Looking at the requests, I believe what's happening in my CSS and structure is trash, and it's loading the appropriate URL, but not displaying. I should add, prior to the buttons I only had the iframe with the script in it as a proof of concept. I div'd it, added the stylesheet, and added the buttons, and now here we are.
This may be a rookie mistake, or something more complicated. I haven't done development in a long time, and I'm just trying to solve a little problem at work. If you could spare a minute, I'd be happy to know how to fix this, and also any feedback on what I could be doing better. I'd love to get back into doing more of this, so I'm interested to learn anything the community can share. I've searched the site and the internet, and I've found a couple of related solutions but nothing for this in particular.
Thanks!
EDIT:
In case it helps, below is the HTML before the buttons and stylesheet, which worked (it rotated between webpages every 7 seconds):
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Info Cycle</title>
</head>
<body>
<iframe id="frame" src=""
style="
position: fixed;
top: 0px;
bottom: 0px;
right: 0px;
width: 100%;
border: none;
margin: 0;
padding: 0;
overflow: hidden;
z-index: 999999;
height: 100%;
"></iframe>
<script type="text/javascript">
var urlArray = ['url1.com',
'url2.com',
'url3.com',
'url4.com',
'url5.com'];
var count = 0;
var i = document.getElementById('frame');
var u = document.getElementById('url');
var timer = setInterval(cycleTimer, 7000);
function nextUrl() {
url = urlArray[++count];
count = (count >= urlArray.length - 1)? -1 : count;
return url;
}
function cycleTimer() {
u.innerHTML = '';
i.src = nextUrl();
i.onload = function(){
u.innerHTML = i.src;
}
}
</script>
</body>
</html>
The iframe style was something I found in an old file I'd written (probably copied and pasted from Stack Overflow to just get a thing to work).
The problem here is having the script inside the iframe. If you move your script out of the iframe and put it under body or head then it will work.
<!DOCTYPE HTML>
<html>
<head>
<title>Info Cycle</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<link href="main.css" rel="stylesheet">
<script type="text/javascript">
var urlArray = ['url1.com',
'url2.com',
'url3.com',
'url4.com',
'url5.com'];
var count = 0;
var timer = setInterval(cycleTimer, 5000);
function nextUrl() {
url = urlArray[++count];
count = (count >= urlArray.length - 1) ? -1 : count;
return url;
}
function cycleTimer() {
var i = document.getElementById('infoFrame');
var u = document.getElementById('url');
u.innerHTML = '';
i.src = nextUrl();
i.onload = function () {
u.innerHTML = i.src;
}
}
</script>
</head>
<body>
<div class="holder">
<iframe src="" id="infoFrame" frameborder="0" allowfullscreen>
</iframe>
<button type="button" id="btStart" onclick="var timer = setInterval(cycleTimer, 5000);">Start</button>
<button type="button" id="btStop" onclick="clearInterval(timer)" ;>Stop</button>
</div>
</body>
<footer>
</footer>
</html>

How can I update "event.clientX" every sec?

I need to console log x coordinate every 1 sec when pointer is on picture but I have no idea how to update "event" from the js code.
function onPic(event) {
let xOnPic = event.clientX;
console.log(xOnPic);
setTimeout(onPic, 1000);
}
.testDiv {
width: 700px;
height: 350px;
background-image: url("./Pic/pic1.jpeg");
background-repeat: no-repeat;
background-size: 700px 350px;
}
<div onmouseover="onPic(event)" src="./Pic/pic1.jpeg" class="testDiv">
</div>
You need to throw the event more often. Use onmousemove for that. If you want to restrict the amount of outputs you can do that with a variable.
var wait = false
function onPic(event) {
if (!wait) {
wait = true;
let xOnPic = event.clientX;
console.log(xOnPic);
setTimeout(() => wait = false, 1000);
}
}
.testDiv {
width: 700px;
height: 350px;
background-image: url("./Pic/pic1.jpeg");
background-repeat: no-repeat;
background-size: 700px 350px;
}
<!DOCTYPE html>
<html>
<head>
<title>I have no title</title>
<meta charset="UTF-8">
<link rel="stylesheet" href="test.css">
</head>
<body>
<div onmousemove="onPic(event)" src="./Pic/pic1.jpeg" class="testDiv">
</div>
<script src="test.js"></script>
</body>
</html>
I should note that this will only trigger if the mouse actually moved in between, but that is what you usually want.
If you always want to update simply set an variable and output that every second.
let interval = null;
let xPos = 0;
function onEnter() {
interval = setInterval(() => {
console.log(xPos);
}, 1000);
}
function onMove(event) {
xPos = event.clientX;
}
function onLeave() {
clearInterval(interval);
}
.testDiv {
width: 700px;
height: 350px;
background-image: url("./Pic/pic1.jpeg");
background-repeat: no-repeat;
background-size: 700px 350px;
}
<!DOCTYPE html>
<html>
<head>
<title>I have no title</title>
<meta charset="UTF-8">
<link rel="stylesheet" href="test.css">
</head>
<body>
<div onmouseenter="onEnter(event)" onmousemove="onMove(event)" onmouseleave="onLeave(event)" src="./Pic/pic1.jpeg" class="testDiv">
</div>
<script src="test.js"></script>
</body>
</html>
here is a working fiddle. Just use mouseenter mouseleave and mousemove and set Intervall.
JS fiddle
HTML
<svg id="svg" class="pic">
</svg>
JS
let mouseInPic = false;
let x;
$("#svg").on("mouseenter", () => {
mouseInPic = true
})
$("#svg").on("mouseleave", () => {
mouseInPic = false
})
$("#svg").on("mousemove", (e) => {
x = e.clientX
})
window.setInterval(function(){
if(mouseInPic == true){
console.log(x)
}
}, 1000);
Here you have a native JS implementation, with 1 second throttling of the updates, so it will console the position every second but not more often than every second. Since it is not possible to get the mouse position without a mouse event when mouse is over the element but not moving, you will need to remember the position of the mouse and store it into global variable, if mouse is moved on mousemove, just update the new position xOnPic.
Use mouseover and mousemove to detect if mouse is over the selected element and mouseout to detect when mouse is out of the element, so that you can stop printing to console.
var xOnPic = 0
var mouseOverPic = false;
var tryingToUpdate = false;
function tryToUpdate(){
if (!tryingToUpdate){
tryingToUpdate = true
console.log(xOnPic);
setTimeout(onPic, 1000);
}
}
function onPic(){
if (mouseOverPic){
console.log(xOnPic);
setTimeout(onPic, 1000);
}else{
tryingToUpdate = false;
}
}
document.getElementById('Pic').addEventListener('mousemove', function(e){
xOnPic = e.clientX;
mouseOverPic = true;
tryToUpdate();
});
document.getElementById('Pic').addEventListener('mouseover', function(e){
xOnPic = e.clientX;
mouseOverPic = true;
tryToUpdate();
});
document.getElementById('Pic').addEventListener('mouseout', function(e){
xOnPic = '';
mouseOverPic = false;
});
.testDiv{
width: 700px;
height: 350px;
background-image: url("./Pic/pic1.jpeg");
background-repeat: no-repeat;
background-size: 700px 350px;
}
<!DOCTYPE html>
<html>
<head>
<title>I have no title</title>
<meta charset = "UTF-8">
<link rel = "stylesheet" href = "test.css">
</head>
<body>
<div id='Pic' src="./Pic/pic1.jpeg" class = "testDiv">
</div>
<script src = "test.js"></script>
</body>
</html>
Use
setInterval(onPic,1000);

Tracking random div across page

Trying to move my div randomly around page. Currently new randomly generated div appears on new location on page as opposed to transitioning to new position (I want div to track across page instead of deleting itself and reappearing).
function randomdiv1 () {
var divnum = $('.random').length;
var random = $('.random');
var startleft =random.css('left', (Math.floor(Math.random() * ($(window).width()-50))));
var starttop =random.css('top', (Math.floor(Math.random() * ($(window).height()-50))));
return [startleft, starttop];
}
function randomdiv2 () {
var divnum = $('.random').length;
var random = $('.random');
var endleft =random.css('left', (Math.floor(Math.random() * ($(window).width()-50))));
var endtop =random.css('top', (Math.floor(Math.random() * ($(window).height()-50))));
return [endleft, endtop];
}
function randomdiv3 () {
var startdiv = randomdiv1 ();
var enddiv = randomdiv2 ();
$('.random').animate({
top: enddiv[1],
left: enddiv[0],
}, 2000, 'swing', randomdiv3);
}
randomdiv3 ();
.random {
width: 50px;
height: 50px;
background-color: blue;
position: absolute;
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title></title>
<link rel="stylesheet" href="style.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<script src="script.js"></script>
</head>
<body>
<div class="random"></div>
</body>
</html>
This can be achieved in a simple way by adding the following css property to .random:
transition: left 2s, top 2s;
https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Transitions/Using_CSS_transitions
Example below:
https://jsfiddle.net/4r9xch2v/

DOM not updating after adding a class to a div?

I'm trying to write a program that collects all class names in a div, stores them in an array and pushes them all back to the DOM with a class called blue at the end, this is the HTML:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>some title</title>
<style>
.blue{
width: 200px;
height: 200px;
background: blue;
}
</style>
</head>
<body>
<div class="someClass otherClass" id="box"></div>
<button id="btn">click</button>
</body>
</html>
The thing is, I know how to get all the class names inside the div and even how to push blue (on btn click) inside of that div together with the other values I have collected but why isn't the blue box showing up? What am I missing?
var domManipulation = function(){
var box = document.querySelector('#box');
var btn = document.querySelector('#btn');
var class_list = [];
if(box.classList.length > 0){
for(var i = 0; i < box.classList.length; i++){
class_list.push(box.classList[i]);
}
}
btn.addEventListener('click', function(){
class_list.push("blue");
box.classList.add(class_list);
console.log(class_list);
});
}();
Here is a JsBin and I can't use jQuery btw.
This is the problem:
box.classList.add(class_list);
You can't add a whole array of classes because they end up being comma-separated.
var domManipulation = function() {
var box = document.querySelector('#box');
var btn = document.querySelector('#btn');
var class_list = [];
if (box.classList.length > 0) {
for (var i = 0; i < box.classList.length; i++) {
class_list.push(box.classList[i]);
}
}
btn.addEventListener('click', function() {
class_list.push("blue");
class_list.forEach(function(e){
box.classList.add(e);
})
console.log(class_list);
});
}();
#box {height: 50px; background: #eee}
#box.blue {background: blue}
<div class="someClass otherClass" id="box"></div>
<button id="btn">click</button>

jquery animation and float not floating

I have two images I want to be stuck together for lack of a better term. As the image on the left animates off the screen, the right image just sits there not moving. I have tried to use position: relative; in the CSS for the right-hand image and even tried to animate it by adding to the javascript (see comments in the js file) but it didn't change anything.
The HTML
<!DOCTYPE HTML>
<HTML>
<HEAD>
<link rel="stylesheet" type="text/css" href="slidetest01.css">
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js" ></script>
<script src="./javascripts/picslider01a.js"></script>
</HEAD>
<BODY onload="picrotate()">
<div id="slideshow"><img id="picshown" src="./pix/mtn01.jpg">
<img id="pichidden" src="./pix/mtn02.jpg"></div>
</BODY>
</HTML>
The CSS
#slideshow {
position: relative;
left:0px;
top:0px;
width: 1200px;
float: left;
}
#picshown {
position: relative;
float: left;
}
#pichidden {
float: left;
}
The javascript
function picrotate () {
var picts = new Array();
picts[0] = "./pix/mtn01.jpg";
picts[1] = "./pix/mtn02.jpg";
picts[2] = "./pix/mtn03.jpg";
picts[3] = "./pix/mtn04.jpg";
picts[4] = "./pix/mtn05.jpg";
var count = 2;
function rotator() {
$("#picshown").animate({left: "-600px"});
//Tried adding $("#pichidden").animate({left: "0px"}); here but did not work
//Need to delay since the rest triggers immediately after transition starts.
setTimeout(function () { //1 second should be enough time for the slide.
count = (count+1)%5;
var discard = document.getElementById("picshown"); //removes old picture
discard.parentNode.removeChild(discard);
document.getElementById("pichidden").setAttribute("id", "picshown"); //makes current picture the active one
ith = document.createElement("img"); //create a new image
ith.id = "pichidden";
ith.src = picts[count];
$("#slideshow").append(ith);//Append it to the slideshow
}, 1000);
} //end rotator
setInterval(rotator, 2000);
} // end picrotate

Categories

Resources