Proper deleting HTML DOM nodes - javascript

I'm trying to create a star shining animation.
function ShowStars()
{
//if ($('img.star').length > 5)
// return;
var x = Math.floor(Math.random() * gameAreaWidth) - 70;
var y = Math.floor(Math.random() * gameAreaHeight);
var star = document.createElement("img");
star.setAttribute("class", "star");
star.setAttribute("src", imagesPath + "star" + GetRandom(1, 3) + ".png");
star.style.left = x + "px";
star.style.top = y + "px";
gameArea.appendChild(star);
// Light.
setTimeout(function () { star.setAttribute("class", "star shown"); }, 0);
// Put out.
setTimeout(function () { star.setAttribute("class", "star"); }, 2000);
// Delete.
setTimeout(function () { gameArea.removeChild(star); }, 4000);
setTimeout(function () { ShowStars(); }, 500);
}
It works fine until I uncomment the following code which is supposed to regulate star count:
//if ($('img.star').length > 5)
// return;
Then it stops to work as if the created stars are not removed (the first 5 stars blink then nothing happens). Why do the jQuery selector select them after gameArea.removeChild(star);? Isn't it enough to remove them from the parent node?
Browser: Google Chrome 17.
Regards,

Change the commented out lines to
if ($('img.star').length > 5) {
setTimeout(function () { ShowStars(); }, 500);
return;
}
to keep the ShowStars recursion going.

I see a workaround: do not create stars dynamically, but insert them in HTML (<img id="star1">...<img id="starN">, where N is total count) then light and put out the existing nodes. Nevertheless, I'd like to understand, what's wrong with removing nodes in the question above.

Related

Using animate.css (link in description) how do I trigger an animation when a particular event is finished

I have an an image moving across the screen and out of viewport, when the image reaches a particular absolute position (right: - 200), I want to trigger the below animation. I am relatively new to programming, not sure how to track when a particular function is done so that I can trigger the below animation.
var $startLessonButton = $('.startLessonButtonUp');
$startLessonButton.mouseup(function() {
$(this).addClass('animated slideInLeft');
});
---------
var movingOutAnimationCounter = 2;
var movingOutCurrentPosition = window.innerWidth / 2 - 200
function moveTrumpOut() {
movingOutCurrentPosition -= 2;
trumpyWrapper.style.right = movingOutCurrentPosition + 'px';
if (movingOutAnimationCounter < 9 ) {
trumpy.src = '../images/trump_walking_out_' + movingOutAnimationCounter + '.png';
movingOutAnimationCounter += 1;
} else {
movingOutAnimationCounter = 1;
trumpy.src = '../images/trump_walking_out_' + movingOutAnimationCounter + '.png';
}
if (movingOutCurrentPosition > -200 ) {
requestAnimationFrame(moveTrumpOut);
}
}
All the best!
If you know time, when moving element is hidden, you can use this function:
setTimeout(function(){ $('.elem').addClass("animCssClass") }, 1000);
Last parameter, in this example: 1000 is time in ms, when function inside should execute. Run this function on mouseup when you adding class to moving element.

adding image to different div upon change/removal of another div

