I’m doing my portfolio page and there I made a div (here defined as ‘work’), added a click event listener, so when the user clicks it creates three bubbles that float up. It works as expected in Chrome and Edge, but Firefox says that ‘event’ is not defined and throws a ReferenceError. As far as I know from YDKJS book, inner functions have access to all variables from outer functions - so I’m puzzled.
I tried moving the createBubble()
function to global scope, and calling it inside of callback function directly, it won’t budge…
Why?
Short version:
work.addEventListener('click', function(event){
bubblesOnClick();
});
function bubblesOnClick() {
createBubble();
createBubble();
createBubble();
function createBubble() {
var div = document.createElement('div');
// get the coordinates of click where new bubble element will be created
var x = event.clientX; // these event objects aren't recognized in firefox
var y = event.clientY;
// ... create some nice bubbles on these coords ....
}
Long version:
work.addEventListener('click', function(event){
console.log('work-clicked');
work.classList.toggle('bubble--paused');
bubblesOnClick();
});
function bubblesOnClick() {
createBubble();
createBubble();
createBubble();
function createBubble() {
var div = document.createElement('div');
// get the coordinates of click where new bubble element will be created
var x = event.clientX; // these event objects aren't recognized in firefox
var y = event.clientY;
// give dimensions to the element
var height = randomSize(); // bubble's size should be different
div.style.height = height + 'px'; console.log('Height: ' + div.style.height);
div.style.width = height + 'px'; // so the bubble is perfect circle
// centering the bubble's position around pointer
div.style.position = 'absolute';
div.style.left = x - height + randomNum() + 'px';
div.style.top = y - height + randomNum() + 'px';
document.body.appendChild(div);
if (div.clientHeight < 16) {
div.setAttribute('class', 'bubble-small bubble-small--fast');
// deletes the buuble only when the animation is about to end
setTimeout(function(){
div.parentNode.removeChild(div);
}, 1950);
}
else if (div.clientHeight < 31) {
div.setAttribute('class', 'bubble-small bubble-small--intermediate');
setTimeout(function(){
div.parentNode.removeChild(div);
}, 2450);
}
else {
div.setAttribute('class', 'bubble-small bubble-small--slow')
setTimeout(function(){
div.parentNode.removeChild(div);
}, 2950);
}
}
function randomSize() {
// this function is used to give variability to bubble's sizes
var randomNumber = (Math.floor(Math.random() * 10) + 1) * 5;
console.log('Random number:' + randomNumber);
return randomNumber;
}
function randomNum() {
// this function is used to give randomness to bubble's position
return Math.floor(Math.random() * 100);
}
}