Change body's background-color on scroll - javascript

I'm trying to achieve this result, you can see it used brilliantly here
http://www.formuswithlove.se
I want the body background to change when I reach a specific div called #about.
Can you please help me?
Thanks so much,
F.

you could do it based on the scroll offset without any jQuery plugins
$(window).scroll(function(){
if($(window).scrollTop()>500){
$('body').addClass('redBg')
}else{
$('body').removeClass('redBg')
}
})
or use something like jQuery.inview
$("#someElement").bind('inview', function(e, isInView) {
if(isInView){
$('body').addClass('redBg')
}else{
$('body').removeClass('redBg')
}
});

Here is a basic example to get you started. It is tested in Firefox, Chrome, and IE 9 & 10 - not tested in Safari though.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<style>
body{
margin:0;
padding:0;
background:white;
}
div{
width:100%;
height:1600px;
}
</style>
<script type="text/javascript">
var section = {
sections: [
'section1',
'section2',
'section3'
],
sectionOffset: {},
sectionBackground: {
'section1': 'rgb(0, 0, 0)',
'section2': 'rgb(132, 132, 132)',
'section3': 'rgb(255, 255, 255)'
},
currentSection: null
}
window.onload = function()
{
var looplen = section.sections.length;
for(var i = 0; i < looplen; ++i)
{
section.sectionOffset[section.sections[i]] = document.getElementById(section.sections[i]).offsetTop;
}
setTimeout("initialBackgroundChange()", 50);
}
window.onscroll = function()
{
tryBackgroundChange();
};
function tryBackgroundChange()
{
var looplen = section.sections.length,
match,
backgroundColor;
for(var i = 0; i < looplen; ++i)
{
if(pageYOffset >= section.sectionOffset[section.sections[i]])
{
match = section.sections[i];
}
}
if(match != section.currentSection)
{
section.currentSection = match;
changeBackground();
}
}
function changeBackground()
{
var cbc, // Current background-color
tbc, // Target backgrounc-color
ri, // Red incrementation
gi, // Green incrementation
bi, // Blue incrementation
rgb, // Temporary color from cbc to tbc
smoothness = 20; // Higher is smoother
cbc = getStyle(document.body, 'background-color');
cbc = cbc.substr(4, cbc.length-5);
cbc = cbc.split(", ");
tbc = section.sectionBackground[section.currentSection];
tbc = tbc.substr(4, tbc.length-5);
tbc = tbc.split(", ");
ri = (tbc[0] - cbc[0]) / smoothness;
gi = (tbc[1] - cbc[1]) / smoothness;
bi = (tbc[2] - cbc[2]) / smoothness;
for(var i = 1; i <= smoothness; ++i)
{
rgb = [
Math.ceil(parseInt(cbc[0]) + (ri * i)),
Math.ceil(parseInt(cbc[1]) + (gi * i)),
Math.ceil(parseInt(cbc[2]) + (bi * i))
];
setTimeout("document.body.style.backgroundColor = 'rgb(" + rgb.join(",") + ")'", i * (240/smoothness));
}
}
function initialBackgroundChange()
{
if(pageYOffset == 0)
tryBackgroundChange();
}
function getStyle(elem, name)
{
if (document.defaultView && document.defaultView.getComputedStyle)
{
name = name.replace(/([A-Z])/g, "-$1");
name = name.toLowerCase();
s = document.defaultView.getComputedStyle(elem, "");
return s && s.getPropertyValue(name);
}
else if (elem.currentStyle)
{
if (/backgroundcolor/i.test(name))
{
return (function (el)
{ // get a rgb based color on IE
var oRG=document.body.createTextRange();
oRG.moveToElementText(el);
var iClr=oRG.queryCommandValue("BackColor");
return "rgb("+(iClr & 0xFF)+","+((iClr & 0xFF00)>>8)+","+
((iClr & 0xFF0000)>>16)+")";
})(elem);
}
return elem.currentStyle[name];
}
else if (elem.style[name])
{
return elem.style[name];
}
else
{
return null;
}
}
</script>
</head>
<body>
<div id="section1"></div>
<div id="section2"></div>
<div id="section3"></div>
</body>
</html>

