How do I add hover effects over buttons on Vue.js 3? - javascript

I am building a calculator to help practice learning Vue.js 3 (I am new to vue). I have got the basic functionalities down but I am trying to figure out how to add a hover animation over the buttons. If possible I am trying to make a different hover color between the buttons in white and buttons in orange. Any help would be appreciated
Code:
<div class="calculator">
<div class="display">{{ current || '0'}}</div>
<div #click="clear" class="btn">C</div>
<div #click="sign" class="btn">+/-</div>
<div #click="percent" class="btn">%</div>
<div #click="divide" class="operator">÷</div>
<div #click="append('7')" class="btn">7</div>
<div #click="append('8')" class="btn">8</div>
<div #click="append('9')" class="btn">9</div>
<div #click="multiply" class="operator">x</div>
<div #click="append('4')" class="btn">4</div>
<div #click="append('5')" class="btn">5</div>
<div #click="append('6')" class="btn">6</div>
<div #click="minus" class="operator">-</div>
<div #click="append('1')" class="btn">1</div>
<div #click="append('2')" class="btn">2</div>
<div #click="append('3')" class="btn">3</div>
<div #click="plus" class="operator">+</div>
<div #click="append('0')" class="zero">0</div>
<div #click="dot" class="btn">.</div>
<div #click="equal" class="operator">=</div>
</div>
</template>
<script>
export default {
data() {
return {
previous: null,
current: '',
operator: null,
operatorClicked: false,
hover: false
}
},
methods: {
clear() {
this.current = '';
},
sign() {
this.current = this.current.charAt(0) === '-' ?
this.current.slice(1) : `-${this.current}`;
},
percent() {
this.current = `${parseFloat(this.current) / 100}`;
},
append(number) {
if (this.operatorClicked) {
this.current = '';
this.operatorClicked = false;
}
this.current = `${this.current}${number}`;
},
dot() {
if (this.current.indexOf('.') === -1) {
this.append('.')
}
},
setPrevious() {
this.previous = this.current;
this.operatorClicked = true;
},
plus() {
this.operator = (a,b) => a + b;
this.setPrevious();
},
minus() {
this.operator = (a,b) => a - b;
this.setPrevious();
},
multiply() {
this.operator = (a,b) => a * b;
this.setPrevious();
},
divide() {
this.operator = (a,b) => a / b;
this.setPrevious();
},
equal() {
this.current = `${this.operator(
parseFloat(this.current),
parseFloat(this.previous)
)}`;
this.previous = null;
}
}
}
</script>
<style scoped>
.calculator {
margin: 0 auto;
width: 400px;
font-size: 40px;
display: grid;
grid-template-columns: repeat(4, 1fr);
grid-auto-rows: minmax(50px, auto);
}
.display {
grid-column: 1 / 5;
background-color: black;
color: white;
}
.zero {
grid-column: 1 / 3;
border: 1px solid black;
}
.btn {
background-color: white;
border: 1px solid black;
}
.operator {
background-color: orange;
color: white;
border: 1px solid black;
}
</style>

You can use the :hover selector pseudo class, no need to involve js/vue for that
ie:
.btn:hover {
background-color: peach;
}
.operator:hover {
background-color: lavender;
}

Yes, just with hover on btns you can achieve this, no need vue or js
.btn:hover {
background-color: #cac8c3;
}
.operator:hover {
background-color: #6f4d00;
}
Exmaple in this codepen https://codepen.io/JavierSR/pen/LYQdjwY

Related

Vue 3 app bug: why is this method executed before any click event occurs?

