How to pass function to V-on - javascript

I'm stuck with this error when I try to press Next to switch question & answer.
I'm currently using Vue2.
What should I change if i want to use nextbtn function to switch question & answer at the same time.
Error:"[Vue warn]: Error in v-on handler: 'ReferenceError: nextBtn is not defined'
found in
--->
"
HTML
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<div id="app1">
<display-question></display-question>
</div>
JS
Vue.component('display-question',{
data: function(){
return{
counter: 0,
currentQuestion: 0,
answered: 0,
showWrongQuestion: false,
wrongQuestions: [],
temp: [],
wrongAnswers: 0,
correctAnswers: 0,
message: "Enter your answer here",
WhatAnswer: "default",
questions: [
{
question: 'What is the capital of Ukrain ?',
answer: [
'Kyiv',
' Kabul',
' Buenos Aires',
' Praia'
],
correct_answer: 0,
selected: null,
sense: 0
},
{
question: 'When was Queen Elizabeth II death ?',
answer: [
'11/09/2022',
'08/09/2022',
'12/08/2022',
'07/09/2022'
],
correct_answer: 1,
selected: null,
sense: 0
},
{
question: 'How many bones are there in human body?',
answer: [
'206',
'186',
'209',
'190'
],
correct_answer: 0,
selected: null,
sense: 0
},
{
question: 'Who were the 30th president of ?',
answer: [
'Julia Eileen Gillard',
'John Winston Howard ',
' Scott John Morrison ',
'Anthony Albanese,'
],
correct_answer: 2,
selected: null,
sense: 0
},
{
question: 'What is the biggest continent?',
answer: [
'Oceania',
'Europe',
'Asia',
'Africa'
],
correct_answer: 2,
selected: null,
sense: 0
}
],
}},
methods: {
backBtn:function () {
if (this.question > 0) {
this.question = this.question - 1;
}
},
nextBtn: function(){
this.answered < this.questions.length ? this.answered++ : '';
if(!nextBtn.hasAttribute('disabled') && this.currentQuestion < (questionsLength -1)) {
this.currentQuestion++; //I think error happen here
answers.forEach(answer => {
answer.classList.contains('selected') ? answer.classList.remove('selected') : '';
});
nextBtn.setAttribute('disabled', '');
}
else if(this.currentQuestion >= (questionsLength -1)) {
this.questions.forEach( (question) => {
if(question.selected == question.correct_answer && question.sense ==0) {
this.correctAnswers++;
question.sense = 1;
} else if(question.selected != question.correct_answer && question.sense ==0) {
this.wrongAnswers++;
question.sense = 1;
let temp = {};
temp.answers = question.answers;
temp.question = question.question;
temp.correct_answer = question.correct_answer;
temp.selected = question.selected;
this.wrongQuestions.push(temp);
}
});
result.classList.add('active');
question.classList.add('blur');
}
},
calculateResult: (questions) => {
var correct;
for(var i=0; i< questions.length; i++) {
this.questions[i].selected == questions[i].correct ? correct++ : '';
}
return (correct / questions.length) * 100;
},
selectAnswer: function(a) {
var choice = a.currentTarget,
answers = document.querySelectorAll('.answers span'),
nextBtn = document.querySelector('.next-btn');
answers.forEach(answer => {
answer.classList.contains('selected') ? answer.classList.remove('selected') : '';
});
choice.classList.add('selected');
this.questions[this.currentQuestion].selected = choice.dataset.index;
nextBtn.removeAttribute('disabled');
},
},
mounted() {
var nextBtn = this.$el.querySelector('.next-btn'),
wrongAnswersBtn = this.$el.querySelector('.show-wrong-ones'),
backBtn = this.$el.querySelector('.back-Btn'),
answers = this.$el.querySelectorAll('.answers span'),
questionsLength = this.questions.length,
result = this.$el.querySelector('.result'),
question = this.$el.querySelector('.question'),
closeResult = this.$el.querySelector('.result button.close'),
wrongQuestions = this.$el.querySelector('.wrong-questions'),
showMyResults = this.$el.querySelector('#return-to-result');
},
template: '<div><div v-if="counter < questions.length"> <h2>{{questions[currentQuestion].question }}</h2></br> <span class=answer v-for="(answer, index) in questions[currentQuestion].answer" :key="index" v-bind:data-index="index" #click="selectAnswer">{{ answer }}</span><p><button class="backBtn" v-on:click="backBtn">BACK</button> <button class="next-btn" v-on:click="nextBtn" disabled > {{ currentQuestion < (questions.length -1) ? "Next" : "Result!" }} </button></p> </div> <div class="result"><div class="success"></div></div></div>',
})
var test1 = new Vue({
el: "#app1",
data: {
},
});