Related

JQuery/JS script not running in html (works in Codepen)

I'm trying to make a decoding effect and I have found useful stack overflow questions to help with that but I am facing a weird problem. I have an example that I got from a stack overflow link(answer by Flambino) and it works perfectly fine. However, when I put it in my html files and test it locally, it doesn't do anything(no decoding effect). My local code from these html files are below.
html,
head,
body {
width: 100%;
margin: 0;
background-color: rgb(38, 64, 185);
}
* {
font-family: 'Whitney', sans-serif;
box-sizing: border-box;
}
div.mainContent {
margin-top: 100px;
}
span.morphText {
color: white;
}
.code {
color: red;
}
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="css/mainStyles.css">
<link href="https://fonts.googleapis.com/css2?family=Poppins:ital,wght#0,100;0,200;0,300;0,400;0,500;0,600;0,700;0,800;0,900;1,100;1,200;1,300;1,400;1,500;1,600;1,700;1,800;1,900&display=swap" rel="stylesheet">
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<meta charset="utf-8">
<script type="text/javascript">
jQuery.fn.decodeEffect = (function($) {
var defaultOptions = {
duration: 3000,
stepsPerGlyph: 10,
codeGlyphs: "ABCDEFGHIJKLMNOPQRSTUWVXYZ1234567890",
className: "code"
};
// get a random string from the given set,
// or from the 33 - 125 ASCII range
function randomString(set, length) {
console.log("ues");
var string = "",
i, glyph;
for (i = 0; i < length; i++) {
console.log("ues");
glyph = Math.random() * set.length;
string += set[glyph | 0];
}
return string;
}
// this function starts the animation. Basically a closure
// over the relevant vars. It creates a new separate span
// for the code text, and a stepper function that performs
// the animation itself
function animate(element, options) {
var text = element.text(),
span = $("<span/>").addClass(options.className).insertAfter(element),
interval = options.duration / (text.length * options.stepsPerGlyph),
step = 0,
length = 0,
stepper = function() {
if (++step % options.stepsPerGlyph === 0) {
length++;
element.text(text.slice(0, length));
}
if (length <= text.length) {
span.text(randomString(options.codeGlyphs, text.length - length));
setTimeout(stepper, interval);
} else {
span.remove();
}
};
element.text("");
stepper();
}
// Basic jQuery plugin pattern
return function(options) {
options = $.extend({}, defaultOptions, (options || {}));
return this.each(function() {
animate($(this), options);
});
};
}(jQuery));
$("#sometext").decodeEffect();
</script>
</head>
<body>
<div class="mainContent">
<span id="sometext" class="morphText">
Hello, world
</span>
</div>
</body>
</html>
You should wrap your js code in $(document).ready so your code will run as soon as DOM becomes safe for manipilation (check this in documentation - https://api.jquery.com/ready/).
so your code will be next:
$( document ).ready(function() {
jQuery.fn.decodeEffect = (function($) {
var defaultOptions = {
duration: 3000,
stepsPerGlyph: 10,
codeGlyphs: "ABCDEFGHIJKLMNOPQRSTUWVXYZ1234567890",
className: "code"
};
// get a random string from the given set,
// or from the 33 - 125 ASCII range
function randomString(set, length) {
console.log("ues");
var string = "",
i, glyph;
for (i = 0; i < length; i++) {
console.log("ues");
glyph = Math.random() * set.length;
string += set[glyph | 0];
}
return string;
}
// this function starts the animation. Basically a closure
// over the relevant vars. It creates a new separate span
// for the code text, and a stepper function that performs
// the animation itself
function animate(element, options) {
var text = element.text(),
span = $("<span/>").addClass(options.className).insertAfter(element),
interval = options.duration / (text.length * options.stepsPerGlyph),
step = 0,
length = 0,
stepper = function() {
if (++step % options.stepsPerGlyph === 0) {
length++;
element.text(text.slice(0, length));
}
if (length <= text.length) {
span.text(randomString(options.codeGlyphs, text.length - length));
setTimeout(stepper, interval);
} else {
span.remove();
}
};
element.text("");
stepper();
}
// Basic jQuery plugin pattern
return function(options) {
options = $.extend({}, defaultOptions, (options || {}));
return this.each(function() {
animate($(this), options);
});
};
}(jQuery));
$("#sometext").decodeEffect();
});
when you call it in head element $("#sometext") is not yet available, move it to the bottom of body
<body>
<div class="mainContent">
<span id="sometext" class="morphText">
Hello, world
</span>
</div>
<script>
$("#sometext").decodeEffect();
</script>
</body>

javascript random gen nr + loops

I'm trying to make an program where it randomly picks 10 questions out of X questions(got 14 random ones written at the moment) without it picking the same questions again but i've been stuck for 4 hours on this junk.
My problem is with "randomNumbers()" function. This function generates random number (which marks the question respectively) and then checks if the numberArray already has generated number. If it doesnt, the number is supposed to be pushed to array.
I think I figured out the problem to be ## VERSION 1 ## for-loops if/else conditions. Any help ? :(
//edit, is while (true) correct way to handle this?
// dont mind ##VERSION 2## it was the first way I tried solving the problem.
(a lot of console logs to determine the bug :P )
HTML
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8"/>
<title>Testimiskeskkond</title>
<!--<link rel="stylesheet" type="text/css" href="style.css"/> -->
<script src="scripts/jquery-2.1.4.min.js"></script>
<script src="scripts/js.js"></script>
</head>
<body>
<button onclick="startQuiz()">Alusta testimist</button>
<div id="question1"></div>
<div id=questions></div>
</body>
JAVASCRIPT
var amountOfQuestions = 11;
var questionCounter = 0;
var numberArray = new Array();
var questions = new Array();
questions[0] = 'Mitu kassi elab P2rnus?',
questions[1] = 'Mis on kassi nimi?',
questions[2] = 'Mida kass teeb?',
questions[3] = 'Millal kass syndis?',
questions[4] = 'Mitu hammast kassil on?',
questions[5] = 'Mitu kyynt on kassil?',
questions[6] = 'Mitu k6rva on kassil?',
questions[7] = 'Mis v2rvi on kass?',
questions[8] = 'Tooli v2rvus?',
questions[9] = 'Laua suurus?',
questions[10] = 'Lemmik jook?',
questions[11] = 'Lemmik s88k?',
questions[12] = 'Raamatupoe nimi?',
questions[13] = 'Viinapoe nimi?';
function startQuiz() {
var setQuestions = "";
while (questionCounter < amountOfQuestions) {
var random = randomNumbers();
console.log(random + "appppppi");
if (questionCounter < amountOfQuestions) {
setQuestions += questions[random] + "<br>";
questionCounter += 1;
} else {
setQuestions += questions[random];
questionCounter += 1;
}
}
$('#questions').html(setQuestions);
}
function randomNumbers() {
var arrLength = numberArray.length;
while (true) {
console.log(arrLength);
var randomNr = Math.floor(Math.random() * 14);
console.log(randomNr + " tereeeeeeeeee");
/*
######################
########### VERSION 1
######################*/
if (arrLength == 0) {
console.log("pppppppppppp");
numberArray.push(randomNr);
break;
} else if (arrLength == 1) {
console.log("oooooooooooo");
if (numberArray[0] == randomNr) {
console.log("xxxxxxxxxxxxx");
break;
} else {
console.log("rrrrrrrrrrrrrrr");
numberArray.push(randomNr);
break;
}
} else {
for (var i = 0; i < arrLength-1; i++) {
console.log("yyyyyyyyyyyyyyyyyyyy");
if (numberArray[i] == randomNr) {
console.log("qqqqqqqqqqqqqqqqqqqq");
continue;
} else {
console.log("zzzzzzzzzzzzzz")
numberArray.push(randomNr);
break;
}
}
}
/*
######################
########### VERSION 2
######################
if (arrLength > 0) {
console.log("oooooooooooo");
for (var i = 0; i < arrLength; i++) {
console.log("yyyyyyyyyyyyyyyyyyyy");
if (numberArray[i] == randomNr) {
console.log("qqqqqqqqqqqqqqqqqqqq");
continue;
} else {
console.log("zzzzzzzzzzzzzz")
numberArray.push(randomNr);
break;
}
}
} else {
console.log("pppppppppppp");
numberArray.push(randomNr);
break;
} */
}
return randomNr;
}
let selectionCount = 10;
let randomQuestions = [];
while(randomQuestions.length < selectionCount) {
let randomNr = Math.floor(Math.random() * questionList.length);
if(!randomQuestions.includes(randomNr)) {
randomQuestions.push(randomNbr);
}
}

How to show and hide a Javascript output using a Jquery toggle button

I'm having trouble hiding and showing a type of widget that allows a trail of colored 'dust' to be trailed where ever your mouse goes, but I want there to be a way to turn it on and off again (With it starting in the off position). Any Ideas?
<script>
$(document).ready(function(){
$("myFunction()").click(function(){
$("#div1").toggle();
});
});
</script>
<script id="div1" type="text/javascript">
// <![CDATA[
var colour="#ff9000";
var sparkles=120;
/****************************
* Tinkerbell Magic Sparkle *
* (c) 2005 mf2fm web-design *
* http://www.mf2fm.com/rv *
* DON'T EDIT BELOW THIS BOX *
****************************/
var x=ox=400;
var y=oy=300;
var swide=800;
var shigh=600;
var sleft=sdown=0;
var tiny=new Array();
var star=new Array();
var starv=new Array();
var starx=new Array();
var stary=new Array();
var tinyx=new Array();
var tinyy=new Array();
var tinyv=new Array();
window.onload=function() { if (document.getElementById) {
var i, rats, rlef, rdow;
for (var i=0; i<sparkles; i++) {
var rats=createDiv(3, 3);
rats.style.visibility="hidden";
document.body.appendChild(tiny[i]=rats);
starv[i]=0;
tinyv[i]=0;
var rats=createDiv(5, 5);
rats.style.backgroundColor="transparent";
rats.style.visibility="hidden";
var rlef=createDiv(1, 5);
var rdow=createDiv(5, 1);
rats.appendChild(rlef);
rats.appendChild(rdow);
rlef.style.top="2px";
rlef.style.left="0px";
rdow.style.top="0px";
rdow.style.left="2px";
document.body.appendChild(star[i]=rats);
}
set_width();
sparkle();
}}
function sparkle() {
var c;
if (x!=ox || y!=oy) {
ox=x;
oy=y;
for (c=0; c<sparkles; c++) if (!starv[c]) {
star[c].style.left=(starx[c]=x)+"px";
star[c].style.top=(stary[c]=y)+"px";
star[c].style.clip="rect(0px, 5px, 5px, 0px)";
star[c].style.visibility="visible";
starv[c]=50;
break;
}
}
for (c=0; c<sparkles; c++) {
if (starv[c]) update_star(c);
if (tinyv[c]) update_tiny(c);
}
setTimeout("sparkle()", 40);
}
function update_star(i) {
if (--starv[i]==25) star[i].style.clip="rect(1px, 4px, 4px, 1px)";
if (starv[i]) {
stary[i]+=1+Math.random()*3;
if (stary[i]<shigh+sdown) {
star[i].style.top=stary[i]+"px";
starx[i]+=(i%5-2)/5;
star[i].style.left=starx[i]+"px";
}
else {
star[i].style.visibility="hidden";
starv[i]=0;
return;
}
}
else {
tinyv[i]=50;
tiny[i].style.top=(tinyy[i]=stary[i])+"px";
tiny[i].style.left=(tinyx[i]=starx[i])+"px";
tiny[i].style.width="2px";
tiny[i].style.height="2px";
star[i].style.visibility="hidden";
tiny[i].style.visibility="visible"
}
}
function update_tiny(i) {
if (--tinyv[i]==25) {
tiny[i].style.width="1px";
tiny[i].style.height="1px";
}
if (tinyv[i]) {
tinyy[i]+=1+Math.random()*3;
if (tinyy[i]<shigh+sdown) {
tiny[i].style.top=tinyy[i]+"px";
tinyx[i]+=(i%5-2)/5;
tiny[i].style.left=tinyx[i]+"px";
}
else {
tiny[i].style.visibility="hidden";
tinyv[i]=0;
return;
}
}
else tiny[i].style.visibility="hidden";
}
document.onmousemove=mouse;
function mouse(e) {
set_scroll();
y=(e)?e.pageY:event.y+sdown;
x=(e)?e.pageX:event.x+sleft;
}
function set_scroll() {
if (typeof(self.pageYOffset)=="number") {
sdown=self.pageYOffset;
sleft=self.pageXOffset;
}
else if (document.body.scrollTop || document.body.scrollLeft) {
sdown=document.body.scrollTop;
sleft=document.body.scrollLeft;
}
else if (document.documentElement && (document.documentElement.scrollTop || document.documentElement.scrollLeft)) {
sleft=document.documentElement.scrollLeft;
sdown=document.documentElement.scrollTop;
}
else {
sdown=0;
sleft=0;
}
}
window.onresize=set_width;
function set_width() {
if (typeof(self.innerWidth)=="number") {
swide=self.innerWidth;
shigh=self.innerHeight;
}
else if (document.documentElement && document.documentElement.clientWidth) {
swide=document.documentElement.clientWidth;
shigh=document.documentElement.clientHeight;
}
else if (document.body.clientWidth) {
swide=document.body.clientWidth;
shigh=document.body.clientHeight;
}
}
function createDiv(height, width) {
var div=document.createElement("div");
div.style.position="absolute";
div.style.height=height+"px";
div.style.width=width+"px";
div.style.overflow="hidden";
div.style.backgroundColor=colour;
return (div);
}
// ]]>
</script>
<p onclick="myFunction()">Toggle sparks</p>
I cant find when div1 is being declared anywhere. But wouldnt the easiest method be to edit the styling on display to 'none' or 'hidden'

Change Website Background(image) whit Section

I'm Programming a Website and want that it changes it Backgroundimage when i reached a div Box i found it like i have to do it when i want to change the color of it (the Background) but not how it goes with Images, kinda like this
http://www.formuswithlove.se/
but just with Images
here is the code how to do it with colors if its help for someone
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<style>
body{
margin:0;
padding:0;
background:white;
}
div{
width:100%;
height:1600px;
}
</style>
<script type="text/javascript">
var section = {
sections: [
'section1',
'section2',
'section3'
],
sectionOffset: {},
sectionBackground: {
'section1': 'rgb(0, 0, 0)',
'section2': 'rgb(132, 132, 132)',
'section3': 'rgb(255, 255, 255)'
},
currentSection: null
}
window.onload = function()
{
var looplen = section.sections.length;
for(var i = 0; i < looplen; ++i)
{
section.sectionOffset[section.sections[i]] = document.getElementById(section.sections[i]).offsetTop;
}
setTimeout("initialBackgroundChange()", 50);
}
window.onscroll = function()
{
tryBackgroundChange();
};
function tryBackgroundChange()
{
var looplen = section.sections.length,
match,
backgroundColor;
for(var i = 0; i < looplen; ++i)
{
if(pageYOffset >= section.sectionOffset[section.sections[i]])
{
match = section.sections[i];
}
}
if(match != section.currentSection)
{
section.currentSection = match;
changeBackground();
}
}
function changeBackground()
{
var cbc, // Current background-color
tbc, // Target backgrounc-color
ri, // Red incrementation
gi, // Green incrementation
bi, // Blue incrementation
rgb, // Temporary color from cbc to tbc
smoothness = 20; // Higher is smoother
cbc = getStyle(document.body, 'background-color');
cbc = cbc.substr(4, cbc.length-5);
cbc = cbc.split(", ");
tbc = section.sectionBackground[section.currentSection];
tbc = tbc.substr(4, tbc.length-5);
tbc = tbc.split(", ");
ri = (tbc[0] - cbc[0]) / smoothness;
gi = (tbc[1] - cbc[1]) / smoothness;
bi = (tbc[2] - cbc[2]) / smoothness;
for(var i = 1; i <= smoothness; ++i)
{
rgb = [
Math.ceil(parseInt(cbc[0]) + (ri * i)),
Math.ceil(parseInt(cbc[1]) + (gi * i)),
Math.ceil(parseInt(cbc[2]) + (bi * i))
];
setTimeout("document.body.style.backgroundColor = 'rgb(" + rgb.join(",") + ")'", i * (240/smoothness));
}
}
function initialBackgroundChange()
{
if(pageYOffset == 0)
tryBackgroundChange();
}
function getStyle(elem, name)
{
if (document.defaultView && document.defaultView.getComputedStyle)
{
name = name.replace(/([A-Z])/g, "-$1");
name = name.toLowerCase();
s = document.defaultView.getComputedStyle(elem, "");
return s && s.getPropertyValue(name);
}
else if (elem.currentStyle)
{
if (/backgroundcolor/i.test(name))
{
return (function (el)
{ // get a rgb based color on IE
var oRG=document.body.createTextRange();
oRG.moveToElementText(el);
var iClr=oRG.queryCommandValue("BackColor");
return "rgb("+(iClr & 0xFF)+","+((iClr & 0xFF00)>>8)+","+
((iClr & 0xFF0000)>>16)+")";
})(elem);
}
return elem.currentStyle[name];
}
else if (elem.style[name])
{
return elem.style[name];
}
else
{
return null;
}
}
</script>
</head>
<body>
<div id="section1"></div>
<div id="section2"></div>
<div id="section3"></div>
</body>
</html>
try this:
if($(document).scrollTop() == 400){
$('body').css('background','red')
}

Undefined index after running function a few times

So I was trying to create my own Blackjack in javascript for learning purposes and even though the code is overall working, I came across a weird bug.
After some clicks on the Deal html button, which calls the function deal(), I will get either a playerHand[i] undefined or dealerHand[i] undefined error on line 114 or 118, respectively, of the code posted below.
I noticed this also happened if I clicked the button very fast for whatever reason.
I suspected it had something to do with memory optimization so I used the delete command to reset those arrays between game turns, but the error persists.
So, why do my arrays break after some use?
Thanks.
JS:
var deck = [];
var dealerHand = [];
var playerHand = [];
var dscore = 0;
var pscore = 0;
var turn = 0;
function Card(suit, src) {
this.src = src;
this.suit = getSuit(suit);
this.value = getValue(src);
};
function getSuit(suit) {
if (suit == 1) return "Clubs";
if (suit == 2) return "Diamonds";
if (suit == 3) return "Hearts";
if (suit == 4) return "Spades";
};
function getValue(src) {
if (src == 1) return 11;
if (src < 10) return src;
else return 10;
};
function createDeck() {
for (i=1; i<=4; i++) {
for(j=1; j<=13; j++) {
var card = new Card(i, j);
deck.push(card);
};
};
};
function getCard() {
var rand = Math.floor(Math.random()*deck.length);
deck.splice(rand,1);
return deck[rand];
};
function deal() {
if(turn == 0) {
dealerHand.push(getCard());
playerHand.push(getCard());
};
dealerHand.push(getCard());
playerHand.push(getCard());
};
function stand() {
dealerHand.push(getCard());
};
function clearBoard () {
$('#player').html("");
$('#dealer').html("");
};
function resetDeck () {
delete deck;
deck = [];
};
function resetHands () {
delete dealerHand;
delete playerHand;
dealerHand = [];
playerHand = [];
};
function resetScore () {
pscore = 0;
dscore = 0;
};
function isAce (arr) {
for(i=0; i<arr.length; i++) {
if (arr[i].src == 1) return true;
else return false;
};
}
function updateScore() {
resetScore();
if (playerHand.length > 0 && dealerHand.length > 0) {
for(i=0; i<playerHand.length; i++) {
pscore += playerHand[i].value;
};
for(i=0; i<dealerHand.length; i++) {
dscore += dealerHand[i].value;
};
//Regra do Às
if(pscore > 21 && isAce(playerHand)) {
pscore -= 10;
};
if(dscore > 21 && isAce(dealerHand)) {
dscore -= 10;
};
} else {
pscore = 0;
dscore = 0;
};
};
function showScore () {
$('#pscore').html("<p>Player Score: " + pscore + "</p>");
$('#dscore').html("<p>Dealer Score: " + dscore + "</p>");
};
function showCards () {
for(i=0; i<playerHand.length; i++) {
var div = $("<div>");
var img = $("<img>");
img.attr('src', 'img/cards/' + playerHand[i].suit + '/' + playerHand[i].src + '.png');
div.append(img);
$('#player').append(div);
};
for(i=0; i<dealerHand.length; i++) {
var div = $("<div>");
var img = $("<img>");
img.attr('src', 'img/cards/' + dealerHand[i].suit + '/' + dealerHand[i].src + '.png');
div.append(img);
$('#dealer').append(div);
};
};
function cleanUp () {
if (pscore == 21) {
alert("Blackjack!");
newGame();
};
if (pscore > 21) {
alert("Bust!");
newGame();
};
if (dscore == 21) {
alert("You lost!");
newGame();
};
if (dscore > 21) {
alert("You won!");
newGame();
};
};
function newGame () {
turn = 0;
clearBoard();
resetHands();
resetScore();
showScore();
resetDeck();
createDeck();
};
function gameTurn () {
clearBoard();
updateScore();
showCards();
showScore();
cleanUp();
turn++;
};
$(document).ready(function() {
newGame();
$('#deal').on('click', function(){
deal();
gameTurn();
});
$('#stand').on('click', function(){
stand();
gameTurn();
});
});
CSS:
body {
background: url(../img/greenbg.png);
}
.holder {
width:800px;
margin:auto;
}
.clearfix {
clear:both;
}
#pscore, #dscore {
color: white;
margin: 10px;
display: block;
font-size: 1.2rem;
text-shadow: 0 0 5px #000;
}
.container {
width: 600px;
height: 300px;
margin: 10px;
}
div img {
float: left;
margin: 10px;
}
div button {
margin: 10px;
}
HTML:
<html>
<head>
<div class="holder clearfix">
<div id="dscore"><p>Dealer Score: 0</p>
</div>
<div id="dealer" class="container">
</div>
<div id="pscore"><p>Player Score: 0</p>
</div>
<div id="player" class="container">
</div>
<div class="">
<button id="deal">Deal</button>
<button id="stand">Stand</button>
</div>
</div>
</body>
</html>
You have a problem in this function, which may be to blame:
function getCard() {
var rand = Math.floor(Math.random()*deck.length);
deck.splice(rand,1);
return deck[rand];
};
As written, it's removing a card, and then returning the card that now has that position in the deck. If rand was the last element in the array then there is no longer a card in that position, so it'll return undefined.
You should be returning the value of the removed card itself, part of the result of the splice call:
function getCard() {
var rand = Math.floor(Math.random() * deck.length);
var pick = deck.splice(rand, 1);
return pick[0];
};
p.s. it's worth learning modern ES5 utility functions for arrays. For example, your isAce function could be rewritten thus, avoiding the bug where you always return after testing the first element:
function isAce(arr) {
return arr.some(function(n) {
return n === 1;
});
};
or, more cleanly:
function isAce(card) {
return card === 1; // test a single card
};
function holdsAce(hand) {
return hand.some(isAce); // test an array (or hand) of cards
};

Categories