I am building a quiz app with Vue 3 and Bootstrap 4.
I have this method for checking if the clicked answer is the (same as the) correct answer:
checkAnswer(answer) {
return answer == this.results[this.questionCount]["correct_answer"];
}
It should be executed upon clicking a list item, as seen below:
<li v-for="answer in answers" #click="checkAnswer(answer)" :class="{'text-white bg-success' : checkAnswer(answer)}">{{answer}}</li>
If the clicked answer is correct, the list item should be added the classes text-white bg-success, otherwise it should be added text-white bg-danger.
const quizApp = {
data() {
return {
questionCount: 0,
results: [
{
question: "The book "The Little Prince" was written by...",
correct_answer: "Antoine de Saint-Exupéry",
incorrect_answers: [
"Miguel de Cervantes Saavedra",
"Jane Austen",
"F. Scott Fitzgerald"
]
},
{
question:
"Which novel by John Grisham was conceived on a road trip to Florida while thinking about stolen books with his wife?",
correct_answer: "Camino Island",
incorrect_answers: ["Rogue Lawyer", "Gray Mountain", "The Litigators"]
},
{
question:
"In Terry Pratchett's Discworld novel 'Wyrd Sisters', which of these are not one of the three main witches?",
correct_answer: "Winny Hathersham",
incorrect_answers: [
"Granny Weatherwax",
"Nanny Ogg",
"Magrat Garlick"
]
}
]
};
},
methods: {
nextQuestion() {
if (this.questionCount < this.results.length - 1) {
this.questionCount++;
}
},
prevQuestion() {
if (this.questionCount >= 1) {
this.questionCount--;
}
},
checkAnswer(answer) {
// check if the clicked anwser is equal to the correct answer
return answer == this.results[this.questionCount]["correct_answer"];
},
shuffle(arr) {
var len = arr.length;
var d = len;
var array = [];
var k, i;
for (i = 0; i < d; i++) {
k = Math.floor(Math.random() * len);
array.push(arr[k]);
arr.splice(k, 1);
len = arr.length;
}
for (i = 0; i < d; i++) {
arr[i] = array[i];
}
return arr;
}
},
computed: {
answers() {
let incorrectAnswers = this.results[this.questionCount][
"incorrect_answers"
];
let correctAnswer = this.results[this.questionCount]["correct_answer"];
// return all answers, shuffled
return this.shuffle(incorrectAnswers.concat(correctAnswer));
}
}
};
Vue.createApp(quizApp).mount("#quiz_app");
#quiz_app {
height: 100vh;
}
.container {
flex: 1;
}
.quetions .card-header {
padding-top: 1.25rem;
padding-bottom: 1.25rem;
}
.quetions .card-footer {
padding-top: 0.7rem;
padding-bottom: 0.7rem;
}
.answers li {
cursor: pointer;
display: block;
padding: 7px 15px;
margin-bottom: 5px;
border-radius: 6px;
border: 1px solid rgba(0, 0, 0, 0.1);
background: #fff;
}
.answers li:last-child {
margin-bottom: 0;
}
.answers li:hover {
background: #fafafa;
}
.pager {
list-style-type: none;
margin: 0;
padding: 0;
display: flex;
justify-content: space-between;
}
.pager li > a {
display: inline-block;
padding: 5px 10px;
text-align: center;
width: 100px;
background-color: #fff;
border: 1px solid rgba(0, 0, 0, 0.1);
border-radius: 999px;
text-decoration: none !important;
color: #fff;
}
.pager li > a.disabled {
pointer-events: none;
background-color: #9d9d9d !important;
}
.logo {
width: 30px;
}
.nav-item {
width: 100%;
}
.card {
width: 100%;
}
#media (min-width: 768px) {
.nav-item {
width: auto;
}
.card {
width: 67%;
}
}
#media (min-width: 992px) {
.card {
width: 50%;
}
}
<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.4.1/css/bootstrap.min.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>
<script src="https://unpkg.com/vue#next"></script>
<div id="quiz_app" class="container quetions d-flex align-items-center justify-content-center my-3">
<div v-if="results.length" class="card shadow-sm">
<div class="card-header bg-light h6">
{{results[questionCount]['question']}}
</div>
<div class="card-body">
<ul class="answers list-unstyled m-0">
<li v-for="answer in answers" #click="checkAnswer(answer)" :class="{'text-white bg-success' : checkAnswer(answer)}">{{answer}}</li>
</ul>
</div>
<div class="card-footer bg-white">
<ul class="pager">
<li>Previous</li>
<li class="d-flex align-items-center text-secondary font-weight-bold small">Question {{questionCount + 1}} of {{results.length}}</li>
<li>Next</li>
</ul>
</div>
</div>
</div>
The problem
To my surprise, the checkAnswer(answer) method is executed before (and in the absence of) any click.
Question
What am I doing wrong?
UPDATED
checkAnswer() is invoked immediately if used outside a handler.
maybe this will help, when checkAnswer() is called, store the selected answer selectedAnswer and check if answer is correct isCorrect, and use these 2 states to compare the looped answers.
<li
v-for="answer in answers"
:key="answer"
#click="checkAnswer(answer)"
:class="{
'text-white bg-success' : (selectedAnswer === answer && isCorrect),
'text-white bg-danger' : (selectedAnswer === answer && !isCorrect)
}"
>
{{answer}}
</li>
data() {
return {
isCorrect: false,
selectedAnswer: ''
...
}
},
methods: {
checkAnswer(answer) {
// check if the clicked anwser is equal to the correct answer
this.selectedAnswer = answer
if (answer == this.results[this.questionCount]["correct_answer"]) {
this.isCorrect = true
} else {
this.isCorrect = false
}
},
}
https://jsfiddle.net/renzivan15/fw10q5og/12/
This is executing it before the click:
:class="{'text-white bg-success' : checkAnswer(answer)}".
You'll need to keep the state in a variable for each answer and update it within the method.
And as a side node, it is recommended to use :key for looped elements.
The issue is that the checkAnswer is referenced in the html template so it will execute immediately on render. You might want to try instead setting the class to some computed property instead of the function.
<li v-for="answer in answers" #click="checkAnswer(answer)" :class="{'text-white bg-success' : checkAnswer(answer)}">{{answer}}</li>