It seems like what's undefined is not the nextBtn method, but the nextBtn variable that you referenced inside the nextBtn method (from this line if(!nextBtn.hasAttribute('disabled') && this.currentQuestion < (questionsLength -1)) {), on mounted you initialized some variables, you should declare those variables first on data(), then initialize in the mounted. When you're accessing the data, you should use this like this.nextBtn, also try to change the name of the variables so that they're not the same as the name of the method (e.g. in here you have nextBtn as a function and nextBtn as a variable).

Related

filter value from array (object) react

I'm learning by coding, here i have 'allNodes' an array of objects and 'currentNodee' object, i want to check if allNodes contains 'analyser' and 'id' which is equal to 'analyser' and 'id' of 'currentNodee' then take 'analyser' value and print it, but if for example 'allNodes' has same id but its analyser is 'undefined' then do not print anything.
what am i doing wrong here ? any idea is appreciated
const allNodes = [
{ analyser: undefined, id: 7 },
{ analyser: "abc", id: 6 },
];
const currentNodee = { analyser: "abc", id: 7 };
console.log(
allNodes.find((option: any) => {
option.id === currentNodee.id &&
option?.analyser === currentNodee?.analyser;
})
);
English is not my mother language so could be mistakes.
Presented below is one possible way to achieve the desired objective.
Code Snippet
const rd = document.getElementById("rd");
const btn = document.getElementById("myBtn");
const btn2 = document.getElementById("myBtn2");
const allNodes = [{
analyser: undefined,
id: 7
},
{
analyser: "abc",
id: 6
},
];
const currentNodee = {
analyser: "abc",
id: 7
};
const currentNodef = {
analyser: "abc",
id: 6
};
const getResult = (curr) => {
const tgt = allNodes.find(
({ analyser, id }) => curr.id === id
);
if (tgt) {
if (
tgt.analyser &&
tgt.analyser === curr.analyser
) {
return JSON.stringify(tgt);
} else {
return "print nothing";
}
} else {
return "not found"
};
};
btn.textContent = 'Search analyser id=7';
btn.addEventListener('click', () => {
rd.innerText = getResult(currentNodee);
});
btn2.textContent = 'Search analyser id=6';
btn2.addEventListener('click', () => {
rd.innerText = getResult(currentNodef);
});
<div>
Search result: <div id="rd">empty</div>
<button id="myBtn" />
<button id="myBtn2" />
</div>
Printing in single line can be done using JSON.stringify() as demonstrated in the above code snippet.
const allNodes = [
{ analyser: undefined, id: 7 },
{ analyser: "abc", id: 6 },
];
const currentNodee = { analyser: "abc", id: 7 };
const result = allNodes.find(node => (node.analyser === currentNodee.analyser) && (node.id === currentNodee.id))
console.log(!result ? 'No result found' : result);

How to get inside this if statement (JavaScript)