I have a game which involves a dog chasing cats; upon the dog touching the cat div, the class changes so that a "dead" cat appears and is then removed. I would also like to have a smaller version of the dead cat image show up in a div in the upper right corner as a sort of score keeper.
So essentially every time a cat is killed a small image pops up in the score div.
The problem is if I have the prepend for the small image placed where it is now, it continues to add the image indefinitely as opposed to only one for each dead cat. I'm guessing it's because it's within this if statement for the collision detection but I can't figure out a way around it.
I've tried making it a function, moving it outside of the getCollision function, tried to attach a trigger...nothing I've done seems to work to solve what I assume to be a relatively simple problem.
If anyone can help or point me in the right direction I'd greatly appreciate it! Below is the code:
"use strict";
$(document).ready(function() {
console.log("linked");
var $dog = $('.dog'); //global variables
var body = $('body');
var $cat = $('.cat');
function newCat() { //creates a div w/ class cat, appends to body
var cat = $('<div class="cat"></div>');
body.append(cat);
setInterval(function() { //moves cats randomly
cat.css("top", Math.random() * window.innerHeight);
cat.css("left", Math.random() * window.innerWidth);
}, 1500)
}
for(var i=0; i<10; i++) { //create multiple cats
newCat();
}
function getCollision(cat) { //collision detection for elements
$(cat).each(function(index, cat) { //loops through each cat div
var $dogH = $dog.outerHeight(true);
var $dogW = $dog.outerWidth(true);
var $dogX = $dog.position();
var $dogY = $dog.position();
var $catH = parseInt($(cat).css('height').replace('px', ''))
var $catW = parseInt($(cat).css('width').replace('px', ''))
var $catX = parseInt($(cat).css('left').replace('px', ''))
var $catY = parseInt($(cat).css('top').replace('px', ''))
if ($dogX.left < $catX + $catW &&
$dogY.top < $catY + $catH &&
$catX < $dogX.left + $dogW &&
$catY < $dogY.top + $dogW) {
$(cat).addClass('dead');
$('.score').prepend('<img src="images/cat_dead_sm.png" />');
setTimeout(function() {
$('.dead').remove(); //removes dead cat
}, 2500);
console.log('boom');
};
});
};
$(document).mousemove(function(event) { //moves dog div to follow cursor
$('.dog').css({
'top': event.pageY,
'bottom': event.pageX,
'left': event.pageX,
'right': event.pageY
});
$cat = $('.cat')
getCollision($cat); //calls getcollision to check distance
})();
// function keepScore() {
// $('.score').prepend('<img src="images/cat_dead_sm.png" />');
// }
// };
});
I think the problem is that a dead cat can still die - another iteration of the collision detection can occur before the setTImeout that removes the dead cat is triggered. You could check if the current cat is already dead before prepending the score image.
We just need to check if it's already dead to avoid this:
if ($dogX.left < $catX + $catW &&
$dogY.top < $catY + $catH &&
$catX < $dogX.left + $dogW &&
$catY < $dogY.top + $dogW &&
!$(cat).hasClass('dead')
) {
$(cat).addClass('dead');
$('.score').prepend('<img src="images/cat_dead_sm.png" />');
setTimeout(function () {
$('.dead').remove(); //removes dead cat
}, 2500);
console.log('boom');
}
Or even better - you could avoid collision detection on dead cats entirely:
$cat = $('.cat:not(.dead)');
getCollision($cat);

Continuously fade in and out random pictures