JavaScript - How can I access the siblings of an event.currentTarget?

I created a basic voting system for a comment ratings bar. I'm trying to access the previous Sibling Element to update the votes but it's not working properly. IAre you're supposed to use event.currentTarget or event.target? Where did I go wrong? Thank you.
https://jsfiddle.net/donfontaine12/bm9njcLt/46/#&togetherjs=qocecyJqyy
HTML
<div id="comment_ratings_bar">
<div id="comment_rating_sign">+</div>
<div id="comment_rating_num">0</div>
<div id="comment_rating_percentage">[100.00%] </div>
<div class="green_up_arrow"></div>
<div class="red_down_arrow"></div>
</div>
<div id="comment_ratings_bar">
<div id="comment_rating_sign">+</div>
<div id="comment_rating_num">0</div>
<div id="comment_rating_percentage">[100.00%] </div>
<div class="green_up_arrow"></div>
<div class="red_down_arrow"></div>
</div>
<div id="comment_ratings_bar">
<div id="comment_rating_sign">+</div>
<div id="comment_rating_num">0</div>
<div id="comment_rating_percentage">[100.00%] </div>
<div class="green_up_arrow"></div>
<div class="red_down_arrow"></div>
</div>
<div id="comment_ratings_bar">
<div id="comment_rating_sign">+</div>
<div id="comment_rating_num">0</div>
<div id="comment_rating_percentage">[100.00%] </div>
<div class="green_up_arrow"></div>
<div class="red_down_arrow"></div>
</div>
CSS
#comment_ratings_bar {
width: 30%;
margin: 0px 20px;
padding: 0px 20px;
font-size: 110%;
font-weight: bolder;
font-family: 'B612 Mono', monospace;
color: lime;
background-color: black;
border: 0px solid black;
display: flex;
flex-direction: row;
justify-content: center;
}
.green_up_arrow {
display: flex;
flex-direction: row;
width: 0;
height: 0;
border-left: 5px solid transparent;
border-right: 5px solid transparent;
border-bottom: 10px solid lime;
cursor: pointer;
margin: 0em 0.25em;
}
.red_down_arrow {
display: flex;
flex-direction: row;
width: 0;
height: 0;
border-left: 5px solid transparent;
border-right: 5px solid transparent;
border-top: 10px solid red;
cursor: pointer;
margin: 0em 0.25em;
}
JavaScript
window.onload = function() {
let commentUpvotes = 0;
let commentDownvotes = 0;
let totalCommentVotes = commentUpvotes + commentDownvotes;
let commentRatingsBarAll = document.querySelectorAll("#comment_ratings_bar");
for (let c of commentRatingsBarAll) {
c.lastElementChild.previousElementSibling.addEventListener("click", updateCommentVotes);
c.lastElementChild.addEventListener("click", updateCommentVotes);
}
function updateCommentVotes(e) {
let siblings = getSiblings(e);
let sign = siblings[0].textContent;
let number = siblings[1].textContent;
let percentage = siblings[2].textContent;
if (sign && number && percentage) {
let actualNumber = parseFloat(number.replace(/,/g, ''));
if (e.target.className == "green_up_arrow") {
actualNumber++; commentUpvotes++; totalCommentVotes++;
} else {
actualNumber--; commentDownvotes++; totalCommentVotes++;
}
if (actualNumber < 0) { sign.replace("+", ""); }
percentage = "["
+ parseFloat((commentUpvotes / totalCommentVotes) * 100).toFixed(2) +"%]";
number = actualNumber.toLocaleString();
}
}
function getSiblings(element) {
if (element) {
let siblings = [];
let sibling = element.parentNode.firstElementChild;
while(sibling) {
if (sibling.nodeType === 1 && sibling !== element) {
siblings.push(sibling);
sibling = sibling.nextElementSibling;
}
}
return siblings;
}
}
}
Everything's working but inside the updateCommentVotes function, I should have been referencing the actual divs containing the textContent instead of the local variables (sign, number & percentage).
EDIT: It's a partial fix, I need each individual comment bar to refer to its own sign, number and percentage. It seems they all share the same number values. Any tips are appreciated. Although, I believe its because I hard coded the values from siblings. Thank you.
Check the code here: https://jsfiddle.net/donfontaine12/bm9njcLt/46/#
JavaScript
window.onload = function() {
let commentUpvotes = 0;
let commentDownvotes = 0;
let totalCommentVotes = commentUpvotes + commentDownvotes;
let commentRatingsBarAll = document.querySelectorAll("#comment_ratings_bar");
for (let c of commentRatingsBarAll) {
c.lastElementChild.previousElementSibling.addEventListener("click", updateCommentVotes);
c.lastElementChild.addEventListener("click", updateCommentVotes);
}
function updateCommentVotes(e) {
let siblings = getSiblings(e);
let sign = siblings[0].textContent;
let number = siblings[1].textContent;
let percentage = siblings[2].textContent;
if (sign && number && percentage) {
let actualNumber = parseFloat(number.replace(/,/g, ''));
if (e.target.className == "green_up_arrow") {
actualNumber++; commentUpvotes++; totalCommentVotes++;
} else {
actualNumber--; commentDownvotes++; totalCommentVotes++;
}
if (actualNumber < 0) { siblings[0].textContent.replace("+", ""); }
siblings[2].textContent = "["
+ parseFloat((commentUpvotes / totalCommentVotes) * 100).toFixed(2) +"%]";
siblings[1].textContent = actualNumber.toLocaleString();
}
}
function getSiblings(element) {
let siblings = [];
let sibling = element.target.parentNode.firstElementChild;
while(sibling) {
if (sibling.nodeType === 1 && sibling !== element) {
siblings.push(sibling);
sibling = sibling.nextElementSibling;
}
}
return siblings;
}
}

