i want to call a function many time inside my code? - javascript

I plan to make this box move every time I click a button
but the problem is that it works first time when I click s or d but does not work after that.
So can any one help me to find the solution to my problem?
<!DOCTYPE html>
<html>
<head>
<style>
.box {
position: absolute;
left: 10px;
top: 20px;
width: 20px;
height: 20px;
background-color: black;
border: 1px solid black;
border-radius: 5px;
}
</style>
</head>
<body id="bd">
<div class="box"></div>
<script >
document.getElementById('bd').addEventListener('keypress', show);
function show(e){
let x = e.which;
if(x == 122){
// 122 = z
document.getElementsByClassName('box')[0].style.top -='50px' ;
}
else if(x == 133){
// 122 = q
document.getElementsByClassName('box')[0].style.left -='50px' ;
}
else if(x == 115){
// 122 = s
document.getElementsByClassName('box')[0].style.top +='50px' ;
}
else if(x == 100){
// // 122 = d
document.getElementsByClassName('box')[0].style.left +='50px' ;
}
}
</script>
</body>
</html>

You are trying to perform operation on string. First need to convert in number.
Sample:
<!DOCTYPE html>
<html>
<head>
<style>
.box {
position: absolute;
left: 10px;
top: 20px;
width: 20px;
height: 20px;
background-color: black;
border: 1px solid black;
border-radius: 5px;
}
</style>
</head>
<body id="bd">
<div class="box"></div>
<script>
const number = (num) => Number(num.split('px')[0])
const addBy50 = (num) => `${number(num) + 50}px`
const subtractBy50 = (num) => `${number(num) - 50}px`
const style = document.getElementsByClassName("box")[0].style
document.addEventListener("keypress", (e) => {
let x = e.which;
const {
top,
left
} = style
switch (e.which) {
case 122:
style.top = subtractBy50(top);
break;
case 113:
style.left = subtractBy50(left);
break
case 115:
style.top = addBy50(top);
break
case 100:
style.left = addBy50(left);
break
}
});
</script>
</body>
</html>

element.style.top and element.style.left are strings, so your statements are essentially saying
element.style.top = "20px" + "50px";
Instead, consider a separate variable storing position:
let positionLeft = 20;
...
if(x == 115){
positionLeft += 50;
document.getElementsByClassName('box')[0].style.top = positionLeft + 'px';
}

Related

how can I let 3 div elements being resizable

what I want to see the result is 2 set of split view screen (or more), one is vertical, one is horizontal, but in the same javascript file. If it's possible to do in a single JavaScript file will be good
I tried to use this one to make it but it seems like not how to make that.
Here's the code I'm trying to make two div elements and its vertical
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>my app</title>
<style>
.container {
width: 202px;
height: 406px;
border: 1px solid black;
display: flex;
flex-direction: column;
}
.top {
width: 200px;
height: 200px;
border: 1px solid red;
min-height: 100px;
}
.resizer {
width: 202px;
height: 2px;
background-color: green;
}
.resizer:hover {
cursor: ns-resize;
}
.bottom {
width: 200px;
height: 200px;
border: 1px solid blue;
flex: 1 1 0%;
min-height: 100px;
}
</style>
</head>
<body>
<div class="container">
<div class="top" id="top">
something here
</div>
<div class="resizer" id="resizer"></div>
<div class="bottom" id="bottom">
something too
</div>
</div>
<script>
const resizer = document.getElementById('resizer');
const topSection = document.getElementById('top');
const bottomSection = document.getElementById('bottom');
let x = 0;
let y = 0;
let topSectionHeight = 0;
const mouseDownHandler = function (e) {
x = e.clientX;
y = e.clientY;
topSectionHeight = topSection.getBoundingClientRect().height;
document.addEventListener('mousemove', mouseMoveHandler);
document.addEventListener('mouseup', mouseUpHandler);
}
resizer.addEventListener('mousedown', mouseDownHandler);
const mouseMoveHandler = function (e) {
const dx = e.clientX - x;
const dy = e.clientY - y;
const newtopSectionHeight = ((topSectionHeight + dy) * 100) / resizer.parentNode.getBoundingClientRect().height;
topSection.style.height = `${newtopSectionHeight}%`;
resizer.style.cursor = 'ns-resize';
document.body.style.cursor = 'ns-resize';
topSection.style.userSelect = 'none';
topSection.style.pointerEvents = 'none';
bottomSection.style.userSelect = 'none';
bottomSection.style.pointerEvents = 'none';
}
const mouseUpHandler = function () {
resizer.style.removeProperty('cursor');
document.body.style.removeProperty('cursor');
actionBasic.style.removeProperty('user-select');
actionBasic.style.removeProperty('pointer-events');
bottomSection.style.removeProperty('user-select');
bottomSection.style.removeProperty('pointer-events');
document.removeEventListener('mousemove', mouseMoveHandler);
document.removeEventListener('mouseup', mouseUpHandler);
}
</script>
</body>
</html>
thank you for reading so far, please help me if you're able to! If any information is needed, please tell me below and I'll provide it as soon as possible.

