Creating icon on Click is too slow - javascript

I want to create cross on the position of the cursor on click and then fade out
but It's working only when I wait for a moment after I click and I don't know why
here`s the code
body = document.querySelector('body');
function Crossing(e) {
this.newCross = document.createElement('i');
this.newCross.className = 'fas fa-times';
this.newCross.style.position = 'absolute';
this.newCross.style.left = e.clientX - 10 + 'px';
this.newCross.style.top = e.clientY - 14 + 'px';
this.newCross.style.fontSize = '30px';
this.newCross.style.opacity = '100%';
this.newCross.style.transition = 'all 1s ease-out';
body.appendChild(this.newCross);
this.timeout1 = setTimeout(() => this.newCross.style.opacity = '0%', 1);
this.timeout2 = setTimeout(() => this.newCross.remove(), 1000);
}
window.addEventListener('click', () => {
new Crossing(e);
});
This is just part of the actual code but only this part has something to do with creating icon

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);
}
});
};

I would like to show HTML element by event

I'm trying to make a tooltip by clicking a shape.
I've done with adding event listener to canvas shape.
However, I could not add tooltip such as HTML element.
I tried to implement tooltip by using css display:none, block
var toolTip = document.createElement('div');
toolTip.style.width = "50px";
toolTip.style.height = "auto";
toolTip.style.padding = "5px";
toolTip.style.border = "1px solid rgb(177, 177, 177)";
toolTip.style.position = "absolute";
toolTip.style.display = "none";
toolTip.style.display = "background: rgba(111,231,43,0.5)";
toolTip.style.zIndex = "10";
canvas.addEventListener("click", e => {
let rect = canvas.getBoundingClientRect();
this.mousePos = {
x: e.clientX - rect.left,
y: e.clientY - rect.top
};
console.log(this.mousePos.x, this.mousePos.y);
if(0 <= this.mousePos.x <300 && 100 <= this.mousePos.y <110) {
console.log("mouseClicked");
toolTip.style.display = "block";
toolTip.style.left = this.mousePos.x + this.mousePos.x * 0.02;
toolTip.style.top = this.mousePos.y + this.mousePos.y * 0.02;
toolTip.innerHTML = "<p> hello </p>";
}
});
https://codepen.io/chikichaka/pen/NWRjWyG
You create a div element to act as a tooltip but you never append the tooltip to a container.
You must append the div to a container, such as the body
document.body.appendChild(toolTip);

How to fix href link on Ajax loaded content with vanilla JavaScript (no jQuery)

So basically, I'm loading and inserting html to a div element on my homepage. It all works well except that I've realised my regular href link just won't work. When I hover the URL appears on the bottom of Chrome as usual, but when I click, nothing happens.
For what I've seen, it seems like click events might not work properly on dynamically added elements?
The issue is, I've only seen jQuery solutions for this, and, frankly, I'm not even sure if this is the issue at all.
Any ideas?
PS: http://jsfiddle.net/8hz1Lubr/
// -------------------------- get the elements ----------------------- //
const deskbar = document.querySelector('#deskbar');
const screen = document.querySelector('#desktop');
const menuLink = document.querySelector('#primaryNav');
const tabsList = document.querySelector('#tabsList');
const clock = document.getElementById('theTime');
const desktop = document.querySelector('#contentarea');
// -------------------------- create events -------------------------- //
screen.addEventListener('click', toggleMenu);
tabsList.addEventListener('click', activateTab);
menuLink.addEventListener('click', openWindow);
menuLink.addEventListener('click', generateTab);
// -------------------------- open windows --------------------------- //
function openWindow(e) {
let windows = document.querySelectorAll('.window');
let openWindows = [];
windows.forEach(function(theWindow){
openWindows.push(theWindow.getAttribute('data-window'));
});
if(e.target.classList.contains('menuLink') && !openWindows.includes(e.target.getAttribute('data-link'))) {
let newWindow =`<div class="window" id="${e.target.getAttribute('data-link')}" data-window="${e.target.getAttribute('data-link')}">
<header class="header"></header>
<span class="close"></span>
<div class="headerContent">
${e.target.innerText}
<span class="minimize"></span>
</div>
<article>
<div class="content"></div>
</article>
</div>`;
desktop.insertAdjacentHTML('afterbegin', newWindow);
fetchPage(e.target.href, e.target.getAttribute('data-link'));
}
windows = document.querySelectorAll('.window');
// create add event listener for each new window
windows.forEach(function(theWindow){
theWindow.addEventListener('click', closeWindow);
theWindow.addEventListener('click', closeTab);
if(window.matchMedia("(min-width: 960px)").matches) {
theWindow.getElementsByClassName('headerContent')[0].onmousedown = function(event) {
let shiftX = event.clientX - theWindow.getBoundingClientRect().left;
let shiftY = event.clientY - theWindow.getBoundingClientRect().top;
deactivateAllWindows();
theWindow.classList.add('activeWindow');
theWindow.style.position = 'absolute';
theWindow.style.zIndex = 15;
desktop.append(theWindow);
moveAt(event.pageX, event.pageY);
// centers the ball at (pageX, pageY) coordinates
function moveAt(pageX, pageY) {
theWindow.style.left = pageX - shiftX + 'px';
theWindow.style.top = pageY - shiftY + 'px';
}
function onMouseMove(event) {
moveAt(event.pageX, event.pageY);
}
// move the window on mousemove
document.addEventListener('mousemove', onMouseMove);
// drop the window, remove unneeded handlers
theWindow.onmouseup = function() {
document.removeEventListener('mousemove', onMouseMove);
theWindow.onmouseup = null;
};
};
theWindow.ondragstart = function() {
return false;
};
}
});
e.preventDefault();
}
// -------------------------- fetch html content --------------------- //
function fetchPage(url, attribute) {
let windows = document.querySelectorAll('.window');
fetch(url)
.then(function(response) {
return response.text();
})
.then(function(body) {
windows.forEach(function(theWindow) {
theWindow.style.zIndex = 14;
theWindow.classList.remove('activeWindow');
});
windows.forEach(function(theWindow) {
if(theWindow.getAttribute('data-window') == attribute) {
if(window.matchMedia("(min-width: 960px)").matches) {
let randomHeight = Math.floor(Math.random() * (40 - 20 + 1)) + 20;
let randomWidth = Math.floor(Math.random() * (40 - 20 + 1)) + 20;
theWindow.style.zIndex = 15;
theWindow.style.top = randomHeight + '%';
theWindow.style.left = randomWidth + '%';
setTimeout(function(){
theWindow.style.opacity = 1;
}, 125);
}
theWindow.classList.add('activeWindow');
let content = theWindow.querySelector('.content');
content.innerHTML = body;
}
});
});
}

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

issue when trying to put a <span> inside a div with JavaScript

I tried to follow the answers in the similar questions but i still get the same result , what I'm trying to do is putting a span witch is an Oval inside a div , i have implemented this simple
createPong = function () {
var blockSize = 50,
element = document.createElement('span'),
pong;
element.style.position = 'absolute';
element.style.display = 'block';
element.style.width = blockSize + 'px';
element.style.height = blockSize + 'px';
element.style.background = getRandomColor();
element.style.borderRadius = blockSize + 'px';
pong = {
id: pongId = 1,
element: element,
size: blockSize,
dirX: Math.random() > 0.5 ? 1 : -1,
dirY: Math.random() > 0.5 ? 1 : -1,
speed: 5,
collided: false
};
placePong(pong);
return pong;
},
run = function (numberOfPongs) {
var i = 0,
containerElement = document.getElementsByClassName('mainDiv')[0], // <---- pong;
pong = createPong();
document.containerElement.appendChild(pong.element); // <----
pongs.push(pong);
gameId = requestAnimationFrame(loop);
},
but now i have the span (Oval) displayed at the top left corner of the browser and not in the mainDiv , before i implement this simple the Oval was in movement but now still in the same position
LIVE DEMO
This
document.containerElement.appendChild(pong.element);
Appends it to nothing. It needs to go in containerElement.
containerElement.appendChild(pong.element);
Also, your fiddle was appending it to the body.
http://jsfiddle.net/fyL9yu36/1/

Categories