How to show specific message when user presses submit on form?

I am making a javascript form that includes a question being answered with only the number 1-6 (multiple choice) when the user finishes the form, there will be a result showing a chart (ChartJS). I've made that, but I want to show the user below the chart as following. If statement 1 is 1 and If statement 2 is 3 and If statement 3 is 4 then show .... . Here is my code:
/*-----------------------------------------------------
REQUIRE
-------------------------------------------------------*/
var yo = require('yo-yo')
var csjs = require('csjs-inject')
var minixhr = require('minixhr')
var chart = require('chart.js')
/*-----------------------------------------------------
THEME
-------------------------------------------------------*/
var font = 'Montserrat'
var yellow = 'hsla(52,35%,63%,1)'
var white = 'hsla(120,24%,96%,1)'
var violet = 'hsla(329,25%,45%,1)'
var lightBrown = 'hsla(29,21%,67%,1)'
var darkBrown = 'hsla(13,19%,45%,1)'
/*-----------------------------------------------------------------------------
LOADING FONT
-----------------------------------------------------------------------------*/
var links = ['https://fonts.googleapis.com/css?family=Montserrat']
var font = yo`<link href=${links[0]} rel='stylesheet' type='text/css'>`
document.head.appendChild(font)
/*-----------------------------------------------------------------------------
LOADING DATA
-----------------------------------------------------------------------------*/
var questions = [
`
Statement #1:
The next social network I build,
will definitely be for animals.
`,
`
Statement #2:
I really like to do my hobby
`,
`
Statement #3:
My friends say, my middle name should be "Halo".
`,
`
Statement #4:
Rhoma Irama is definitely one of my
favourite artists
`,
`
Statement #5:
I think I could spend all day just
sleeping at my couch
`,
`
Statement #6:
I have a really strong desire to succeed
`
]
var i = 0
var question = questions[i]
var results = []
var answerOptions = [1,2,3,4,5,6]
/*-----------------------------------------------------------------------------
QUIZ
-----------------------------------------------------------------------------*/
function quizComponent () {
var css = csjs`
.quiz {
background-color: ${yellow};
text-align: center;
font-family: 'Montserrat';
padding-bottom: 200px;
}
.welcome {
font-size: 4em;
padding: 50px;
color: ${darkBrown}
}
.question {
font-size: 2em;
color: ${white};
padding: 40px;
margin: 0 5%;
}
.answers {
display: flex;
justify-content: center;
flex-wrap: wrap;
margin: 0 5%;
}
.answer {
background-color: ${violet};
padding: 15px;
margin: 5px;
border: 2px solid ${white};
border-radius: 30%;
}
.answer:hover {
background-color: ${lightBrown};
cursor: pointer;
}
.instruction {
color: ${violet};
font-size: 1em;
margin: 0 15%;
padding: 20px;
}
.results {
background-color: ${white};
text-align: center;
font-family: 'Montserrat', cursive;
padding-bottom: 200px;
}
.resultTitle{
font-size: 4em;
padding: 50px;
color: ${darkBrown}
}
.back {
display: flex;
justify-content: center;
}
.backImg {
height: 30px;
padding: 5px;
}
.backText {
color: ${white};
font-size: 25px;
}
.showChart {
font-size: 2em;
color: ${violet};
margin: 35px;
}
.showChart:hover {
color: ${yellow};
cursor: pointer;
}
.myChart {
width: 300px;
height: 300px;
}
`
function template () {
return yo`
<div class="${css.quiz}">
<div class="${css.welcome}">
IQ Test
</div>
<div class="${css.question}">
${question}
</div>
<div class="${css.answers}">
${answerOptions.map(x=>yo`<div class="${css.answer}" onclick=${nextQuestion(x)}>${x}</div>`)}
</div>
<div class="${css.instruction}">
Choose how strongly do you agree with the statement<br>
(1 - don't agree at all, 6 - completely agree)
</div>
<div class="${css.back}" onclick=${back}>
<img src="http://i.imgur.com/L6kXXEi.png" class="${css.backImg}">
<div class="${css.backText}">Back</div>
</div>
</div>
`
}
var element = template()
document.body.appendChild(element)
return element
function nextQuestion(id) {
return function () {
if (i < (questions.length-1)) {
results[i] = id
i = i+1
question = questions[i]
yo.update(element, template())
} else {
results[i] = id
sendData(results)
yo.update(element, seeResults(results))
}
}
}
function seeResults(data) {
var ctx = yo`<canvas class="${css.myChart}"></canvas>`
return yo`
<div class="${css.results}">
<div class="${css.resultTitle}">
Your Result
</div>
<div class="${css.showChart}" onclick=${function(){createChart(ctx, data)}}>
Click to see the chart
</div>
${ctx}
</div>
`
}
function back() {
if (i > 0) {
i = i-1
question = questions[i]
yo.update(element, template())
}
}
function sendData(results) {
var request = {
url : 'https://cobatest-964fd.firebaseio.com/results.json',
method : 'POST',
data : JSON.stringify(results)
}
minixhr(request)
}
function createChart(ctx, myData) {
minixhr('https://cobatest-964fd.firebaseio.com/results.json', responseHandler)
function responseHandler (data, response, xhr, header) {
var data = JSON.parse(data)
var keys = Object.keys(data)
var arrayOfAnswers = keys.map(x=>data[x])
var stats = arrayOfAnswers.reduce(function(currentResult,answer,i) {
var newResult=currentResult.map((x,count)=>(x*(i+1)+answer[count])/(i+2))
return newResult
}, myData)
var data = {
labels: [
"Caring", "Eager", "Pessimist",
"Hard-headed", "Lazy", "Ambitious"
],
datasets: [
{
label: "My score",
backgroundColor: "rgba(179,181,198,0.2)",
borderColor: "rgba(179,181,198,1)",
pointBackgroundColor: "rgba(179,181,198,1)",
pointBorderColor: "#fff",
pointHoverBackgroundColor: "#fff",
pointHoverBorderColor: "rgba(179,181,198,1)",
data: myData
},
]
}
var myChart = new Chart(ctx, {
type: 'radar',
data: data,
options: {
scale: {
scale: [1,2,3,4,5,6],
ticks: {
beginAtZero: true
}
}
}
})
}
}
}
quizComponent()
Please do help! thank you
Just like onclick is an event, onsubmit is one too.
From w3schools:
in HTML: <element onsubmit="myScript">
in JS: object.onsubmit = function(){myScript};
in JS with eventListener:object.addEventListener("submit", myScript);
You can check it out on w3 schools:
onsubmit event
onsubmit attribute
more