How can I detect when an element is at a certain part of the screen JavaScript

Do you remember that console video game "Guitar Hero"? Or if you are a little younger, "Piano Tiles"?
If you don't know what I'm talking about, click on this link to get an idea = https://www.youtube.com/watch?v=nWLKlEg0VMs&ab_channel=MattSterner
Well, that is exactly what I am doing with this website (on a more basic level of course).
THERE IS NO NEED TO READ THE WHOLE CODE...
What I need your help with:
Look into the JavaScript code and go to the animateFunction() function.
In the if statement you will see I wrote a condition that in human language would be "If I press 'Q key' and the square on the left is where it should be when you get the note right, then console.log(currentNotePosition.bottom);" and that if statement is the same for the notes on the middle line and on the right side.
The issue:
When I click on the keys ('Q', 'W', and 'E'), the console.log(currentNotePosition.bottom) does execute, but it does it sometimes and not when the note is on the spot it should be when I want it to console.log the bottom position. So basically, my code can't detect when a note is at the place where you can score a point.
My theory of the issue:
My code is not able to identify which div/musical_note exactly I want to "score on".
Here is a better place to see and play with my code (tap on the "create" button to start the "game"): https://codepen.io/xavi-font/pen/xxOedzK
(If on the Codepen playground you don't see the "web browser screen" then just pull it up from the bottom, it is a window just like the ones that "contain" the code).
PD: This is written in Vanilla JavaScrpt (No libraries or frameworks).
let speed = 1;
idArray = [];
let topPositionThatAdds = 0;
let squareLeft = {
color: "red",
positionLeft: "250px",
class: 'squareLeft',
}
let squareMiddle = {
color: "green",
positionLeft: "750px",
class: 'squareMiddle',
}
let squareRight = {
color: "yellow",
positionLeft: "1250px",
class: 'squareRight',
}
idList = 0;
randomSquare = [squareLeft, squareMiddle, squareRight];
function generateSquares() {
let randomValue = randomSquare[Math.floor(randomSquare.length * Math.random())];
const newDiv = document.createElement("div");
newDiv.classList.add(randomValue.class);
newDiv.style.top = "-100px";
newDiv.setAttribute("id", idList.toString());
idList++;
idArray.push(idList);
document.body.appendChild(newDiv);
for (let i = 0; i < idArray.length; i++) {
let element = document.getElementById(i.toString());
animateFunction(element);
}
}
function animateFunction(element) {
if (element.style.top == "-100px") {
const interval = setInterval(function() {
element.style.top = eval(parseInt(element.style.top) + 1).toString() + "px";
let currentNotePosition = element.getBoundingClientRect();
document.body.onkeyup = function(e) {
if (e.keyCode == 81 /*Q*/ && currentNotePosition.bottom > 700 && currentNotePosition.bottom < 900 && element.classList.contains('squareLeft')) {
console.log(currentNotePosition.bottom);
}else if (e.keyCode == 87 /*W*/ && currentNotePosition.bottom > 700 && currentNotePosition.bottom < 900 && element.classList.contains('squareMiddle')) {
console.log(currentNotePosition.bottom);
}else if (e.keyCode == 69 /*E*/ && currentNotePosition.bottom > 700 && currentNotePosition.bottom < 900 && element.classList.contains('squareRight')) {
console.log(currentNotePosition.bottom);
}
}
}, speed);
}
}
function startGame() {
let randomGenerationNumber = Math.floor(Math.random() * (500 - 250)) + 250;
const interval = setInterval(generateSquares, randomGenerationNumber);
}
document.getElementById('button').addEventListener("click", startGame);
body{
background: yellow;
padding: 0;
margin: 0;
overflow: hidden;
background-size: cover;
}
#bar{
position: absolute;
bottom: 0;
/* top: 770px; */
height: 100px;
width: 100%;
background: rgb(52,162,162);
background: linear-gradient(90deg, rgba(52,162,162,.25) 0%, rgba(144,28,103,1) 100%);
z-index: 2;
}
.squareRight{
position: absolute;
height: 100px;
width: 100px;
z-index: 1;
left: 250px;
background-size: cover;
background-color: red;
}
.squareMiddle{
position: absolute;
height: 100px;
width: 100px;
z-index: 1;
left: 750px;
background-size: cover;
background-color: green;
}
.squareLeft{
position: absolute;
height: 100px;
width: 100px;
z-index: 1;
left: 1250px;
background-size: cover;
background-color: blue;
}
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>TapTap</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<button id="button">create</button>
<div id="bar"></div>
<script src="app.js"></script>
</body>
</html>
Thank you so much for your time, I hope you can help me with this since its been days and I still can't figure it out.

