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>
Related
I have created a player and I expected it to be smooth as a youtube player. But my player is not that smooth. and it also gives some bug-like
If I mouse down the slider and mousemove it and it slides but after mouse up, it doesn't stop the slide on mousemove and it doesn't give the same result I expected
window.onload = function(){
var music = document.getElementById('music');
music.src = 'https://fr01.mp3snow.com/4d1c6fa75beebf67d9969/Charlie%20Puth%20-%20We%20Don%20t%20Talk%20Anymore%20feat.%20Selena%20Gomez.mp3'
setTimeout(()=>{
var play = document.getElementById('playpause')
//slider for music
var slider = document.getElementById('slider');
//slider Container for slider in music player
var sliderCon = document.getElementById('sliderCon');
var clicked = false;
var body = document.querySelector('body');
var timer = document.getElementById('time');
var durat = document.getElementById('duration');
sliderCon.onmousedown = (e) => {
music.currentTime = (e.offsetX/sliderCon.offsetWidth)*music.duration;
clicked = true;
}
window.onmousemove = (e) =>{
if(clicked == true){
music.currentTime = (e.offsetX/sliderCon.offsetWidth)*music.duration;
if(music.ended == true){
music.play()
}
body.style.cursor = 'grabbing' ;
}
window.onmouseup = () => {
clicked = false;
body.style.cursor = 'inherit';
}
}
function timing(totaltime){
if (totaltime>60){
var minute = Math.floor(totaltime/60)
var second = Math.floor(totaltime%60)
if(minute>9){
var time;
if (second >9){
time = minute+':'+second;
}else{
time = minute+':'+'0'+second;
}
}else if (minute<10){
var time;
if (second >9){
time = '0'+minute+':'+second;
}else{
time = '0'+minute+':'+'0'+second;
}
}
}
else{
if (totaltime<10){
var time = '00:0'+Math.floor(totaltime)
}else{
var time = '00:'+Math.floor(totaltime)
}
}
return time;
}
music.ontimeupdate = () =>{
var sliderWidth = (music.currentTime/music.duration)*100;
slider.style.width = sliderWidth+'%';
timer.innerHTML = timing(music.currentTime)
durat.innerHTML = timing(music.duration)
}
play.onselect = () =>{
document.click();
}
play.onclick = (e) => {
if(music.paused == true || music.ended == true){
music.play();
play.innerHTML = '<i class="fas fa-pause"></i>';
}else if (music.paused == false || music.ended == false){
music.pause();
play.innerHTML = '<i class="fas fa-play"></i>';
}
}
window.onkeydown = (key) => {
if (key.key == 'ArrowRight'){
music.currentTime += 5
}
if (key.key == 'ArrowLeft') {
music.currentTime -= 5
}
if (key.key == ' ') {
if(music.paused == true || music.ended == true){
music.play();
play.innerHTML = 'PAUSE';
}else if (music.paused == false || music.ended == false){
music.pause();
play.innerHTML = 'PLAY';
}
}
if (key.key == 'ArrowUp'){
if(music.volume < 1){
music.volume +=0.1;
}
}
if (key.key == 'ArrowDown'){
if(music.volume > 0.1){
music.volume -=0.1;
}
}
if (key.code == 'NumpadAdd'){
if (music.playbackRate < 2.0){
music.playbackRate += 0.1
}
}
if (key.code == 'NumpadSubtract'){
if (music.playbackRate > 0.1){
music.playbackRate -= 0.1
}
}
if (key.key == 'h'){
music.playbackRate = -1.0;
}
}
},0)
var loaded = document.getElementById('loaded');
console.log(loaded)
music.addEventListener('progress', function(e) {
setTimeout(()=>{
loaded.style.width = Math.round((this.buffered.end(0)/this.duration) * 100)+'%';
},6)
});
}
*{
margin: 0;
padding: 0;
}
body{
background-color: rgba(32, 29, 29, 0.89);
}
.playpause{
color: rgb(255, 248, 248);
left: 22%;
position: relative;
top: 16%;
font-size: 3rem;
font-family: sans-serif;
}
#duration{
color: rgb(255, 248, 248);
text-align: right;
margin-right: 5px;
font-size: 1rem;
font-family: sans-serif;
position: relative;
top: -1rem;
}
#time{
color: rgb(255, 248, 248);
text-align: left;
margin-left: 5px;
font-size: 1rem;
font-family: sans-serif;
}
#fornow{
background-color: rgb(116, 116, 150);
width: 80%;
margin: 50px auto;
height: 150px;
}
.sliderCon{
width: 90%;
margin: 0 auto;
position: relative;
top: 70px;
background-color: rgb(197, 192, 192);
height: 6px;
transition: 0.3s;
}
.slider{
position: relative;
height: 100%;
width: 0%;
transition: 0.3s;
background-color: rgb(228, 54, 54);
}
.sliderCon:hover{
height: 10px;
top: 67px;
cursor: grab;
}
.thumb{
width: 18px;
height: 18px;
background-color: rgb(228, 54, 54);
position: absolute;
margin-left: 98%;
border-radius: 50%;
margin-top: -5px;
transition: 0.3s;
pointer-events: none;
}
.sliderCon:hover .thumb{
margin-left: 97%;
width: 20px;
height: 20px;
}
#loaded{
background-color: rgba(226, 95, 95, 0.616);
position: absolute;
width: 0%;
height: 100%;
}
#loading{
width: 60px;
height: 60px;
background-color: transparent;
margin: 0 auto;
border: 5px solid;
border-color: teal;
transition: 1s;
border-radius: 50%;
animation: load 1s infinite;
animation-fill-mode: both;
border-top-color: tomato;
display: none;
}
#keyframes load{
to{
transform: rotate(360deg);
}
}
.yo{
width: 75px;
height: 75px;
background-color: cyan;
margin: 0 auto;
border-radius: 50%;
position: relative;
}
<!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>Player</title>
<link rel="stylesheet" href="https://pro.fontawesome.com/releases/v5.10.0/css/all.css" integrity="sha384-AYmEC3Yw5cVb3ZcuHtOA93w35dYTsvhLPVnYs9eStHfGJvOvKxVfELGroGkvsg+p" crossorigin="anonymous"/>
<link rel="stylesheet" href="./style.css">
</head>
<body>
<audio src="./" id="music"></audio>
<div class="player">
<div id="fornow">
<div class="sliderCon" id="sliderCon">
<div id="loaded">
</div>
<div class="slider" id="slider">
<div class="thumb" id="thumb"></div>
</div>
</div>
</div>
<div id="time">00:00</div>
<div id="duration">00:00</div>
<div id="loading">
</div>
<div class="controls">
<div class="backward"></div>
<div class="yo">
<div class="playpause" id="playpause"><i class="fas fa-play"></i></div>
</div>
<div class="forward"></div>
</div>
</div>
<script src="./script.js"></script>
</body>
</html>
It is the Code You can run it and see that it is not smooth as youtube
and it is also declared that youtube player is not flash
so what is the secret of youtube players that I don't know?
Please tell me the answer if anyone knows. sorry This is my personal project so I didn't commented it or name it very well
Thank You
I'm learning javascript and I've faced with a strange case while doing the gallery example in the MDN. I decided to add a simple function to this example but it didn't work. My goal is to add a function to the ".displayed-img" img.
I know that the issue is because of the "overlay" div. and I can run my function when I comment that line in the HTML. But I wonder what would be the best approach when I have a case like this and I need to access to an object which sits beneath another one. Thanks.
Here is my code:
var displayedImage = document.querySelector('.displayed-img');
var thumbBar = document.querySelector('.thumb-bar');
var btn = document.querySelector('button');
var overlay = document.querySelector('.overlay');
var imgUrl, currentImgUrl;
/* Looping through images */
for (var i = 0; i < 5; i++) {
imgUrl = 'https://via.placeholder.com/640x48'+(i+1)+'.jpg';
var newImage = document.createElement('img');
newImage.setAttribute('src', imgUrl);
thumbBar.appendChild(newImage);
newImage.addEventListener ('click', function(e){
displayedImage.setAttribute('src', e.target.getAttribute('src'));
} );
}
displayedImage.addEventListener('click', sayHi);
function sayHi(){
console.log('hi');
}
btn.onclick = function() {
if (btn.getAttribute('class')==='dark') {
overlay.style.backgroundColor = 'rgba(0,0,0,0.5)';
btn.textContent = 'Light';
btn.setAttribute('class', 'light');
} else {
overlay.style.backgroundColor = 'rgba(0,0,0,0)';
btn.textContent = 'Darken';
btn.setAttribute('class', 'dark');
}
}
body {
width: 640px;
margin: 0 auto;
}
.full-img {
position: relative;
display: block;
width: 640px;
height: 480px;
}
.overlay {
position: absolute;
top: 0;
left: 0;
width: 640px;
height: 480px;
background-color: rgba(0, 0, 0, 0);
}
button {
border: 0;
background: rgba(150, 150, 150, 0.6);
text-shadow: 1px 1px 1px white;
border: 1px solid #999;
position: absolute;
cursor: pointer;
top: 2px;
left: 2px;
}
.thumb-bar img {
display: block;
width: 20%;
float: left;
cursor: pointer;
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Image gallery</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<h1>Image gallery example</h1>
<div class="full-img">
<img class="displayed-img" src="https://via.placeholder.com/640x480">
<div class="overlay"></div>
<button class="dark">Darken</button>
</div>
<div class="thumb-bar">
</div>
<script src="main.js"></script>
</body>
</html>
I'm pretty new to Javascript and have two onkeydown problems:
I have a walking person (gif) which I want to move by using the arrow keys. When it collides with another div container an invisible layer should become visible. Now I can see that the gif is reacting to the key pressing but it isn't moving to the sides. Do you see where my mistake is?
As I said the gif is showing a walking person. When no key is pressed, the person stands still (png); when left arrow is pressed it walks to the left (gif) and same with right. The problem is that when I press the arrow keys a little longer the gifs stops continuing after a very short time. How can I make Javascript to understand a permanent pressed key as one signal that is continuing?
Sorry for my bad code adding skills; never shared a code with anybody else and don't have an idea what might be relevant for you to understand my problem. I really hope you can help me.
var x=0 ; var y=440 ; // = Karl Koordinaten
var xHA2=795; var yHA2=430; // = Haus2 Koordinaten
var xHA3=433; var yHA3=565; // = Haus3 Koordinaten
var xHO1=250; var yHO1=90; // = Hotel1 Koordinaten
var TastenC; var C; var T; // TastenCode, Code, Taste
var aktiv; // speichert setInterval
function Richtung(C,Velocity) {
// Velocity = speed oder static; dateiname wird zusammengesetzt
if (C==37) { T="L"; window.document.images[0].src="Bilder/karl"+Velocity+"_L.gif"; }
else if (C==39) { T="R"; window.document.images[0].src="Bilder/karl"+Velocity+"_R.gif"; }
else { T="X"; } ;
//return T;
}
function Kollision() {
// Kollisionserkennung Karl mit Haus2
if ((Math.abs(y-yHA2)) <= 40) {
if ((Math.abs(x-xHA2)) <= 40) {
document.getElementById("Layer_haus2").style.visibility = 'visible'; // haus2 getroffen
document.getElementById("Layer_haus3").style.visibility = 'hidden'; // Andere Ebenen ausblenden
document.getElementById("Layer_hotel1").style.visibility = 'hidden';
}
}
// Kollisionserkennung Karl mit Haus3
if ((Math.abs(y-yHA3)) <= 68) {
if ((Math.abs(x-xHA3)) <= 68) {
document.getElementById("Layer_haus3").style.visibility = 'visible'; // haus3 getroffen
document.getElementById("Layer_hotel1").style.visibility = 'hidden'; // Andere Ebenen ausblenden
document.getElementById("Layer_haus2").style.visibility = 'hidden';
}
}
// Kollisionserkennung Karl mit Hotel1
if ((Math.abs(y-yHO1)) <= 68) {
if ((Math.abs(x-xHO1)) <= 68) {
document.getElementById("Layer_hotel1").style.visibility = 'visible'; // ("hotel1 getroffen!");
document.getElementById("Layer_haus2").style.visibility = 'hidden'; // Andere Ebenen ausblenden
document.getElementById("Layer_haus3").style.visibility = 'hidden';
}
}
}
function AUS() {
document.getElementById("Layer_haus2").style.visibility = 'hidden'; // Alle Ebenen ausblenden
document.getElementById("Layer_haus3").style.visibility = 'hidden';
document.getElementById("Layer_hotel1").style.visibility = 'hidden';
}
function Objektbewegung(Taste) {
if (Taste=="L") {x-=2; xHA2=(xHA2-haus2mitbew); xHA3=(xHA3-haus3mitbew); xHO1=(xHO1-hotel1mitbew); } ;
if (Taste=="R") {x+=2; xHA2=(xHA2+haus2mitbew); xHA3=(xHA3+haus3mitbew); xHO1=(xHO1+hotel1mitbew); } ;
if (Taste=="X") { yHA2=(yHA2+haus2mitbew); yHA3=(yHA3-haus3mitbew); yHO1=(yHO1-hotel1mitbew); } ;
Kollision();
document.getElementById("karl_laufen").style.left = x;
document.getElementById("karl_laufen").style.top = y;
document.getElementById("haus2").style.left = xHA2;
document.getElementById("haus2").style.top = yHA2;
document.getElementById("haus3").style.left = xHA3;
document.getElementById("haus3").style.top = yHA3;
document.getElementById("hotel1").style.left = xHO1;
document.getElementById("hotel1").style.top = yHO1;
}
function TasteGedrueckt(Ereignis) {
if (!Ereignis) { Ereignis = window.event; }
if (Ereignis.which) { TastenC = (Ereignis.which); }
else if (Ereignis.keyC) { TastenC = (Ereignis.keyC); }
Richtung(TastenC,"speed");
window.clearInterval(aktiv); // Ruecksetzen des Intervalls bei jedem Tastendruck
aktiv = window.setInterval("Objektbewegung(T)", 5); // Intervall alle x Millisekunden ausfŸhren
//Objektbewegung(T); // einzeln weitergehen
}
function TasteLosgelassen(Ereignis) {
if (!Ereignis) { Ereignis = window.event; }
if (Ereignis.which) { TastenC = (Ereignis.which); }
else if (Ereignis.keyC) { TastenC = (Ereignis.keyC); }
Richtung(TastenC,"static");
window.clearInterval(aktiv);
haus2mitbew=0;
haus3mitbew=0;
hotel1mitbew=0;
}
document.onkeydown = TasteGedrueckt;
document.onkeyup = TasteLosgelassen;
#airbnb_cityscape {
background-image: url("../Bilder/cityscape_hintergrund.png");
height: 768px;
width: 1280px;
}
#karl_laufen {
width: 200px;
height: 300px;
visibility: visible;
position: absolute;
z-index: 2;
top: 440px;
left: 0px;
border: 0;
}
#haus1 {
visibility: visible;
position: absolute;
z-index: 2;
top: 436px;
left: 1045px;
width: 232px;
height: 201px;
border: 0;
}
#haus2 {
visibility: visible;
position: absolute;
z-index: 5;
top: 430px;
left: 795px;
width: 255px;
height: 207px;
border: 0;
}
#haus3 {
visibility: visible;
position: absolute;
z-index: 4;
top: 433px;
left: 565px;
width: 198px;
height: 208px;
border: 0;
}
#haus4 {
visibility: visible;
position: absolute;
z-index: 1;
top: 427px;
left: 0px;
width: 244px;
height: 210px;
border: 0;
}
#hotel1 {
visibility: visible;
position: absolute;
z-index: 3;
top: 90px;
left: 250px;
width: 304px;
height: 549px;
border: 0;
}
#Layer_haus2 {
visibility: hidden;
position: absolute;
z-index: 5;
margin-top: 366px;
margin-left: 1000px;
border: 0px;
}
#Layer_haus3 {
visibility: hidden;
position: absolute;
z-index: 6;
top: 320px;
right: 120px;
width: 400px;
height: 200px;
background-color: #8F8;
}
#Layer_hotel1 {
visibility: visible;
position: absolute;
z-index: 7;
border: 0px;
height: 768px;
width: 1280px;
background-color: rgba(255, 255, 255,0.5);
}
#hotelier {
margin-top: 333px;
margin-left: 950px;
position: absolute;
}
.sprechblase {
background-image: url("../Bilder/Sprechblase.png");
position: absolute;
margin-top: 270px;
margin-left: 470px;
height: 314px;
width: 525px;
}
#hoteliertext {
height: 300px;
width: 420px;
margin-left: 20px;
margin-top: 20px;
margin-right: 20px;
font-family: "Source Sans Pro";
font-size: 2em;
font-weight: 300;
}
#hotelier_karl {
margin-top: 333px;
position: absolute;
}
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<title>Wo soll Karl wohnen?</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link href='http://fonts.googleapis.com/css?family=Source+Sans+Pro:300' rel='stylesheet' type='text/css'>
<script src="js/script2.js"></script>
<link rel="stylesheet" href="css/style.css">
</head>
<body>
<div id="airbnb_cityscape">
<div id="karl_laufen">
<img src="Bilder/Karlstatic_R.png">
</div>
<div id="haus1">
<img src="Bilder/haus1.png">
</div>
<div id="haus2">
<img src="Bilder/haus2.png">
</div>
<div id="haus3">
<img src="Bilder/haus3.png">
</div>
<div id="haus4">
<img src="Bilder/haus4.png">
</div>
<div id="hotel1">
<img src="Bilder/hotel1.png">
</div>
<div id="Layer_haus2" onclick="AUS();"> </div>
<div id="Layer_haus3" onclick="AUS();"> </div>
<div id="Layer_hotel1" onclick="AUS();">
<div id="hotelier_karl"><img src="Bilder/hotelier_karl.png"></div>
<div id="hotelier"><img src="Bilder/hotelier.gif"></div>
<div class="sprechblase"><div id="hoteliertext">Schön, dass du dich für unser Hotel interessierst! In unserem 5-Sterne-Superior-Hotel kostet eine Nacht 120€</div></div>
</div>
</div>
</body>
</html>
I've been searching a lot on the site and the web but can't really seem to find any help. My problem is that I need to make a function that creates a new div box on the press of a button and that div box needs to be draggable and editable.
function makeNote(e) {
// Check the event object if the .click is on the canvas
// or a created note
if (e.eventPhase === 2) {
// Create the new comment at the corsor postition
var $newbox = $('<div class="ui-widget-content" id="newbox" style="top:' + e.pageY + 'px; left: ' + e.pageX + 'px;"><span id="close">Delete comment</span><p>Your comment:</p><textarea></textarea></div>');
$('#canvas').append($newbox);
$newbox.draggable();
}
}
function deleteNote() {
$(this).parent('#newbox').remove();
}
// wait until the dom document is loaded
jQuery(document).ready(function () {
// listen for a .click() event on the canvas element
$('#canvas').click(function (e) {
makeNote(e);
});
// Remove the note
$("#close").click(function () {
deleteNote();
});
});
html, body {
background-color: #cccccc;
margin: 0;
padding: 0;
height: 100%;
position: relative;
}
#newbox {
position: absolute;
background-color: white;
height: 200px;
width: 200px;
box-shadow: 10px 10px 10px #888;
padding: 20px;
z-index: 1000;
}
textarea {
background: transparent;
width: 200px;
height: 180px;
border: 0;
}
#canvas {
height:auto !important;
min-height: 100%;
height:100%;
z-index: -1000;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" scr="http://code.jquery.com/jquery-1.11.0.min.js"></script>
<script type="text/javascript" src="JavaScript.js"></script>
<link rel="stylesheet" ahref="StyleSheet1.css" />
</head>
<body>
<div id="canvas">
</div>
</body>
</html>
draggable is a part of jquery-ui library. Not jquery.
Add <script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script> to your code.
function makeNote(e) {
// Check the event object if the .click is on the canvas
// or a created note
if (e.eventPhase === 2) {
// Create the new comment at the corsor postition
var $newbox = $('<div class="ui-widget-content" id="newbox" style="top:' + e.pageY + 'px; left: ' + e.pageX + 'px;"><span id="close">Delete comment</span><p>Your comment:</p><textarea></textarea></div>');
$('#canvas').append($newbox);
$newbox.draggable();
}
}
function deleteNote() {
$(this).parent('#newbox').remove();
}
// wait until the dom document is loaded
jQuery(document).ready(function () {
// listen for a .click() event on the canvas element
$('#canvas').click(function (e) {
makeNote(e);
});
// Remove the note
$("#close").click(function () {
deleteNote();
});
});
html, body {
background-color: #cccccc;
margin: 0;
padding: 0;
height: 100%;
position: relative;
}
#newbox {
position: absolute;
background-color: white;
height: 200px;
width: 200px;
box-shadow: 10px 10px 10px #888;
padding: 20px;
z-index: 1000;
}
textarea {
background: transparent;
width: 200px;
height: 180px;
border: 0;
}
#canvas {
height:auto !important;
min-height: 100%;
height:100%;
z-index: -1000;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="JavaScript.js"></script>
<link rel="stylesheet" ahref="StyleSheet1.css" />
</head>
<body>
<div id="canvas">
</div>
</body>
</html>
Since you use jQuery, you can use .draggable() from jQuery UI along with contenteditable="true":
function addNew() {
var field = $('<div contenteditable="true">Text</div>')
field.appendTo('#fields').draggable();
}
#fields div {
border: 1px dashed #ddd;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/themes/smoothness/jquery-ui.css">
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>
<button onClick="addNew()">Add new field</button>
<hr/>
<div id="fields"></div>
There is something I want to notice.
never use same id to elements.
use jquery .on function for element that make by scripts.
never use box-shadow :D
function makeNote(e) {
// Check the event object if the .click is on the canvas
// or a created note
if (e.eventPhase === 2) {
// Create the new comment at the corsor postition
var $newbox = $('<div class="ui-widget-content" id="newbox'+e.pageX+e.pageY+'"><span class="close">Delete comment</span><p>Your comment:</p><textarea></textarea></div>');
$('#canvas').append($newbox);
$($newbox).css({
'top' : ($('#canvas').height() / 2 - 150 + sequentCounter++) + 'px' ,
'left' : ($('#canvas').width() / 2 - 100 + rowSeqCounter + sequentCounter++) + 'px'
});
$newbox.draggable({cancel : '.close'});
}
}
var sequentCounter = 1;
var rowSeqCounter = 1;
// wait until the dom document is loaded
jQuery(document).ready(function () {
// listen for a .click() event on the canvas element
$('#div_element_maker').click(function (e) {
if (sequentCounter > 70){
sequentCounter = 1;
rowSeqCounter += 11;
if (rowSeqCounter > 50)
rowSeqCounter = 1;
}
makeNote(e);
});
// Remove the note
$('#canvas').on('click',".close", function () {
$(this).parent().remove()
});
});
html, body {
background-color: #cccccc;
margin: 0;
padding: 0;
height: 100%;
position: relative;
}
.ui-widget-content {
position: absolute;
background-color: white;
height: 180px;
width: 185px;
border: 1px solid darkgray;
/*box-shadow: 10px 10px 10px #888;*/
padding: 20px;
z-index: 1000;
}
textarea {
background: transparent;
width: 180px;
height: 100px;
border: 1px solid darkgray;
}
#canvas {
height:auto !important;
min-height: 100%;
height:100%;
z-index: -1000;
}
.close{
cursor: pointer;
background: red;
}
#div_element_maker{
cursor: pointer;
background: green;
padding: 10px;
margin: 10px;
color: white;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><script src="http://code.jquery.com/ui/1.12.1/jquery-ui.min.js"></script>
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" scr="http://code.jquery.com/jquery-1.11.0.min.js"></script>
<script type="text/javascript" src="JavaScript.js"></script>
<link rel="stylesheet" ahref="StyleSheet1.css" />
</head>
<body>
<div id="canvas">
<span id="div_element_maker">make element</span>
</div>
</body>
</html>
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");