SYNTAX ERRORS FIXED. Dreamweaver says that I have an error in my code on line 52. I can't see what is wrong? Maybe this has something to do with the fact that my if and else statements are not working.
IF AND ELSE STATEMENTS FIXED. If I test the if and else statements individually they work correctly, but when I run the entire document, they do not run. Could someone tell me if the error and my if/else statements not working are related or if there is something else wrong.
<script>
var car1=new Object();
car1.Name="Rusty";
car1.Speed="1px", 40;
car1.Distance=0;
var car2=new Object();
car2.Name="Dusty";
car2.Speed="2px", 40;
car2.Distance=0;
var car3=new Object();
car3.Name="Crankshaft";
car3.Speed="4px", 40;
car3.Distance=0;
function runRusty(){
setInterval(function(){moveRusty()},40);
function moveRusty(){car1.Distance=car1.Distance +1
document.getElementById("rusty").style.marginLeft=car1.Distance + "px"
};
};
function runDusty(){
setInterval(function(){moveDusty()},40);
function moveDusty(){car2.Distance=car2.Distance +1
document.getElementById("dusty").style.marginLeft=car2.Distance + "px"
};
};
function runCrankshaft(){
setInterval(function(){moveCrank()},40);
function moveCrank(){car3.Distance=car3.Distance +1
document.getElementById("crankshaft").style.marginLeft=car3.Distance + "px"
};
};
function winLose () {if (document.getElementById("rusty").style.marginLeft="900px"){
alert("Winner is Rusty!");
clearInterval(runRusty);
}
else if(document.getElementById("dusty").style.marginLeft="900px"){
alert("Winner is Dusty!");
clearInterval(runDusty);
}
else if(document.getElementById("crankshaft").style.marginLeft="900px"){
alert("Winner is Crankshaft!");
clearInterval(runCrankshaft);
};
};
</script>
EDIT:
The if and else statements now work as I changed declared my functions globally and changed them slightly. The code now looks as such:
var car1=new Object();
car1.Name="Rusty";
car1.Speed=1;
car1.Distance=0;
var car2=new Object();
car2.Name="Dusty";
car2.Speed=2;
car2.Distance=0;
var car3=new Object();
car3.Name="Crankshaft";
car3.Speed=4;
car3.Distance=0;
var moveRusty;
var moveDusty;
var moveCrankShaft;
function runRusty(){
moveRusty=setInterval(function(){
car1.Distance=car1.Distance + car1.Speed;
document.getElementById("rusty").style.marginLeft=car1.Distance + "px";
winLose();
},40);
};
function runDusty(){
moveDusty=setInterval(function(){
car2.Distance=car2.Distance + car2.Speed;
document.getElementById("dusty").style.marginLeft=car2.Distance + "px";
winLose();
},40);
};
function runCrankshaft(){
moveCrankShaft=setInterval(function(){
car3.Distance=car3.Distance + car3.Speed;
document.getElementById("crankshaft").style.marginLeft=car3.Distance + "px";
winLose();
},40);
}
function winLose () {
if (car1.Distance >= 900){
alert("Winner is Rusty!");
car1.Distance = 0;
car1.Speed = 0;
car2.Distance = 0;
car2.Speed = 0;
car3.Distance = 0;
car3.Speed = 0;
}
else
if(car2.Distance >= 900){
alert("Winner is Dusty!");
car1.Distance = 0;
car1.Speed = 0;
car2.Distance = 0;
car2.Speed = 0;
car3.Distance = 0;
car3.Speed = 0;
}
else
if(car3.Distance >= 900){
alert("Winner is Crankshaft!");
car1.Distance = 0;
car1.Speed = 0;
car2.Distance = 0;
car2.Speed = 0;
car3.Distance = 0;
car3.Speed = 0;
}
};
clearInterval(moveRusty);
clearInterval(moveDusty);
clearInterval(moveCrankShaft);
Everything works now. All the alerts happen and the position of the cars is reset. But all my clearInterval() do not work. I don't know if clearInterval() is the correct thing to use. What I want to do is reset the page so that I can run the "game" again. Right now, the only way to do that is by refreshing the page. I've double checked how I've declared my setInterval() and how I'm calling them in my clearInterval(), and as far as I can it's right?
You are using clearInterval() wrong. You are passing it a function parameter whereas it expects an object.
// correct usage
var time = setInterval(stuff, 100);
clearInterval(time);
You have a semi colon before the else. ; which is a syntax error, remove it . You have a lot of them in weird places also, I suggest you don't put them after function declarations, if blocks if/else blocks, loop blocks etc.
When you want to test if to things are 'equal' in a if statement, you need to use == or === and NOT =
if (document.getElementById("crankshaft").style.marginLeft = "900px") // WRONG
if (document.getElementById("crankshaft").style.marginLeft == "900px") // RIGHT
if (document.getElementById("crankshaft").style.marginLeft === "900px") // BETTER
Read the answer to the following question to know the difference between == and ===
Difference between == and === in JavaScript
Hope this helps
Related
My code is supposed to add 1 to the counter when I hit space and then change the magnifying glass to tilt the other direction. It just doesn't do anything when I hit space.
I've fixed every problem I saw, nothing worked. Maybe somebody else knows, I'm really not that good at js.
var hits = 0;
var hitElement = document.querySelector( '.hits' );
document.body.onkeydown = function(e) {
if( e.keyCode == 32 ) {
addHit();
}
}
var mag = "🔎";
var hitElement2 = document.querySelector( '.mag' );
document.body.onkeydown = function(f) {
if( f.keyCode == 32 ) {
if( mag.text == "🔎") {
mag = "🔍";
renderMag();
else
mag = "🔎";
renderMag();
}
}
}
var addHit = function() {
hits++;
renderHits();
}
var renderMag = function() {
hitElement2.innerHTML = mag;
}
var renderHits = function() {
hitElement.innerHTML = hits;
}
var resetHits = function() {
hits = 0;
renderHits();
}
Console says absolutely nothing too.
I fixed a few things and changed a few things that didn't need fixing. The three key points:
As mentioned, if a bit harshly, by Randy, your second event listener was overwriting your first, so hits was not increasing
The brackets in the if statement of your second event listener had some issues
Though checking the mag icon might work, using icons in the code feels like asking for something to break, so I changed that to a modulo check, to see whether hits was odd or even.
You were on the right track. When you have issues like this in the future, try putting console log statements in various places in the code. Make predictions about what variables should have what values at what points, then check if they do, then, if they don't, try to figure out why not.
var hits = 0;
var hitElement = document.querySelector('.hits');
var mag = "🔎";
var hitElement2 = document.querySelector('.mag');
document.body.onkeydown = function(f) {
if (f.key == ' ') {
addHit();
if (hits % 2 === 0) {
mag = "🔍";
renderMag();
} else {
mag = "🔎";
renderMag();
}
}
}
function addHit() {
hits++;
renderHits();
}
function renderMag() {
hitElement2.innerHTML = mag;
}
function renderHits() {
hitElement.innerHTML = hits;
}
function resetHits() {
hits = 0;
renderHits();
}
<div class="hits"></div>
<div class="mag"></div>
http://csdev.cegep-heritage.qc.ca/students/cguigue/primordialCasino/game.html
supposed to click on the spin button and it should start the wheel spinning as well as changed the text on the screen in my displayArea, though when i click spin nothing happens,
getting undefined type error on the following code and not sure as to why
$('#wheel').rotate({
angle: 0,
animateTo: 2520,
duration: 4000
});
it says it isn't a function... :S
also...
if(currentGame.place == 0 && cellText == 0)
{
currentGame.setBet(betAmount * 40);
}
function rouletteGame(num, even, col)
{
this.place = num;
this.isEven = even;
this.colour = col;
this.win = 0;
this.hasBet = false;
this.setBet = function(bet)
{
this.win += bet;
this.hasBet = true;
}
says currentGame.place is undefined
but im initializing it in a for loop and its calling my above function...
for (var i = 1; i < rouletteWheel.length; ++i)
{
place = i;
if(i % 2 == 1)
{
isEven = false;
}
else
{
isEven = true;
}
if( i = red[count])
{
colour = "red";
++count;
}
else
{
colour = "black";
}
rouletteWheel[i] = new rouletteGame(place, isEven, colour);
}// for ()
.rotate() is not a built-in JQuery plugin. You will need to download or link the plugin in order for it to work. Add the following in your element of the HTML:
<script type="text/javascript" src="http://jqueryrotate.googlecode.com/svn/trunk/jQueryRotate.js"></script>
and see if that helps. with the first part of your problem.
As for the second part, I'm not sure if Javascript works this way too (I think it does), but you should create the new roulette game outside of the loop, and only change the values inside. Otherwise you are only creating a new roulette game for use within the scope of the for loop, not outside.
May want to check the documentation for this, as I'm not 100% positive about it. I just know it's how most other languages work.
I want to increment a counter each time I call a function.
But it is being set to 0 each time I call it.
How can I maintain the updated value of nextKeyIndex?
I am calling getKey function from a javascript file.
Other javascript file which should return updated index (from 0 to 4) has below code..
var nextKeyIndex=0;
function getKey() {
if (nextKeyIndex == 4)
nextKeyIndex = 0;
else
nextKeyIndex = nextKeyIndex + 1;
alert(nextKeyIndex);
I tried you code as below and its working for me. Please try below code.
<script>
var nextKeyIndex=0;
function getKey() {
if (nextKeyIndex == 4)
nextKeyIndex = 0;
else
nextKeyIndex = nextKeyIndex + 1;
alert(nextKeyIndex);
}
</script>
<input type="button" onclick="getKey()" value="click" />
All variables in javascript are by default global if you do not explicitly declare them within a function. Are you sure that the first line declaration (var nextKeyIndex=0) is not being re-run or reloaded somewhere?
Click Me To Increment
var nextKeyIndex=0;
getKey=function() {
if (nextKeyIndex == 4)
nextKeyIndex = 0;
else
nextKeyIndex = nextKeyIndex + 1;
alert(nextKeyIndex);
}
It works for me in jsfiddle:
http://jsfiddle.net/WJYx2/
How to set a global variable in javascript?
You can set a global variable if you declare something without var or declare it as part of window object
global = 10; // global variable
window.global = 10; // also global variable
var nextKeyIndex=0;
function getKey() {
if (nextKeyIndex == 4){
nextKeyIndex = 0;
}else{
nextKeyIndex = nextKeyIndex + 1;
}
alert(nextKeyIndex);
}
I have a variable number of promotional items (panels) that are in a sliding belt, that should be set to the width of a panel (300px) multiplied with the amount of panels.
It alerts the correct beltsize. With fixed numbers the slider works too. I suspect the error to be in the if/else if part. I am not even sure this is valid Javascript Syntax.
Any hint is appreciated.
$(window).ready(function(){
var whichpanel = 1;
var panels = $(".panel").length;
var beltsize = panels*300;
$('.belt').css({'width':beltsize});
});
$(window).ready(function promoslider(){
if (panels>whichpanel){
$('.belt').delay(7000).animate({'left':'-=300'}, 500);
whichpanel += 1;
}
else if (panels=whichpanel){
$('.belt').delay(7000).animate({'left':'0'}, 500);
whichpanel = 1;
}
setTimeout(promoslider, 0);
});
promoslider;
UPDATE! Here is the code that works for me now (http://jsfiddle.net/zr5Nd/10/):
$(window).ready(function () {
var whichpanel = 1;
var panels = $(".panel").length;
var beltsize = panels * 300;
$('.belt').css({
'width': beltsize
});
function movingdiv() {
if (panels > whichpanel) {
//alert('Panels:' + panels + '/whichpanel:' + whichpanel);
$('.belt').delay(1000).animate({
'margin-left': '-=300px'
}, 500);
whichpanel += 1;
} else if (panels == whichpanel) {
//alert('Panels:' + panels + '/whichpanel:' + whichpanel);
$('.belt').delay(1000).animate({
'margin-left': '0'
}, 500*panels);
whichpanel = 1;
} else {
alert('3');
}
setTimeout(movingdiv, 0);
}
setTimeout(movingdiv, 0);
});
You need to use the equality/identity operators (==/===) instead of the assignment operator = in your else if statement, e.g.
else if (panels == whichpanel){
$('.belt').delay(7000).animate({'left':'0'}, 500);
whichpanel = 1;
}
Also, I believe promoslider; is supposed to be promoslider();.
You should put the call of promoslider into $(window).ready as well, as the function does not yet exist otherwise. Plus you have to do the call this way promoslider(), promoslider alone will not result in a call.
And of course you have to use the equals-operator == instead of the assign-operator = in your if else-statement.
use panels === whichpanel instead of panels=whichpanel
variables whichpanel, panels have lost their scope in the if/else if part.
I am beginning to hate objects in javascript.
Every time I have error and I fix it, a new error appears, and so on.
Can you please take a look at the following code and tell me what's wrong ?
problem message:
"this.Images is undefined"
and more errors also
HTML File
<div id="SlideShow" >
<img id="img" src="images/img.jpg" alt="" /><span id="desc"></span>
</div>
<script type="text/javascript">
meToo.Images = ['images/img.jpg','images/img2.jpg','images/img3.jpg','images/img4.jpg','images/img5.jpg'];
meToo.Titles = ['Pic1','pic2','Pic3','Pic4','Pic5'];
meToo.Play('img');
</script>
Javascript Object
var meToo = {
Images: [],
Titles: [],
counter: 0,
Play: function(ElemID){
var element = document.getElementById(ElemID);
var ImgLen = this.Images.length;
if(this.counter < ImgLen){
this.counter++;
element.src = this.Images[this.counter];
element.nextSibling.innerHTML = this.Titles[this.counter];
}else{
this.counter = 0;
}
setTimeout(this.Play, 1000);
}
};
See the Example
See this question. Otherwise setTimeout sets this to the window object. Also, the counter should be incremented after setting the images or you will be reading outside the array bounds.
Finally, when resetting the counter to 0, there will be an additional one-second delay before the loop restarts, because the image is not being reset in that else block. You may wish to rewrite that part of the logic.
Updated Fiddle
if(this.counter < ImgLen){
element.src = this.Images[this.counter];
element.nextSibling.innerHTML = this.Titles[this.counter];
this.counter++;
}else{
this.counter = 0;
}
var _this = this;
setTimeout(function() { _this.Play('img') }, 1000);
This is what I would write to keep the loop going at one-second intervals:
Play: function(ElemID) {
var element = document.getElementById(ElemID);
var ImgLen = this.Images.length;
if (this.counter == ImgLen) {
this.counter = 0;
}
element.src = this.Images[this.counter];
element.nextSibling.innerHTML = this.Titles[this.counter];
this.counter++;
var _this = this;
setTimeout(function() {
_this.Play('img')
}, 1000);
}
if(this.counter < ImgLen)
is wrong.
What will happen here is that when you run
this.counter++;
the value of that variable will now be ImgLen.length
Arrays in javascript go from 0 to length -1.So now you'll be exceeding the array's length, when you run:
this.Images[this.counter];
and encounter an error.
The quick fix here is to change to
if(this.counter < ImgLen -1)
If you're encountering other problems, then post the exact error message. (Run in Chrome and press F12 (for example) to bring up the console so you can see the errors).
Here check this out.It should work perfectly for you.I have made it a singleton object and also I am doing a check if incase meToo.Play is called before the dom is loaded it will not crash.All the other mistakes that the guys above are pointing are also taken care of.
<script>
var meToo = function(){
var Images = ['http://www.image-upload.net/di/WMPI/img.jpg','http://www.image-upload.net/di/HPUQ/img2.jpg','http://www.image-upload.net/di/WQ9J/img3.jpg','http://www.image-upload.net/di/GIM6/img4.jpg','http://www.image-upload.net/di/0738/img5.jpg'];
var Titles = ['Pic1','pic2','Pic3','Pic4','Pic5'];
var counter = 0;
return {
Play: function(ElemID) {
var element = document.getElementById(ElemID);
if(element){
var ImgLen = Images.length;
if(counter < ImgLen) {
element.src = Images[counter];
element.nextSibling.innerHTML = Titles[this.counter];
counter++;
} else {
counter = 0;
}
}
setTimeout(callmeToo, 1000);
}
}
}();
function callmeToo(){
meToo.Play('img');
}
callmeToo();
</script>