Move an element back and forth diagonally using Java Script

I'm trying to make my div element move back and forth inside a container infinitely.
The goal is to use Java Script only, no CSS animations, jQuery, etc.
const container = document.getElementById('container');
const box = document.getElementById('box');
let t = setInterval(move, 1);
let pos = 1;
function move() {
box.style.left = pos + 'px';
box.style.top = pos + 'px';
pos++;
if (pos === 150) {
clearInterval(t)
}
}
#container{
width: 200px;
height: 200px;
background-color: green;
position: relative;
}
#box{
width: 50px;
height: 50px;
background-color: red;
position: absolute;
animation-direction: alternate;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Animation</title>
<link href="animation.css" rel="stylesheet">
<script defer src="animation.js"></script>
</head>
<body>
<div id="container">
<div id="box"></div>
</div>
</body>
</html>
So here the code. As you see, I've used position relative/absolute to make the element move with setInterval function. But when I try to reverse it back to "it's corner", it just won't work. To be honest, I've tried some stuff already, but I really can't find the solution of doing it without using any other instruments.
Thanks in advance.
You need to increase/decrease the values considering a boolean variable like below:
const container = document.getElementById('container');
const box = document.getElementById('box');
let t = setInterval(move, 1);
let pos = 1;
let test = true;
function move() {
box.style.left = pos + 'px';
box.style.top = pos + 'px';
if (test)
pos++; /* move down */
else
pos--; /* move up */
/* update the direction when you reach the top or bottom limit*/
if (pos >= 150)
test = false
else if (pos <= 0)
test = true;
}
#container {
width: 200px;
height: 200px;
background-color: green;
position: relative;
}
#box {
width: 50px;
height: 50px;
background-color: red;
position: absolute;
}
<div id="container">
<div id="box"></div>
</div>
An alternative to get the same results
const box = document.getElementById('box');
let jump = 1;
let pos = 0;
window.setInterval(() => {
pos = pos + jump;
if (pos > 150 || pos < 0) {
jump = jump * (-1);
}
box.style.left = pos + 'px';
box.style.top = pos + 'px';
}, 1);
#container{
width: 200px;
height: 200px;
background-color: green;
position: relative;
}
#box{
width: 50px;
height: 50px;
background-color: red;
position: absolute;
animation-direction: alternate;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Animation</title>
<link href="animation.css" rel="stylesheet">
<script defer src="animation.js"></script>
</head>
<body>
<div id="container">
<div id="box"></div>
</div>
</body>
</html>

JavaScript itareate over divs and create a new one if doesn't fits