I'm creating this simple quiz with 6 questions that I'm storing in an array. What I'm stuck with is that when you've reached the last question and you click 'Next', I'd like to show your results along with a text and a 'Restart' button.
What happens now though is that it show the last question again but without any answer-butons (I'm not getting into that if statement).
I'm pretty new to js, here's my code.
const startQuiz = document.querySelector('.container__start-btn');
const theQuestion = document.querySelector('.container__question');
const fourAnswers = document.querySelector('.container__answers');
const counter = document.querySelector('.container__counter__correct-answer');
const questionCounter = document.querySelector('.container__counter__question-nr');
const containerCounter = document.querySelector('.container__counter');
let currentQuestion = 0;
let count = 0;
const showQuestion = () => {
startQuiz.innerText = 'NEXT';
while (fourAnswers.firstChild) {
fourAnswers.removeChild(fourAnswers.firstChild);
}
theQuestion.innerText = questions[currentQuestion].question;
checkCounters();
}
const checkCounters = () => {
counter.textContent = `Score: ${count}`;
questionCounter.textContent = `Question: ${currentQuestion + 1}/${questions.length}`;
generateAnswers();
}
const generateAnswers = () => {
questions[currentQuestion].answers.forEach(answer => {
const button = document.createElement('button');
button.innerText = answer.answer;
if (answer.correct) {
button.classList.add('right');
}
button.classList.add('btn');
fourAnswers.appendChild(button);
fourAnswers.classList.remove('hide');
})
fourAnswers.onclick = () => {
const selected = event.target;
if (selected.classList.contains('right')) {
selected.classList.add('selectedRight');
count++;
counter.textContent = `Score: ${count}`;
}
if (!selected.classList.contains('right')) {
selected.classList.add('selectedWrong');
}
const rightA = document.querySelector('.right');
rightA.classList.add('selectedRight');
}
currentQuestion++;
if (currentQuestion > questions.length) {
console.log('inside if');
startQuiz.innerText = 'START';
theQuestion.innerText = `Good job! You got ${count} correct answers out of ${questions.length}. Press 'START' to go again.`;
count = 0;
currentQuestion = 0;
}
}
const questions = [
{
question: 'What is the capital of Greece?',
answers: [
{ answer: 'Athens', correct: true },
{ answer: 'Gothenburg', correct: false },
{ answer: 'Madrid', correct: false },
{ answer: 'Berlin', correct: false }
]
},
{
question: 'What is the capital of Sweden?',
answers: [
{ answer: 'Stockholm', correct: true },
{ answer: 'Lisboa', correct: false },
{ answer: 'Paris', correct: false },
{ answer: 'New York', correct: false }
]
},
{
question: 'What is the capital of Portugal?',
answers: [
{ answer: 'Lisboa', correct: true },
{ answer: 'Valencia', correct: false },
{ answer: 'Porto', correct: false },
{ answer: 'London', correct: false }
]
},
{
question: 'What is the capital of Argentina?',
answers: [
{ answer: 'Buenos Aires', correct: true },
{ answer: 'Santiago', correct: false },
{ answer: 'Amsterdam', correct: false },
{ answer: 'Beijing', correct: false }
]
},
{
question: 'What is the capital of Thailand?',
answers: [
{ answer: 'Bangkok', correct: true },
{ answer: 'Manila', correct: false },
{ answer: 'Rome', correct: false },
{ answer: 'Nicosia', correct: false }
]
},
{
question: 'What is the capital of Denmark?',
answers: [
{ answer: 'Copenhagen', correct: true },
{ answer: 'Oslo', correct: false },
{ answer: 'Beirut', correct: false },
{ answer: 'Los Angeles', correct: false }
]
}
]
startQuiz.addEventListener('click', showQuestion);
You should change the line 51 as follows.
if (currentQuestion >= questions.length) {
This is because the questions.length is 6 and the counter currentQuestion is 6 at the last question.
-- edit --
OK, try to modify like the following.
const showQuestion = () => {
if (currentQuestion >= questions.length) {
console.log('inside if');
startQuiz.innerText = 'START';
theQuestion.innerText = `Good job! You got ${count} correct answers out of ${questions.length}. Press 'START' to go again.`;
count = 0;
currentQuestion = 0;
return;
}
startQuiz.innerText = 'NEXT';
while (fourAnswers.firstChild) {
fourAnswers.removeChild(fourAnswers.firstChild);
}
theQuestion.innerText = questions[currentQuestion].question;
checkCounters();
currentQuestion++;
}
And delete currentQuestion++; from generateAnswers()
Difficult to be sure without a full reproducible jsfiddle, but I think it should be:
if (currentQuestion >= questions.length)
instead of:
if (currentQuestion > questions.length)
Put your if in the beginning of the function and return inside of it so that you exit the function and do nothing else once you go into the if.
Currently what's happening is that the foreach is triggered even when the currentQuestion has passed the questions.length.
Also add the check to be more or equal.
const generateAnswers = () => {
if (currentQuestion >= questions.length) {
console.log('inside if');
startQuiz.innerText = 'START';
theQuestion.innerText = `Good job! You got ${count} correct answers out of ${questions.length}. Press 'START' to go again.`;
count = 0;
currentQuestion = 0;
return; // end the function here so the other logic doesn't trigger.
}
questions[currentQuestion].answers.forEach(answer => {
const button = document.createElement('button');
button.innerText = answer.answer;
if (answer.correct) {
button.classList.add('right');
}
button.classList.add('btn');
fourAnswers.appendChild(button);
fourAnswers.classList.remove('hide');
})
fourAnswers.onclick = () => {
const selected = event.target;
if (selected.classList.contains('right')) {
selected.classList.add('selectedRight');
count++;
counter.textContent = `Score: ${count}`;
}
if (!selected.classList.contains('right')) {
selected.classList.add('selectedWrong');
}
const rightA = document.querySelector('.right');
rightA.classList.add('selectedRight');
}
currentQuestion++;
}

Issue with key/value pair in for loop: Cannot read property 'achievement' of undefined\n

Is it possible to get the current key of newAchievements in the for loop for (var key in achievementObject) after the line newAchievements.push?
For example, if the key of achievementObject is “Finish level 1”, is it possible to return the current key of newAchievements(which would be 0 in this case) after the line newAchievements.push in the same for loop?
Right now, I get this JavascriptException:
"StackTrace": "TypeError: Cannot read property 'achievement' of undefined\n at handlers.UpdateAchievementsReadOnlyData (...-main.js:24:34)\n at Object.invokeFunction (Script:116:33)"
I need to update the value of the achievement "Level1FinishTimes" with server.UpdateUserReadOnlyData(MyRequest); before I call ChooseanAchievement() for the next key/value pair.
Is it possible to get the current key of newAchievements in the for loop? If not, what would be the best way to update the value of an achievement(with server.UpdateUserReadOnlyData(MyRequest);) before I call ChooseanAchievement() for the next key/value pair?
handlers.UpdateAchievementsReadOnlyData = function (args, context)
{
var achievementObject = args.AchievementObject;
var achievementKeys = [];
var newAchievements = [];
for (var key in achievementObject)
{
achievementKeys.push(key);
};
log.info(achievementKeys);
var getUserReadOnlyDataResult = server.GetUserReadOnlyData({ PlayFabId: currentPlayerId, Keys: achievementKeys });
for (var key in achievementObject)
{
log.info("achievementObject[key]--->" + achievementObject[key]);
newAchievements.push(ChooseanAchievement(getUserReadOnlyDataResult, key, achievementObject[key]));
if (newAchievements[key].achievement != "")
{
log.info("newAchievements.achievement " + newAchievements[key].achievement, "newAchievements.addvalue " + newAchievements[key].addvalue);
var MyRequest = {
PlayFabId: currentPlayerId,
Data: {},
Permission: UserDataPermission.Public
};
MyRequest.Data[newAchievements[key].achievement] = newAchievements[key].addvalue;
server.UpdateUserReadOnlyData(MyRequest);
log.info("Updating achievement " + newAchievements[key].achievement + " was succuessful.");
}
else
{
log.info("Could not find this achievement.");
}
};
}
function ChooseanAchievement(result, achievementkey, achievementvalue)
{
switch (achievementkey)
{
case "Level1FinishTimes":
if (result.Data.hasOwnProperty(achievementkey))
{
if ((result.Data[achievementkey].Value != null) && (result.Data[achievementkey].Value != ""))
{
if (Number(achievementvalue) == 1)
{
log.info("Level1FinishTimes ok" + achievementkey + achievementvalue);
return { achievement: achievementkey, addvalue: Number(result.Data[achievementkey].Value) + Number(achievementvalue) };
}
else
{
log.info("Level1FinishTimes" + achievementkey + achievementvalue);
return { achievement: achievementkey, addvalue: result.Data[achievementkey].Value };
}
}
else
return { achievement: "", addvalue: false };
}
else
return { achievement: "", addvalue: false };
break;
case "Finish level 1 three times":
var resultdatalevel1finish = server.GetUserReadOnlyData({ PlayFabId: currentPlayerId, Keys: ["Level1FinishTimes"] });
if (resultdatalevel1finish.Data.hasOwnProperty("Level1FinishTimes"))
{
if ((resultdatalevel1finish.Data.Level1FinishTimes.Value != null) && (resultdatalevel1finish.Data.Level1FinishTimes.Value != ""))
{
if ((Number(resultdatalevel1finish.Data.Level1FinishTimes.Value) >= 3) && (achievementvalue == true))
{
log.info("Finish level 1 three times ok" + achievementkey + achievementvalue);
return { achievement: achievementkey, addvalue: achievementvalue };
}
else
{
log.info("Finish level 1 three times" + achievementkey + achievementvalue);
return { achievement: achievementkey, addvalue: result.Data[achievementkey].Value };
}
}
else
return { achievement: "", addvalue: false };
}
else
return { achievement: "", addvalue: false };
break;
//...
}
}
It looks like you are misunderstood the terms key and index of an array. You are pushing an item into array. You need to use index to get an item of an array, e.g. fooData[0]:
const fooData = [
{'Finish level 0': 0, test1: 0},
{'Finish level 1': 1, test1: 1},
{'Finish level 2': 2, test1: 2},
];
fooData.push({'Finish level 3': 0, test1: 3});
// To get newly pushed item of array:
const maxIndex = fooData.length - 1;
console.log(`Newly pushed item of array:`, fooData[maxIndex]);
However, you can have a key in array. You need to use key to get an item of an array, e.g. fooData['someKeyOfAnArray']:
const fooData = [
{'Finish level 0': 0, test1: 0},
{'Finish level 1': 1, test1: 1},
{'Finish level 2': 2, test1: 2},
];
// To get an object by key from an array
fooData['someKeyOfAnArray'] = {'message': 'This is a message'};
console.log(`// Object by key from an array: `, fooData['someKeyOfAnArray']);

Javascript array of headers to a tree

I'm working with a list of HTML headers (h2,h3,h4,h5,h6).
The picture describes the idea:
[
{
text: 'Some header',
rank: 2, // stays for <h2>
},
{
text: 'Some another header',
rank: 3, // stays for <h3>
},
{
text: 'A header with the same rank',
rank: 3, // stays for <h3>
},
{
text: 'One more subsection header',
rank: 4, // stays for <h4>
}
]
And I'm trying to turn it into a tree:
[
{
text: 'Some header',
children: [
{
text: 'Some another header',
},
{
text: 'A header with the same rank',
children: [
{
text: 'One more subsection header',
}
]
}
]
}
]
Here's my current code:
function list_to_tree(list) {
// We go from the end to the beggining
list = list.reverse();
let node, nextNode, roots = [], i;
for (i = 0; i < list.length; i += 1) {
node = list[i];
nextNode = list[i+1];
// If the next one's rank is greater, the current into the next as a child
if (nextNode !== undefined && node.rank > nextNode.rank) {
list[i+1].children.push(node);
} else {
// Else it's a root
roots.push(node);
}
}
return roots;
};
But it works only for the first h3, but the second h3 will go as a root. Any idea on how to achieve the goal? Thank you.
You could use the level property rank for indicating the nested position in a helper array.
Then iterate the data and build children arrays, if necessary.
function getTree(array) {
var levels = [{}];
array.forEach(function (o) {
levels.length = o.rank;
levels[o.rank - 1].children = levels[o.rank - 1].children || [];
levels[o.rank - 1].children.push(o);
levels[o.rank] = o;
});
return levels[0].children;
}
var data = [{ text: 'Main Heading', rank: 1 }, { text: 'Sub Heading', rank: 2 }, { text: 'Sub Sub Heading', rank: 3 }, { text: 'Sub Heading', rank: 2 }, { text: 'Sub Sub Heading', rank: 3 }, { text: 'Sub Sub Heading', rank: 3 }];
console.log(getTree(data));
.as-console-wrapper { max-height: 100% !important; top: 0; }
This solution will work irrespective of starting rank and also of the order in which the list is given... and it uses the exact data you provided...
var jsonHeaders =
[
{
text: 'Some header',
rank: 2, // stays for <h2>
},
{
text: 'Some another header',
rank: 3, // stays for <h3>
},
{
text: 'A header with the same rank',
rank: 3, // stays for <h3>
},
{
text: 'One more subsection header',
rank: 4, // stays for <h4>
}
];
function list_to_tree(list)
{
var jsonTree = [{}];
list = list.reverse();
for (i = 0, l = list.length; i < l; i++)
{
node = list[i];
var json = {};
json.text = node.text;
json.rank = node.rank;
if(jsonTree[0].rank == undefined)
{
jsonTree[0] = json;
}
else
if(jsonTree[0].rank == json.rank)
{
jsonTree.push(json);
}
else
if(jsonTree[0].rank < json.rank)
{
jsonTree[0] = ranker(jsonTree[0], json);
}
else
if(jsonTree[0].rank > json.rank)
{
var jsonTemp = jsonTree[0];
jsonTree[0] = json;
json = jsonTemp;
jsonTree[0] = ranker(jsonTree[0], json);
}
}
return jsonTree;
}
function ranker(jsonTree, json)
{
if(jsonTree.children == undefined)
{
jsonTree.children = [];
jsonTree.children.push(json);
}
else
if(jsonTree.children[0].rank == json.rank)
{
jsonTree.children.push(json);
}
else
if(jsonTree.children[0].rank < json.rank)
{
jsonTree.children[0] = ranker(jsonTree.children[0], json);
}
else
if(jsonTree.children[0].rank > json.rank)
{
var jsonTemp = jsonTree;
jsonTree = json;
json = jsonTemp;
jsonTree.children[0] = ranker(jsonTree.children[0], json);
}
return jsonTree;
}
var jsonTree = list_to_tree(jsonHeaders);
console.log('jsonArrayTree = ', jsonTree);
Here's the working function in case someone needs it:
function list_to_tree(list) {
list = list.reverse();
let node, currentRank = list[0].rank, i, roots = [];
for (i = 0; i < list.length; i += 1) {
node = list[i];
if (node.rank > currentRank) {
for (let n = i; n < list.length; n += 1) {
if (list[n].rank < node.rank) {
list[n].children.unshift(node);
break;
}
}
} else {
currentRank = node.rank;
roots.push(node);
}
}
return roots.reverse();
};

JavaScript - How to make matching game cards stay flipped over after click

I found this matching game on codepen.io that I am using in corporation with a trivia spinner - thanks #Malky.kid - The idea is once they get to the matching game they have 10 clicks to match as many as they can but the cards MUST stay flipped over.
This is for a project and the odds of winning has to do with chance not skill.
(function(){
var Memory = {
init: function(cards){
this.$game = $(".game");
this.$modal = $(".modal");
this.$overlay = $(".modal-overlay");
this.$restartButton = $("button.restart");
this.cardsArray = $.merge(cards, cards);
this.shuffleCards(this.cardsArray);
this.setup();
},
shuffleCards: function(cardsArray){
this.$cards = $(this.shuffle(this.cardsArray));
},
setup: function(){
this.html = this.buildHTML();
this.$game.html(this.html);
this.$memoryCards = $(".card");
this.binding();
this.paused = false;
this.guess = null;
},
binding: function(){
this.$memoryCards.on("click", this.cardClicked);
this.$restartButton.on("click", $.proxy(this.reset, this));
},
// kinda messy but hey
cardClicked: function(){
var _ = Memory;
var $card = $(this);
if(!_.paused && !$card.find(".inside").hasClass("matched") && !$card.find(".inside").hasClass("picked")){
$card.find(".inside").addClass("picked");
if(!_.guess){
_.guess = $(this).attr("data-id");
} else if(_.guess == $(this).attr("data-id") && !$(this).hasClass("picked")){
$(".picked").addClass("matched");
_.guess = null;
} else {
_.guess = null;
_.paused = true;
setTimeout(function(){
$(".picked").removeClass("picked");
Memory.paused = false;
}, 600);
}
if($(".matched").length == $(".card").length){
_.win();
}
}
},
win: function(){
this.paused = true;
setTimeout(function(){
Memory.showModal();
Memory.$game.fadeOut();
}, 1000);
},
showModal: function(){
this.$overlay.show();
this.$modal.fadeIn("slow");
},
hideModal: function(){
this.$overlay.hide();
this.$modal.hide();
},
reset: function(){
this.hideModal();
this.shuffleCards(this.cardsArray);
this.setup();
this.$game.show("slow");
},
// Fisher--Yates Algorithm -- https://bost.ocks.org/mike/shuffle/
shuffle: function(array){
var counter = array.length, temp, index;
// While there are elements in the array
while (counter > 0) {
// Pick a random index
index = Math.floor(Math.random() * counter);
// Decrease counter by 1
counter--;
// And swap the last element with it
temp = array[counter];
array[counter] = array[index];
array[index] = temp;
}
return array;
},
buildHTML: function(){
var frag = '';
this.$cards.each(function(k, v){
frag += '<div class="card" data-id="'+ v.id +'"><div class="inside">\
<div class="front"><img src="'+ v.img +'"\
alt="'+ v.name +'" /></div>\
<div class="back"><img src="https://s3-us-west-2.amazonaws.com/s.cdpn.io/74196/codepen-logo.png"\
alt="Codepen" /></div></div>\
</div>';
});
return frag;
}
};
var cards = [
{
name: "php",
img: "https://s3-us-west-2.amazonaws.com/s.cdpn.io/74196/php-logo_1.png",
id: 1,
},
{
name: "css3",
img: "https://s3-us-west-2.amazonaws.com/s.cdpn.io/74196/css3-logo.png",
id: 2
},
{
name: "html5",
img: "https://s3-us-west-2.amazonaws.com/s.cdpn.io/74196/html5-logo.png",
id: 3
},
{
name: "jquery",
img: "https://s3-us-west-2.amazonaws.com/s.cdpn.io/74196/jquery-logo.png",
id: 4
},
{
name: "javascript",
img: "https://s3-us-west-2.amazonaws.com/s.cdpn.io/74196/js-logo.png",
id: 5
},
{
name: "node",
img: "https://s3-us-west-2.amazonaws.com/s.cdpn.io/74196/nodejs-logo.png",
id: 6
},
{
name: "photoshop",
img: "https://s3-us-west-2.amazonaws.com/s.cdpn.io/74196/photoshop-logo.png",
id: 7
},
{
name: "python",
img: "https://s3-us-west-2.amazonaws.com/s.cdpn.io/74196/python-logo.png",
id: 8
},
{
name: "rails",
img: "https://s3-us-west-2.amazonaws.com/s.cdpn.io/74196/rails-logo.png",
id: 9
},
{
name: "sass",
img: "https://s3-us-west-2.amazonaws.com/s.cdpn.io/74196/sass-logo.png",
id: 10
},
{
name: "sublime",
img: "https://s3-us-west-2.amazonaws.com/s.cdpn.io/74196/sublime-logo.png",
id: 11
},
{
name: "wordpress",
img: "https://s3-us-west-2.amazonaws.com/s.cdpn.io/74196/wordpress-logo.png",
id: 12
},
];
Memory.init(cards);
})();
see game here
The only difference to this is that the cards stay flipped over - if they match cards they should still show that they are matched - it highlights green for a second. The cards flip back over after you select two cards ONLY if they do not match. If they do match they stay facing up but I need it always facing up. Thanks

Categories

Resources