<script type="text/javascript">
var interval;
$('#105').mouseover(function()
{ mouseOver('105'); });
$('#105').mouseout(function()
{ mouseOut('105') ;});
function mouseOver(videoId)
{ var num = 2;
interval = setInterval(function()
{ $('#'+videoId).attr('src', '../thumbs/268255615/268255615.'+num+'.jpg');
if(num == 12)
{ num = 1; }
else
{ num++; }},500); }
function mouseOut (videoId)
{ clearInterval(interval); $('#'+videoId).attr('src', '../thumbs/268255615/268255615.1.jpg'); }
</script>
<script type="text/javascript">
var interval;
$('#104').mouseover(function()
{ mouseOver('104'); });
$('#104').mouseout(function()
{ mouseOut('104') ;});
function mouseOver(videoId)
{ var num = 2;
interval = setInterval(function()
{ $('#'+videoId).attr('src', '../thumbs/325082397/325082397.'+num+'.jpg');
if(num == 12)
{ num = 1; }
else
{ num++; }},500); }
function mouseOut (videoId)
{ clearInterval(interval); $('#'+videoId).attr('src', '../thumbs/325082397/325082397.1.jpg'); }
</script>
The code above is a JavaScript image rotator. The problem with the code is that the last image path always overwrites the image paths before it.
For example if image path one = thumbs/imagea.jpg and if path two = thumbs/imageb.jpg path one ("thumbs/imagea.jpg")then becomes path two on hover becomes ("thumbs/imageb.jpg")
This script worked at one point trying to figure out what is wrong or been changed any ideas?
This is quite obvious: you are redefining mouseOver as a function. The second time you define it, it overwrites the first function. This is because mouseOver is defined on window-scope. Splitting it up in two blocks does not change that. Also note that "interval" is also being defined twice, so a name clash will also occur here.
A solution would be to either use closures, change the name of one of either functions or merge the two functions into one.
Closures are done by wrapping each script in the following block:
(function() {
// your script here
}());
A merged function would be:
var i, setupImage, images;
images = [
{ "id" : "#104", "prefix" : "../thumbs/325082397/325082397." },
{ "id" : "#105", "prefix" : "../thumbs/268255615/268255615." }
];
setupImage = function (image) {
'use strict';
var interval;
$(image.id).mouseover(function () {
var num = 2;
interval = setInterval(function () {
$(image.id).attr('src', image.prefix + num + '.jpg');
if (num === 12) {
num = 1;
} else {
num += 1;
}
}, 500);
});
$(image.id).mouseout(function () {
$(image.id).mouseout(function () {
clearInterval(interval);
$(image.id).attr('src', image.prefix + '1.jpg');
});
});
};
for (i = 0; i < images.length; i += 1) {
setupImage(images[i]);
}
Related
I have the following code:
var lives = 10;
var score = 0;
var input = $('#input');
var board = $('#board');
var validate = $('#validate');
function randomNum(min, max) {
return Math.random() * (max - min) + min;
}
var levelOne = (randomNum(0, 999));
var levelTwo = (randomNum(999, 1999));
$('#generate').click(function () {
if (score > 1) {
board.html(levelOne);
console.log(levelOne)
setTimeout(function () {
board.fadeOut();
}, 3000);
} else {
board.html(levelTwo);
console.log(levelTwo)
setTimeout(function () {
board.fadeOut();
}, 3000);
}
});
The first number gets it output as expected, but if I keep on generating numbers, the logs say it's the same number plus I can't see it in the screen (the timeout is not working as well?). I've done this game in Objective-C but now in JS something is missing in my logic. Can someone give me a hint?
EDIT: I've tried this
$('#generate').click(function () {
var levelOne = (randomNum(0, 999));
if (score > 1) {
board.html(levelOne);
console.log(levelOne)
setTimeout(function () {
board.fadeOut();
}, 3000);
} // etc
}
and also inside the if. I don't understand why I get always the same number.
You're caching the variables levelOne and levelTwo outside of your click handler so random numbers are only generated once, if you're like them to be repeatedly regenerated put those lines inside your click handler like so:
var lives = 10;
var score = 0;
var input = $('#input');
var board = $('#board');
var validate = $('#validate');
function randomNum(min, max) {
return Math.random() * (max - min) + min;
}
$('#generate').click(function () {
if (score > 1) {
var levelOne = randomNum(0, 999);
board.html(levelOne);
console.log(levelOne)
setTimeout(function () {
board.fadeOut();
}, 3000);
} else {
var levelTwo = randomNum(999, 1999);
board.html(levelTwo);
console.log(levelTwo)
setTimeout(function () {
board.fadeOut();
}, 3000);
}
});
The 'Win' and 'Draw' parts are showing up on time, but the 'Lost' part doesn't show the message 'you lost'until I click on an empty cell once again. Please check out my code and help me find any errors.
Below is my code:
Marked is a class that changes the opacity of the clicked cell.
1,2,3...are the id's of respective cells in the table(html).
I tried delay() too instead of setTimeout(), but it didn't work as well.
$(document).ready(function() {
var timer;
var x = 0;
$("td").click(function() {
if($(this).text()=='') {
$(this).text("0").addClass("marked");
x = 1;
}
}).click(function() {
if(x==1) {
timer = setTimeout(function() {
var choose = $("td").not(".marked");
var random = choose[Math.floor(Math.random()*choose.length)];
$(random).text("X").addClass("marked");
},1000);
x=0;
showResult();
}
});
function showResult() {
var one = $("#1").text();
var two = $("#2").text();
var three = $("#3").text();
var four = $("#4").text();
var five = $("#5").text();
var six = $("#6").text();
var seven = $("#7").text();
var eight = $("#8").text();
var nine = $("#9").text();
if(one==two && two==three)
result(one)
else if (four==five && five==six)
result(four)
else if(seven==eight && eight==nine)
result(seven)
else if (one==four && four==seven)
result(one)
else if (two==five && five==eight)
result(two)
else if (three==six && six==nine)
result(three)
else if (one==five && five==nine)
result(one)
else if(three==five && five==seven)
result(three);
else {
var z = $("td").not(".marked");
if(z.length == 0) {
$("p").text("Draw!");
$("td").removeClass("marked");
$("td").text("");
$("#demo1").append('<img src="https://media.tenor.com/images/54c63f726505bfdb455eb4c29e626ad8/tenor.gif">');
clearTimeout(timer);
}
}
}
function result(y) {
var result = y;
if(result=="X"){
clearTimeout(timer);
$("p").text("You Lost!");
$("td").removeClass("marked");
$("td").text("");
$("#demo1").append('<img src="https://media.tenor.com/images/08902a85a6107684f8614846f4a54218/tenor.gif">');
}
if(result=="0") {
$("td").text("");
$("p").text("You Won!");
$("#demo1").append('<img src="https://i.gifer.com/4OuC.gif">');
$("td").removeClass("marked");
clearTimeout(timer);
}
}
});
You are calling showResult immeadiately when the user clicked, so it cant't recognize the X put into the table one second later.
Just do:
$("td").click(function() {
[...]
}).click(function() {
if (x == 1) {
timer = setTimeout(function() {
var choose = $("td").not(".marked");
var random = choose[Math.floor(Math.random() * choose.length)];
$(random).text("X").addClass("marked");
/******** ADD ANOTHER CHECK HERE ********/
showResult();
}, 1000);
x = 0;
showResult();
}
});
It might also be a good idea to add a return to showResult that returns false when a result was achieved. This way you could do something like
x = 0;
if (showResult()) {
timer = setTimeout(function() {
[...]
}
}
And the user can't get a loose message right after a win message.
Also: Why do you need the 2 click listeners? You can just use the if statement in the top one and then you don't need the (x == 1)
Good day all, I'm trying to make a jquery game where a group of enemy will spawn after a group of enemy gets destroyed. I'm calling alien_cruiser() function & unbinding minion_roulette() function after minion_roulette_counter gets 0. But every time I run, function does not get unbind & after counter gets 0 both type of enemies show. I want to run them one by one. Here are the codes:
var sound = new Audio("sounds//dishoom.ogg");
var score = 0;
var minion_roulette_life = 10;
var cruiser_life = 20;
var minion_roulette_counter = 3;
var cruiser_counter = 3;
function processBullet() {
$(".projectile").each(function() {
var maxTop = $(this).offset().top;
var breakable1 = $(this).collision("#minion-roulette");
var breakable2 = $(this).collision("#cruiser");
$(this).css("top", maxTop - 25);
if (breakable1.length != 0 || breakable2.length != 0) {
$(this).remove();
}
if (maxTop <= 35) {
$(this).remove();
}
if (breakable1.length != 0) {
--minion_roulette_life;
if (minion_roulette_life == 0) {
sound.play();
breakable1.remove();
minion_roulette(true);
minion_roulette_counter--;
$("#score").html(++score);
minion_roulette_life = 10;
}
}
//This is the place where it checks if counter is 0 or not
if (minion_roulette_counter == 0) {
$('#content').unbind(function() {
minion_roulette(false)
});
alien_cruiser(false);
minion_roulette_counter = -1;
}
if (breakable2.length != 0) {
--cruiser_life;
if (cruiser_life == 0) {
sound.play();
breakable2.remove();
alien_cruiser(true);
$("#score").html(++score);
cruiser_life = 20;
}
}
});
}
Am I doing any wrong here? Please I need a solution badly. Tnx.
In this situation, you could use a conditional statement to determine which function to call.
For example:
if (minion_roulette_counter == 0) {
alien_cruiser();
}
else {
minion_roulette();
}
Binding and unbinding doesn't 'turn off' a function, unfortunately. To quote MDN:
The bind() method creates a new function that, when called, has its this keyword set to the provided value, with a given sequence of arguments preceding any provided when the new function is called.
– MDN: 'Bind'
If possible I'd like to use to remove count and use an argument in self.addOrbitTrap(). At the moment for testing my code does something like this:
Bbrot.prototype.findMSet = function() {
//...code
var self = this;
canvasInterval = setInterval(function() {
self.addOrbitTrap();
}, 0);
}
var count = 0;
Bbrot.prototype.addOrbitTrap = function() {
//...code
if (count === 100) {
// Call a different function. That's why I use count
}
count++;
}
Edit: To be more specific, count is used in my code to count how many times addOrbitTrap() successfully runs (it does not add an orbit trap if a randomly selected pixel is a part of the Mandelbrot Set). After it runs some number of times, I call a different function (from within addOrbitTrap()). I would rather not use a global variable because count is not used anywhere else.
You could introduce count as a local variable inside findMSet that you pass to addOrbitTrap(); at each interval the value will be increased:
Bbrot.prototype.findMSet = function() {
//...code
var self = this,
count = 0;
canvasInterval = setInterval(function() {
self.addOrbitTrap(++count);
}, 0);
}
Handling the value is simple:
Bbrot.prototype.addOrbitTrap = function(count) {
//...code
if (count === 100) {
// Call a different function. That's why I use count
}
}
just make the variable on the object and use it.
Bbrot.prototype.count = 0;
Bbrot.prototype.findMSet = function() {
//...code
var self = this;
canvasInterval = setInterval(function() {
self.addOrbitTrap();
}, 0);
}
Bbrot.prototype.addOrbitTrap = function() {
if(ranSuccessful)
this.count++;
}
Bbrot.prototype.someOtherFunc = function() {
return this.count;
}
I am trying to figure out a way to make my countdown timer restart at 25 all over again when it reaches 0. I dont know what I am getting wrong but it wont work.
Javascript
window.onload = function() {
startCountDown(25, 1000, myFunction);
}
function startCountDown(i, p, f) {
var pause = p;
var fn = f;
var countDownObj = document.getElementById("countDown");
countDownObj.count = function(i) {
//write out count
countDownObj.innerHTML = i;
if (i == 0) {
//execute function
fn();
//stop
return;
}
setTimeout(function() {
// repeat
countDownObj.count(i - 1);
},
pause
);
}
//set it going
countDownObj.count(i);
}
function myFunction(){};
</script>
HTML
<div id="countDown"></div>
try this, timer restarts after 0
http://jsfiddle.net/GdkAH/1/
Full code:
window.onload = function() {
startCountDown(25, 1000, myFunction);
}
function startCountDown(i, p, f) {
var pause = p;
var fn = f;
var countDownObj = document.getElementById("countDown");
countDownObj.count = function(i) {
// write out count
countDownObj.innerHTML = i;
if (i == 0) {
// execute function
fn();
startCountDown(25, 1000, myFunction);
// stop
return;
}
setTimeout(function() {
// repeat
countDownObj.count(i - 1);
}, pause);
}
// set it going
countDownObj.count(i);
}
function myFunction(){};
I don't see you resetting the counter. When your counter goes down to 0, it executes the function and return. Instead, you want to execute the function -> reset the counter -> return
You can do this by simply adding i = 25 under fn() :
function startCountDown(i, p, f) {
var pause = p;
var fn = f;
var countDownObj = document.getElementById("countDown");
countDownObj.count = function(i) {
// write out count
countDownObj.innerHTML = i;
if (i == 0) {
// execute function
fn();
i = 25;
// stop
return;
}
setTimeout(function() {
// repeat
countDownObj.count(i - 1);
},
pause
);
}
// set it going
in #Muthu Kumaran code is not showing zero after countdown 1 . you can update to this:
if (i < 0) {
// execute function
fn();
startCountDown(10, 1000, myFunction);
// stop
return;
}
The main reason for using setInterval for a timer that runs continuously is to adjust the interval so that it updates as closely as possible to increments of the system clock, usually 1 second but maybe longer. In this case, that doesn't seem to be necessary, so just use setInterval.
Below is a function that doesn't add non–standard properties to the element, it could be called using a function expression from window.onload, so avoid global variables altogether (not that there is much point in that, but some like to minimise them).
var runTimer = (function() {
var element, count = 0;
return function(i, p, f) {
element = document.getElementById('countDown');
setInterval(function() {
element.innerHTML = i - (count % i);
if (count && !(count % i)) {
f();
}
count++;
}, p);
}
}());
function foo() {
console.log('foo');
}
window.onload = function() {
runTimer(25, 1000, foo);
}