COM
COM

Reputation: 71

Javascript functions an if statements

I'm making an Odd one out game and Im a bit stuck with the functions of it. (I have added an alert so I know that the image is being clicked on) So basically character 3 is the odd one out and character 1 + 2 are not the odd ones out. But when I click on characters 1 + 2 the same alert comes up as the one for character 3 (the odd one out). I've tried making new functions for the right/wrong answers but thats not working either. It's probably only something small but Im really stuck and any help at all would be appreciated.

This is the HTML:

<div id ="characters">
<img src="boy__pirate.png" class = "character" id ="character1"      onclick="characterclicked(1);" >
<img src="girl__pirate.png" class = "character" id ="character2"   onclick="characterclicked(2);" >
<img src="pig__.png" class = "character" id ="character3" onclick="characterclicked(3);"> 
</div> 

This is the JS:

var oddoneout = new Array(); 
oddoneout[0] = {characterName:"character3", answer: 1};  
oddoneout[1] = {characterName:"character6", answer: 2};
oddoneout[2] = {characterName:"character9", answer: 3}; 

oddoneout.sort(function() {return Math.random() -0.5;});


function characterclicked() {  
if (oddoneout) {  
    alert("You're right!")


} 
} 

Upvotes: 1

Views: 96

Answers (2)

gaetanoM
gaetanoM

Reputation: 42044

Try to change characterclicked to:

var oddoneout = new Array();
    oddoneout[0] = {characterName:"character3", answer: 1};
    oddoneout[1] = {characterName:"character6", answer: 2};
    oddoneout[2] = {characterName:"character9", answer: 3};

    oddoneout.sort(function(a, b) {return Math.random() -0.5;});


    function characterclicked(i) {
        switch(i) {
            case 1:
            case 2:
            case 3:
                if (oddoneout[i-1].answer == i) {
                    alert("You're right!");
                }
                break;
            default:
                alert(i);
                break;
        }
    }

To unsort the array your comparison function is wrong. So I tried to adjust your code hoping it could help you.

Upvotes: 1

Bill Cheng
Bill Cheng

Reputation: 956

var oddoneout = new Array(); 
oddoneout[0] = {characterName:"character3", answer: 1};  
oddoneout[1] = {characterName:"character6", answer: 2};
oddoneout[2] = {characterName:"character9", answer: 3}; 

oddoneout.sort(function() {return Math.random() -0.5;});

function characterclicked(choice) {  
// perform your checking here
if (oddoneout[choice-1].answer===2) { 
    alert("You're right!")
    } 
}

Upvotes: 1

Related Questions