Remove div's with almost the same id once a certain top value is reached - javascript

So I've got this code to create a rectangular div every 800ms which falls down the screen.
Now I'd like to be able to remove a div once it reaches a certain top value, otherwise it'll
get too cluttered with div's. Now I have no idea how to exactly do that, considering the id's I've given them. I'd also like to know how I could end up removing every single one of those div's once it's game over. This is what I have so far all together: http://student.howest.be/pieter-jan.vandenb1/crossdodger/Game.html. I'm pretty new at javascript so thanks in advance!
var idNumber = 0;
SpawnBlock();
function SpawnBlock()
{
UpdateBlock();
setTimeout(SpawnBlock, 800);
}
function UpdateBlock()
{
var block = document.createElement("div");
block.style.width = "25px";
block.style.height = "25px";
block.style.background = "lightgrey"
block.style.top = "-25px";
block.style.left = Math.random() * 455 + "px";
block.style.position = "absolute";
block.id = "block" + ++idNumber;
//block.speed = 0.5;
sym.$("Stage").append(block);
sym.$("#block"+idNumber).transition({top:"800px"},8000,"linear");
}
It's made in Adobe Edge, hence the "sym." namespace.

This worked for me in a similar environment:
var bl = document.getElementById("block" + (idNumber));
bl.parentNode.removeChild(bl);

var idNumber = 0;
SpawnBlock();
var divblocks = [];
function SpawnBlock()
{
UpdateBlock();
setTimeout(SpawnBlock, 800);
}
function UpdateBlock()
{
var block = document.createElement("div");
block.style.width = "25px";
block.style.height = "25px";
block.style.background = "lightgrey"
block.style.top = "-25px";
block.style.left = Math.random() * 455 + "px";
block.style.position = "absolute";
block.id = "block" + ++idNumber;
//block.speed = 0.5;
sym.$("Stage").append(block);
sym.$("#block"+idNumber).transition({top:"800px"},8000,"linear");
divblocks.push(block.id);
if (divblocks.length > 800)
{
$(divblocks[0]).Remove();
}
}

Related

Prevent double images in function using Math.random

I have a function that adds random images to my divs that disappear over time and create a mouse trail. My issue is: there are double images.
I'd like to add something that checks if the background url is already located on the page and if that's the case, skips to the next in the array and check it again until until it comes across one that is not there. So like a loop that refreshes every time a 'trail' is being created.
Maybe I am asking for something that won't work? What if all the images are already on the page? I don't really have an answer for it and I also don't have an idea how to solve that problem yet.
For now I tried adding a counter that checks the usedImages and counts them, but it seems to have flaws and I am unsure where to look or how to fix it. Does anyone have any tips on how to do this? Is it even possible?
My fiddle
var bgImages = new Array(
"https://www.studiourbanestrategien.com/wordpress/wp-content/uploads/2019/05/schraegluftbild-1024x725.jpg",
"https://www.studiourbanestrategien.com/wordpress/wp-content/uploads/2019/05/pikto-608x1024.jpg",
"https://www.studiourbanestrategien.com/wordpress/wp-content/uploads/2019/05/Jettenhausen-EG-Grundriss-913x1024.jpg",
"https://www.studiourbanestrategien.com/wordpress/wp-content/uploads/2019/05/lageplan-945x1024.jpg",
"https://www.studiourbanestrategien.com/wordpress/wp-content/uploads/2019/05/Jettenhausen-EG-Grundriss-913x1024.jpg",
"https://www.studiourbanestrategien.com/wordpress/wp-content/uploads/2019/05/Jettenhauser-Esch-Modell-2-1024x768.jpg",
"https://www.studiourbanestrategien.com/wordpress/wp-content/uploads/2019/07/DSCN3481-1024x768.jpg",
"https://www.studiourbanestrategien.com/wordpress/wp-content/uploads/2019/07/zoom-in-3_ASTOC-1024x683.jpg",
"https://www.studiourbanestrategien.com/wordpress/wp-content/uploads/2016/07/IMG_1345-1024x768.jpg"
);
const numberOfImages = 10;
const timesPerSecond = .1;
var usedImages = {};
var usedImagesCount = 0;
function preloadImages(images) {
for (i = 0; i < images.length; i++) {
let l = document.createElement('link')
l.rel = 'preload'
l.as = 'image'
l.href = images[i]
document.head.appendChild(l);
}
}
function animate(e) {
var image = document.createElement('div');
image.classList.add('trail');
var sizew = 200;
var sizeh = 200;
image.style.transition = '3s ease';
image.style.position = 'fixed';
image.style.top = e.pageY - sizeh / 2 + 'px';
image.style.left = e.pageX - sizew / 2 + 'px';
image.style.width = sizew + 'px';
image.style.height = sizeh + 'px';
var random = Math.floor(Math.random() * (bgImages.length));
if (!usedImages[random]) {
image.style.backgroundImage = "url(" + bgImages[random] + ")";
usedImages[random] = true;
usedImagesCount++;
if (usedImagesCount === bgImages.length) {
usedImagesCount = 0;
usedImages = {};
}
} else {
animate(e);
}
console.log(usedImages);
console.log(usedImagesCount);
image.style.backgroundSize = 'cover';
image.style.pointerEvents = 'none';
image.style.zIndex = 1;
document.body.appendChild(image);
//opacity and blur animations
window.setTimeout(function() {
image.style.opacity = 0;
image.style.filter = 'blur(20px)';
}, 40);
window.setTimeout(function() {
document.body.removeChild(image);
}, 2100);
};
window.onload = function() {
preloadImages(bgImages);
var wait = false;
window.addEventListener('mousemove', function(e) {
if (!wait) {
wait = true;
setTimeout(() => {
wait = false
}, timesPerSecond * 800);
animate(e);
}
});
};