Hello guys I hope you can help me with JavaScript, I'm trying to itarate over some divs, the issue is that when I iterate sometimes a div never change to the other divs, it suppose to be infinite, I will recive thousands of different divs with different height and it should create an other div container in the case it does not fits but I can not achieve it work's, I'm using Vanilla JavaScript because I'm lerning JavaScript Regards.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<style>
.big_container{
height: 600px;
width: 150px;
background-color: #f1f1f1;
float: left;
}
.items{
background-color: gray;
height: 50px;
}
.new_container{
margin-bottom: 10px;
height: 300px;
width: 150px;
background-color: red;
float: left;
margin-left: 5px;
}
</style>
</head>
<body>
<div class="big_container">
<div class="items">1</div>
<div class="items">2</div>
<div class="items">3</div>
<div class="items">4</div>
<div class="items">5</div>
<div class="items">6</div>
<div class="items">7</div>
<div class="items">8</div>
<div class="items">9</div>
<div class="items">10</div>
<div class="items">11</div>
<div class="items">12</div>
<div class="items">13</div>
</div>
<div class="new_container">
</div>
</body>
<script>
number = 0
sum = 0
new_container = document.getElementsByClassName('new_container')[number].offsetHeight
divs = document.getElementsByClassName('items')
for ( var i = 0; i < divs.length; i++ ){
sum += this.document.getElementsByClassName( 'items' )[0].offsetHeight
if ( sum <= new_container ){
console.log(sum, "yes")
document.getElementsByClassName("new_container")[number].appendChild( this.document.getElementsByClassName( 'items' )[0] )
} else {
sum = 0
console.log(sum, "NO entra")
nuevo_contenedor = document.createElement('div'); // Creo un contenedor
nuevo_contenedor.className = "new_container";
nuevo_contenedor.setAttribute("style", "background-color: red;");
document.body.appendChild(nuevo_contenedor)
number += + 1
}
}
</script>
</html>
I really apreciate a hand.
I know that I'm late, but there is my approach how this can be done.
// generate items with different height
function generateItems(count) {
const arr = [];
for (let i = 0; i < count; i++) {
const div = document.createElement("DIV");
const height = Math.floor((Math.random() * 100) + 10);
div.setAttribute("style", `height: ${height}px`);
div.setAttribute("class", "items");
const t = document.createTextNode(i + 1);
div.appendChild(t);
arr.push(div);
}
return arr;
}
function createNewContainer(height) {
const new_container = document.createElement("DIV")
new_container.setAttribute("class", "new_container");
new_container.setAttribute("style", `height: ${height}px`)
document.body.appendChild(new_container);
return new_container;
}
function breakFrom(sourceContainerId, newContainerHeight) {
const srcContainer = document.getElementById(sourceContainerId);
const items = srcContainer.childNodes;
let new_container = createNewContainer(newContainerHeight);
let sumHeight = 0;
for (let i = 0; i < items.length; i++) {
let item = items[i];
if (item.offsetHeight > newContainerHeight) {
// stop!!! this item too big to fill into new container
throw new Error("Item too big.");
}
if (sumHeight + item.offsetHeight < newContainerHeight) {
// add item to new container
sumHeight += item.offsetHeight;
new_container.appendChild(item.cloneNode(true));
} else {
// create new container
new_container = createNewContainer(newContainerHeight);
new_container.appendChild(item.cloneNode(true));
// don't forget to set sumHeight)
sumHeight = item.offsetHeight;
}
}
// if you want to remove items from big_container
// for (let i = items.length - 1; i >= 0; i--) {
// srcContainer.removeChild(items[i]);
// }
}
// create big container with divs
const big_container = document.getElementById("big_container");
const items = generateItems(13);
items.forEach((div, index) => {
big_container.appendChild(div);
});
breakFrom("big_container", 300);
#big_container {
width: 150px;
background-color: #f1f1f1;
float: left;
}
.items {
background-color: gray;
border: 1px solid #000000;
text-align: center;
}
.new_container {
margin-bottom: 10px;
height: 300px;
width: 150px;
background-color: red;
border: 1px solid red;
float: left;
margin-left: 5px;
}
<div id="big_container"></div>
This example gives you the ability to play with divs of random height. Hope, this will help you.

Check if a div touches another div

I've made margin of 2 divs move (using variable and variable++ or -- with style attribute in js to change margin) Like that:
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<meta charset="utf-8" />
<title>Game</title>
<style>
body{
position: absolute;
background: #f00;
}
.point{
position: absolute;
width: 15px;
height: 15px;
background: #fff;
border-radius: 10px;
margin: 0px 0 0;
}
.player{
position: absolute;
text-align: center;
width: 200px;
height: 20px;
background: #0005ff;
margin: 550px 550px 0px;
}
</style>
<script>
var num = 550;
$(document).keydown(function (event) {
switch (event.keyCode) {
// Left Arrow
case 37: num = num-- - 15;
document.getElementById('player').style.margin = '550px ' + num + 'px 0px';
break;
// Right Arrow
case 39: num = 15 + num++;
document.getElementById('player').style.margin = '550px ' + num + 'px 0px';
break;
}
});
var nump = 0;
$(document).load(function () {
nump++;
document.getElementById('point').style.margin = nump + 'px 0px 0px';
});
</script>
</head>
<body>
<div class="point" id="point"></div>
<div class="player" id="player"></div>
</body>
</html>
Now I got problem about moving div named point.The div, point is not moving when I use $(document).load but the other div works. How can I fix that?
My second question is how can i check when div "point" touch div "player" then i'll return div point to the start and make a loop.
try this to move the point
var nump = 0;
var touch = false;
var flagtouch;
$(document).ready(function () {
flagtouch = setInterval(function(){
movePoint(nump);
},1000);
});
function movePoint()
{
document.getElementById('point').style.margin = nump + 'px 0px 0px';
touch = chekTouch(); // check whether the divs touches and return true if touched
if(touch)
{
clearInterval(flagtouch);
}
else
{
nump = nump+5;
}
}
For the second question:
With http://api.jquery.com/position/, you can known the position of both divs, and as you know too the width and height of the elements, you can calculate the region occupied by each element, and then when the elements touch each other.

Categories

Resources