Vue.js Battle - confirm box overrides reset function

i'm currently working through Udemy's Vue.js tutorial. I've reached the section where you are building a battle web app game. After finishing it, I decided to practice my refactoring and came across this bug.
When you click the attack buttons and then the confirm box comes up to ask if you want to play again, it seems to add one extra item in my log array instead of resetting the game fully.
I'm suspecting it is to do with pressing the attack buttons too quickly, and then the confirm box comes up before running an addToLog() and then it runs it afterwards.
Or it could be my bad code. lol
Note that I know that clicking cancel on the confirm box also comes up with bugs too.
index.html
<!DOCTYPE html>
<html>
<head>
<title>Monster Slayer</title>
<script src="https://npmcdn.com/vue/dist/vue.js"></script>
<link rel="stylesheet" href="css/foundation.min.css">
<link rel="stylesheet" href="css/app.css">
</head>
<body>
<div id="app">
<section class="row">
<div class="small-6 columns">
<h1 class="text-center">YOU</h1>
<div class="healthbar">
<div class="healthbar text-center" style="background-color: green; margin: 0; color: white;" :style="{width: playerHealth + '%'}">
{{ playerHealth }}
</div>
</div>
</div>
<div class="small-6 columns">
<h1 class="text-center">BADDY</h1>
<div class="healthbar">
<div class="healthbar text-center" style="background-color: green; margin: 0; color: white;" :style="{width: computerHealth + '%'}">
{{ computerHealth }}
</div>
</div>
</div>
</section>
<section class="row controls" v-if="!isRunning">
<div class="small-12 columns">
<button id="start-game" #click="startGame">START GAME</button>
</div>
</section>
<section class="row controls" v-else>
<div class="small-12 columns">
<button id="attack" #click="attack">ATTACK</button>
<button id="special-attack" #click="specialAttack">SPECIAL ATTACK</button>
<button id="heal" #click="heal">HEAL</button>
<button id="restart" #click="restart">RESTART</button>
</div>
</section>
<section class="row log" v-if="turns.length > 0">
<div class="small-12 columns">
<ul>
<li v-for="turn in turns" :class="{'player-turn': turn.isPlayer, 'monster-turn': !turn.isPlayer}">
{{ turn.text }}
</li>
</ul>
</div>
</section>
</div>
<script src="app.js"></script>
</body>
</html>
css/app.css
.text-center {
text-align: center;
}
.healthbar {
width: 80%;
height: 40px;
background-color: #eee;
margin: auto;
transition: width 500ms;
}
.controls,
.log {
margin-top: 30px;
text-align: center;
padding: 10px;
border: 1px solid #ccc;
box-shadow: 0px 3px 6px #ccc;
}
.turn {
margin-top: 20px;
margin-bottom: 20px;
font-weight: bold;
font-size: 22px;
}
.log ul {
list-style: none;
font-weight: bold;
text-transform: uppercase;
}
.log ul li {
margin: 5px;
}
.log ul .player-turn {
color: blue;
background-color: #e4e8ff;
}
.log ul .monster-turn {
color: red;
background-color: #ffc0c1;
}
button {
font-size: 20px;
background-color: #eee;
padding: 12px;
box-shadow: 0 1px 1px black;
margin: 10px;
}
#start-game {
background-color: #aaffb0;
}
#start-game:hover {
background-color: #76ff7e;
}
#attack {
background-color: #ff7367;
}
#attack:hover {
background-color: #ff3f43;
}
#special-attack {
background-color: #ffaf4f;
}
#special-attack:hover {
background-color: #ff9a2b;
}
#heal {
background-color: #aaffb0;
}
#heal:hover {
background-color: #76ff7e;
}
#restart {
background-color: #ffffff;
}
#restart:hover {
background-color: #c7c7c7;
}
app.js
new Vue({
el: app,
data: {
playerHealth: 100,
computerHealth: 100,
isRunning: false,
turns: [],
},
methods: {
startGame: function() {
this.isRunning = true;
this.playerHealth = 100;
this.computerHealth = 100;
this.clearLog();
},
attackController: function(attacker, maxRange, minRange) {
let receiver = this.setReceiver(attacker);
let damage = 0;
if (attacker === 'player') {
damage = this.randomDamage(maxRange, minRange);
this.computerHealth -= damage;
}
if (attacker === 'computer') {
damage = this.randomDamage(maxRange, minRange);
this.playerHealth -= damage;
}
this.addToLog(attacker, receiver, damage);
if (this.checkWin()) {
return;
}
},
attack: function() {
this.attackController('player', 10, 3);
this.attackController('computer', 10, 3);
},
specialAttack: function() {
this.attackController('player', 30, 5);
this.attackController('computer', 30, 5);
},
heal: function() {
if (this.playerHealth <= 90) {
this.playerHealth += 10;
} else {
this.playerHealth = 100;
}
this.turns.unshift({
isPlayer: true,
text: 'Player heals for ' + 10,
});
},
randomDamage: function(max, min) {
return Math.floor(Math.random() * max, min);
},
checkWin: function() {
if (this.computerHealth <= 0) {
this.alertBox('YOU WIN! New Game?');
} else if (this.playerHealth <= 0) {
this.alertBox('LOSER!!! New Game?');
}
return false;
},
alertBox: function(message) {
if (confirm(message)) {
this.isRunning = false;
this.startGame();
} else {
this.isRunning = false;
}
return true;
},
restart: function() {
this.isRunning = false;
this.startGame();
},
addToLog: function(attacker, receiver, damage) {
this.turns.unshift({
isPlayer: attacker === 'player',
text: attacker + ' hits ' + receiver + ' for ' + damage,
});
},
clearLog: function() {
this.turns = [];
},
setReceiver: function(attacker) {
if (attacker === 'player') {
return 'computer';
} else {
return 'player';
}
},
damageOutput: function(attacker, health) {
if (attacker === 'player') {
damage = this.randomDamage(maxRange, minRange);
this.computerHealth -= damage;
}
},
},
});
Github repo is here if you prefer that. Thanks!
Your attack (and specialAttack) function attacks for both players:
attack: function() {
this.attackController('player', 10, 3);
this.attackController('computer', 10, 3);
},
Currently, it is checking for win at every attackController call. So when the first attacker (player) wins, the game resets AND the second player attacks.
So, my suggestion, move the checkWin out of the attackController into the attack functions:
attack: function() {
this.attackController('player', 10, 3);
this.attackController('computer', 10, 3);
this.checkWin();
},
The same to specialAttack.
Code/JSFiddle: https://jsfiddle.net/acdcjunior/wwc1xnyc/10/
Note, when the player wins, in the code above, the computer will still "strike back", even though the game is over. If you want to halt that, make checkWin return if the game is over:
checkWin: function() {
if (this.computerHealth <= 0) {
this.alertBox('YOU WIN! New Game?');
return true;
} else if (this.playerHealth <= 0) {
this.alertBox('LOSER!!! New Game?');
return true;
}
return false;
},
And add an if to attack (and specialAttack):
attack: function() {
this.attackController('player', 10, 3);
if (this.checkWin()) return;
this.attackController('computer', 10, 3);
this.checkWin();
},
Updated fiddle: https://jsfiddle.net/acdcjunior/wwc1xnyc/13/