Make a multiple objects with javascript and png

I'm trying to get a spaceship animation scene with a group of comets going down.
//Create a comet div with img attached to it
var cometScene = function(spaceNo){
var b = document.createElement('div');
b.id = 'cometio';
var cometImage = document.createElement('img');
cometImage.setAttribute('src', 'images/comet1.png');
b.appendChild(cometImage);
document.getElementById('wrap').appendChild(b);
}
//Comet move
function cometMove(){
var comet = document.getElementById('cometio');
var pos = 0;
var interval = setInterval(scene, 3);
function scene(){
if (pos === 1000){
clearInterval(interval);
} else {
pos++;
comet.style.top = pos + 'px';
comet.style.left = pos + 'px';
}
}
setInterval(scene, 3)
}
But when I call a function cometScene(3) I'm not getting 3 similar objects. Also how these objects can be allocated across the whole screen as this is just a single div.
function main(){
var w = document.createElement('div');
w.id = 'wrap';
document.querySelector('body').appendChild(w);
astronautScene();
cometScene();
shaceshipScene();
cometMove();
astronautMove();
}
This it what I would do:
Give the comets a class instead of an id, because there can be more of them.
Because there can be multiple use a loop to iterate through them
To give them the ability to move freely, they need to have position:absolute or something similiar
Don't use the same variable for the position of all comets, because they could be in different positions
To get the current position just parse the currect top and left value to a Number
//Create a comet div with img attached to it
var cometScene = function(spaceNo) {
var b = document.createElement('div');
b.className = 'cometio';
var cometImage = document.createElement('img');
cometImage.setAttribute('src', 'images/comet1.png');
b.appendChild(cometImage);
document.getElementById('wrap').appendChild(b);
}
//Comet move
function cometMove() {
var comets = document.getElementsByClassName('cometio');
for (let i = 0; i < comets.length; i++) {
const comet = comets[i];
comet.style.top = "0px";
comet.style.left = "0px";
comet.style.position = "absolute";
var interval = setInterval(scene, 3);
function scene() {
let x = parseInt(comet.style.left);
let y = parseInt(comet.style.top);
if (x === 1000) {
clearInterval(interval);
} else {
comet.style.top = (1 + x) + 'px';
comet.style.left = (1 + y) + 'px';
}
}
}
//setInterval(scene, 3)don't start the interval twice
}
function main() {
var w = document.createElement('div');
w.id = 'wrap';
document.querySelector('body').appendChild(w);
//astronautScene();
cometScene();
//shaceshipScene();
cometMove();
//astronautMove();
}
main();

Space shooter - shoot function

I have some problem with this code to work. I want to create the effect of shooter game but when I create a div I have to wait until it finishes its animation before create another one, how could I made it? Please help.
function createShot (){
div[i] = document.createElement("div");
screen.appendChild(div[i]);
div[i].style.height = 5 + "px";
div[i].style.position = "absolute";
div[i].style.border = 2 + "px solid #F30";
div[i].style.width = 5 + "px";
div[i].style.left = x+3 + "px";
div[i].style.top = divy + "px";
t = setInterval (shot,1);
}
function shot (){
if (divy <= 0){
screen.removeChild(div[i]);
divy = 260;
clearInterval (t);
} else {
divy -= 5;
div[i].style.top = divy + "px";
}
}
tshoot = setInterval(createShot,1000);
Looks like i is global and not incremented, so you cannot have more than one shoot instance at a time. Relying on globals is a bad practice, especially in an asynchronous environment. Here is a working example:
var shoot = function(div)
{
var x = parseInt(div.style.left);
x++;
if (x>1000) {
clearInterval(div.t);
document.body.removeChild(div);
return;
}
div.style.left = x+'px';
}
var createShot = function(){
var div = document.createElement('div');div.style.height = 5 + "px";
div.style.position = "fixed";
div.style.border = "5px solid red";
div.style.width = "5px";
div.style.left = "0px";
div.style.top = "100px";
document.body.appendChild(div);
div.t = setInterval(shoot, 10, div);
}
setInterval(createShot, 200)

HTML javascript function to create element, but cannot find it with other function