I am trying to get make a function that will continuously fade in and out pictures that are randomly selected, so that the same picture doesn't come up twice. I can get it to fade out / change image / fade in once if it is clicked with
$("img").click(function() { CODE });
but I have to click the image each time, and I am getting stuck trying to make it into a function that is called when the page has loaded:
$(document).ready(function() {
$("img").fadeOut(2000, function() {
while (picPicker1 === picPicker2) {
picPicker2 = (Math.floor(Math.random() * 5) - 1);
}
var source = pics[picPicker2];
$("img").attr("src", source);
$("img").fadeIn(2000);
picPicker1 = picPicker2;
});
});
pics[] is an array with the web addresses of five different pictures. I also tried using setInterval, but that didn't work either. New to all of these languages so thank you in advance for your patience!
setInterval was the correct function to use. The code you've provided in your question is missing a closing });.
Here's some basic code that makes use of setInterval to change the image:
JQuery:
var pics = [
"https://placehold.it/350x150/ff0000",
"https://placehold.it/350x150/00ff00",
"https://placehold.it/350x150/0000ff",
"https://placehold.it/350x150/F2F5A9",
"https://placehold.it/350x150/FF00FF",
];
setInterval(function() {
var picPicker2 = (Math.floor(Math.random() * 5) + 1);
var source = pics[picPicker2];
$("img").fadeOut(500).attr("src", source).fadeIn(500);
}, 2000);
Note: The images will repeat occasionally, but the code I've provided is only a base for you to improve upon.
Fiddle Demo
You can either use setInterval(), for (x = 5; x > 0; x ++) {}, var x = 0; do {} while (x = 0);, or var x = 0; while (x = 0) {}.
$(document).ready(function() {
var picPicker, source;
function generateImage() {
$("img").fadeOut(2000, function() {
picPicker = (Math.floor(Math.random() * 200));
source = 'https://unsplash.it/400/300/?image=' + picPicker;
$("img").attr("src", source);
$("img").fadeIn(2000);
});
setTimeout(generateImage, 5000);
}
generateImage();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<img src="https://unsplash.it/400/300/?image=1">

Creating random image flicker

Basically I'm trying to make a skull flicker over a persons face, I've achieved it flashing up once. But the effect I'm trying to achieve is that it looks more organic and random. Here's the basic structure:
function flicker() {
var maxFlick = 6,
amount = Math.round(Math.random() * maxFlick),
running = false;
function showHide() {
$flicker.show();
running = true;
setTimeout(function() {
$flicker.hide();
running = false;
}, 100)
}
for (i = 0; i < amount; i++) {
if(!running) {
showHide();
}
}
}
setInterval(flicker, 4000);
I had presumed that running a for loop with a random amount statement would produce the desired effect, but it's still only flashing up once every 4000milliseconds as previously. Any pointers?
With the help of Regent and this fiddle I came up with the answer:
function flicker() {
var maxFlick = 6,
amount = Math.round(Math.random() * maxFlick),
delta = 2,
timer;
var doneFlicks = 0;
var flickInterval = setInterval(showHide, timer);
function showHide() {
timer = Math.round((Math.random() + delta) * 100)
$flicker.show();
var hide = setTimeout(function() {
$flicker.hide();
doneFlicks++
}, 20)
if (doneFlicks == amount) {
clearInterval(flickInterval);
}
}
}
setInterval(flicker, 3000);
This produces a randomised flicker effect that's called every 3 seconds - perfect for a horror film effect!
Thanks again to Regent for all the help!

Change random result to sequence

How to change this random result into a sequence starting from lower number? I am new in JS and have tried to make modification with no solution. I hope anybody can help.
function randomFeed() {
var $el = $("#randomFeed");
var random = new Array('news1','news2','news3','news4','news5','news6');
var randomIndex = Math.floor(Math.random() * 4);
var newElement = random[randomIndex];
$el.prepend("<tr><td>" + newElement + "</td></tr>").find("tr").first().hide();
$el.find("tr").first().fadeIn();
if ($el.find("tbody tr").length > 20) {
$el.find("tbody tr").last().fadeOut(400, function() {
$(this).remove();
});
}
slimScrollUpdate($el.parents(".scrollable"));
setTimeout(function() {
randomFeed();
}, 3000);
}
So you need sequential news slide instead of random? Try this (note the global feedIndex variable)
var feedIndex = 0;
function randomFeed() {
var $el = $("#randomFeed"),
news = new Array('news1','news2','news3','news4','news5','news6'),
newElement = news[feedIndex++ % news.length];
//console.log(newElement);
$el.prepend("<tr><td>" + newElement + "</td></tr>").find("tr").first().hide();
$el.find("tr").first().fadeIn();
if ($el.find("tbody tr").length > 20) {
$el.find("tbody tr").last().fadeOut(400, function() {
$(this).remove();
});
}
slimScrollUpdate($el.parents(".scrollable"));
setTimeout(function() {
randomFeed();
}, 3000);
}
BTW, this code in it's state is very bad. It changes the DOM every time to show new feed element. It is better to render all elements whith display:none and only toggle visibility of actual one. It is common pattern
Try this:
news = new Array('news1','news2','news3','news4','news5','news6')
// option 1
news.sort(function() {
return .5 - Math.random();
});
//news = news1,news2,news3,news6,news4,news5
//option 2
len = news.length,
randomNumber = Math.floor((Math.random() * len) + 0);
// randomNumber = 3
part = news.slice(randomNumber, len)
// part = arrnews6,news4,news5
Please be more precise what are you expecting/about what your goal is!

Categories

Resources