Div's not sorting according to classes

I found this article that's supposed to be related to what I was looking for, which is sorting a list by class. However, in my code, it didn't work. So I'm trying to figure out how to solve the problem. I have two classes, "offline" and "none". I want the class "offline" to come at top and the class "none" to appear at bottom under "offline" area. I have one more class in each div's which is "indbox", therefore, I tried to use "getElementsByClassName" but it's not working.
Here's my code from codepen.
$(document).ready(function() {
$(".con-button").click(function(){
var cssObj = {};
cssObj.left = $(this).position().left;
cssObj.width = $(this).outerWidth();
$(".controls .effect").css( cssObj );
if(this.id == "c-all") {
$('.offline').hide();
$('.offline').fadeIn("slow").show();
$('.online').hide();
$('.online').fadeIn("slow").show();
$('.none').fadeIn("slow").show();
} else if (this.id == "c-online") {
$('.offline').hide();
$('.online').hide();
$('.online').fadeIn("slow").show();
$('.none').hide();
} else if (this.id == "c-offline") {
$('.offline').hide();
$('.offline').fadeIn("slow").show();
$('.online').hide();
$('.none').hide();
}
});
$(".con-button").eq(0).trigger("click");
getSteams();
var elem = $('#offline').find('div').sort(sortMe);
function sortMe(a, b) {
return a.getElementsByClassName("offline") < b.getElementsByClassName("none");
}
$('#offline').append(elem);
});
var channels = ["BasicallyIDoWrk", "FreeCodeCamp", "Golgothus", "OgamingSC2", "maatukka", "Vinesauce", "brunofin", "comster404", "esl_csgo"];
var cb = "?client_id=egn4k1eja0yterrcuu411n5e329rd3&callback=?";
function getSteams() {
channels.forEach(function(indchannel) {
//for (var channel in channels) {
//var indchannel = channel;
var streamURL = "https://api.twitch.tv/kraken/streams/" + indchannel + cb;
var channelURL = "https://api.twitch.tv/kraken/channels/" + indchannel + cb;
$.ajax({
url: streamURL,
type: 'GET',
dataType: "jsonp",
data: {
//action: 'query',
format: 'json',
},
headers: {
"Accept": "application/vnd.twitchtv.v5+json",
},
success: function(data) {
var game;
var status;
if(data.stream === null) {
$.getJSON(data._links.channel + "/?client_id=egn4k1eja0yterrcuu411n5e329rd3&callback=?", function(data2) {
if(data2.status == 404) {
game = "The Account doesn't exist";
status = "none";
} else {
game = "Offline";
status = "offline";
}
$("#offline").append('<div class="indbox ' + status + '"><a target="_blank" href="#">'+ indchannel + '<br/>' + game +'</a></div>');
} );
} else {
game = data.stream.game;
status = "online";
$("#online").append('<div class="indbox ' + status + '"><a target="_blank" href="#">'+ indchannel + '<br/>' + game +'</a></div>');
};
}
});
});
}
html, body{
height:100%;
margin: 0;
background-color: #ffffff;
}
.wrapper {
text-align: center;
position: relative;
width: 100%;
height: 100%;
display:block;
}
.container {
width: 75%;
margin: 30px auto 0;
position: relative;
}
.logobox img {
width: 20%;
margin: 0 auto;
}
.controls {
position: relative;
width: 100%;
}
.con-button {
position: relative;
background-color: white;
border: none;
margin: 0.5em 0 0 0;
padding: 0.5em 1em 0.5em 1em;
text-align: center;
color: rgb(100,65,164);
font-size: 20px;
transition: .4s;
}
.con-button:hover {
cursor: pointer;
/*border-bottom: 3px solid rgba(224, 217, 236, 1);*/
}
.con-button:focus {outline: 0;}
.divider hr {
border-top: 1px solid #6441A4;
}
.effect {
position: absolute;
display: block;
left: 0;
bottom: 5px;
height: 2px;
width: 60px;
transition: 0.4s ease-in-out;
/*border-bottom: 3px solid rgba(100, 65, 164, 1);*/
background: #6441A4;
}
.indbox {
width: 100%;
display: block;
margin: 5px 0px;
padding: 8px 0px;
}
.online {
background-color: #98FB98;
}
.offline {
background-color: #ff9999;
}
.none {
background-color: #D3D3D3;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="wrapper">
<div class="container">
<div class="twitchtvarea">
<div class="logobox">
<img src="https://s6.postimg.org/bay7stotd/Twitch_Purple_RGB.png" />
</div>
<div class="twitchbox">
<div class="controls">
<button id="c-all" class="con-button active" type="button">All</button>
<button id="c-online" class="con-button" type="button">Online</button>
<button id="c-offline" class="con-button" type="button">Offline</button>
<div class="effect"></div>
</div>
<div class="divider"><hr></div>
<div id="online"></div>
<div id="offline"></div>
</div>
</div>
</div>
</div>
The code I would like for you to focus on is:
var elem = $('#offline').find('div').sort(sortMe);
function sortMe(a, b) {
return a.getElementsByClassName("offline") < b.getElementsByClassName("none");
}
$('#offline').append(elem);
Please help me fix it.
Looking through your code, I find out that you are using thisSort Function; however, your way of doing is incorrect. In the example, they have:
function compare(a, b) {
if (a is less than b by some ordering criterion) {
return -1;
}
if (a is greater than b by the ordering criterion) {
return 1;
}
// a must be equal to b
return 0;
}
So in order to sort "offline" before "none", your function has to return 1
function sortMe(a, b){
if (a.hasClass("offline")) {
return 1; //if an element has offline, move it above.
} else {
return -1; //if an element doesn't have offline, it means it's none. Move it down.
}
}
You might want to add in the condition to check whether they both have offline class.
Your problem can be solved by using the :
appendTo();
method.
instead of the :
append();
method.
I added two additional divs in your html code and made a small change to your javascript code ant it works !!!
the html goes like this :
<div class="divider"><hr></div>
<div id="online"></div>
<div id="offline">
<div class="notconnected"></div>
<div class="nonexisting"></div>
</div>
</div>
and the javascript was changed here :
if(data2.status == 404) {
game = "The Account doesn't exist";
status = "none";
}
else {
game = "Offline";
status = "offline";
}
if(status==="none"){
$('<div class="indbox ' + status + '" id="'+status+'"><a target="_blank" href="#">'+ indchannel + '<br/>' + game +'</a></div>').appendTo(".nonexisting");}
else{
$('<div class="indbox ' + status + '" id="'+status+'"><a target="_blank" href="#">'+ indchannel + '<br/>' + game +'</a></div>').appendTo(".notconnected");
}
} );
The Documentation for the method is here : appendTo()

Categories