I am trying to program a scrambling puzzle in Javscript/HTML, in which I draw blue and red squares on an HTML file page. When the blue squares are clicked on, they move depending on their location with respect to the red square. I wrote a method that draws the squares and names them "blue1, blue2, blue3, red" etc. However, when I try to find the square named "red" with getElementById("red") and call getBoundingClientRect() on it, I get an error for
trying to call getBoundingClientRect() on a null object.
I'm not sure why it would be null since I can see the square named "red" when I run my code.
Here is the code that draws the squares:
var board = [["blue3", "blue2"],["blue1", "red"]];
var dim = 2;
var width = 50;
var height = 50;
// add the squares
function addSquares()
{
for(var i = 0; i < dim; i++)
{
for(var j = 0; j < dim; j++)
{
// create square
var label = j + i * dim;
var name = board[i][j];
var div = document.createElement(name);
div.style.width = width + "px";
div.style.height = height + "px";
div.style.left = width * j + "px";
div.style.top = height * i + "px";
div.style.position = "absolute";
// determine color of square
if(i != dim - 1 || j != dim - 1)
{
div.style.backgroundColor = "blue";
}
else
{
div.style.backgroundColor = "red";
}
document.getElementById("container").appendChild(div);
// do something when clicked
div.addEventListener("click", function(){getMove(this);});
}
}
}
And here is the code for getMove(), where there is an error once I call var red = redelem.getBoundingClientRect();
function getMove(elem) {
var move = elem.getBoundingClientRect();
var redelem = document.getElementById('red');
var red = redelem.getBoundingClientRect();
mwcenter = 0.5 * (move.right + move.left);
mhcenter = 0.5 * (move.bottom + move.top);
rwcenter = 0.5 * (red.right + red.left);
rhcenter = 0.5 * (red.bottom + red.top);
if (mwcenter - rwcenter == 50 && mhcenter == rhcenter)
{
leftPress(elem);
rightPress(redelem);
}
else if (mwcenter - rwcenter == -50 && mhcenter == rhcenter)
{
rightPress(elem);
leftPress(redelem);
}
else if (mhcenter - rhcenter == 50 && mwcenter == rwcenter)
{
upPress(elem);
downPress(redelem);
}
else if (mhcenter - rhcenter == -50 && mwcenter == rwcenter)
{
downPress(elem);
upPress(redelem);
}
}
"name" is not the same as "id". getElementById does not find the div by looking for it's name, it gets it by id, so it will not find the element whose name is "red", without an id. You have two options:
Either:
Use getElementByName() instead of getElementById(), using the following line instead of the one that causes the error:
var redelem = document.getElementByName('red');
Or:
Give each of the divs an id:
You created the element and gave it a name, so you will also need to give it an id like this:
div.id = "red";
Actually, in your code it should be
div.id = name;
but I wanted my first example to be less confusing by showing you what you literally wanted for the red div. So, you can give your divs an id each and then you will be able to use getElementById successfuly.

Turning off opacity on centered div

I am writing a box that appears in the center of a website. To do that I dynamically (js) create two elements - overlay that covers whole page and has 0.5 opacity to show some website, and a box that should have no opacity.
The problem is that both the overlay and the box are a bit transparent.
this.createOverlay = function () {
handler = document.createElement('div');
handler.style.display = 'hidden';
handler.style.width = '100%';
handler.style.height = '100%';
handler.style.top = 0;
handler.style.left = 0;
handler.style.position = 'absolute';
handler.style.background = 'black';
handler.style.color = "#aaaaaa";
handler.style.opacity = "0.5";
handler.style.filter = "alpha(opacity = 5)";
return this;
};
this.createCenteredBox = function (width, height, url) {
var data = JSON.parse(data);
handler = document.createElement('a');
handler.href = data.product_feed_deep_link;
handler.target = "_blank";
handler.style.display = "block";
handler.style.width = width + "px";
handler.style.height = height + "px";
handler.style.position = "absolute";
handler.style.color = "black";
handler.style.backgroundColor = "#ffffff";
handler.style.opacity = "1";
handler.style.top = "50%";
handler.style.left = "50%";
handler.style.marginTop = "-" + height / 2 + "px";
handler.style.marginLeft = "-" + width / 2 + "px";
handler.style.padding = "0 10px 10px 10px";
handler.style.borderRadius = "4px";
var div = document.createElement('div');
handler.appendChild(div);
return this;
};
This is the code, I can't turn off box'es opacity no matter if I set opacity to 1 on it, or opacity filter, or whatever.
How can I solve this?
Opacity isn't inherited (see here), however, all elements that reside inside (descendants) of that elements that the opacity property is applied to will be effected.
The best way to get around this is to use rgba.
handler.style.background = "rgba(0, 0, 0, .5)"; // RGB 0,0,0 is #000 (black).
//handler.style.opacity = "0.5";
//handler.style.filter = "alpha(opacity = 5)";
See 2nd and 3rd answer here as well

Categories