resize the font size of the text box - javascript

I am using the below code to shrink the font size, but it will reduce only once, I want it to reduce every time when i enter a new character.
<input type="text" value="" id="allocatedVisionBudget" onkeydown="resizetext()">
<style>
#allocatedVisionBudget {
width: 10%;
height: 93.3px;
background-color: rgba(255,255,255,0);
border: none;
font-size: 60px;
color: #7e8081;
padding: 0px;
}
</style>
<script>
function resizetext(){
var xy = document.getElementById('allocatedVisionBudget').value;
var x = document.getElementById("allocatedVisionBudget").style.fontSize=60;
//x;
xy;
var i=0;
var y=xy.length;
if(xy.length > 4) {
document.getElementById("allocatedVisionBudget").style.fontSize=x-20;
}
}
</script>

You only have one condition:
if(xy.length > 4) {
so it only resizes when you change the lenght from 4 to 5 or from 5 to 4.
Either add more conditions, or better make the fontSize calculated as a function of the text length:
document.getElementById("allocatedVisionBudget").style.fontSize=f(xy);
function resizetext(e){
var xy = document.getElementById('allocatedVisionBudget').value;
var l=xy.length;
var f = Math.ceil(80/xy.length) || 60;
console.log(e, xy, l, f);
document.getElementById("allocatedVisionBudget").style.fontSize=f + "px";
}
#allocatedVisionBudget {
width: 10%;
height: 93.3px;
background-color: rgba(255,255,255,0);
border: #f00 solid 1px;
font-size: 60px;
color: #7e8081;
padding: 0px;
}
Input: <input type="text" value="" id="allocatedVisionBudget" onkeypress="resizetext(event)" onkeydown="resizetext(event)" onkeyup="resizetext(event)">

a few things you need to do
when you set to input element font size it should wrap as string with px or % etc...
this is example:
var x = document.getElementById("allocatedVisionBudget").style.fontSize
= "60px";
when you use x-20 the x is string so you need to use the parseInt(x) function
here is a demo for your code
HTML:
<input type="text" value="" id="allocatedVisionBudget" onkeydown="resizetext()">
javascript:
window.resizetext = function() {
var xy = document.getElementById('allocatedVisionBudget').value;
var x = document.getElementById("allocatedVisionBudget").style.fontSize = "60px";
var i = 0;
var y = xy.length;
if (xy.length > 4) {
document.getElementById("allocatedVisionBudget").style.fontSize = (parseInt(x) - 20) + "px";
}
};
CSS:
#allocatedVisionBudget {
width: 100%;
height: 93.3px;
background-color: rgba(255, 255, 255, 0);
font-size: 60px;
color: #7e8081;
padding: 0px;
}

Related

How can I get jQuery code working on touch screen device

I use some jQuery code for my range slider, it works well on PC but not working on a touch device and I don't know how to fix it.
I have tried different ways such as:
_ Use on('touchmove', rangeInputChangeEventHandler); instead of on('input', rangeInputChangeEventHandler); but it still not working
_ Add $('input[type="range"]').on( 'touchstart', rangeInputChangeEventHandler); below $('input[type="range"]').on( 'input', rangeInputChangeEventHandler); line and it's still not working.
Here is my code, it includes Javascript, jQuery, HTML, and CSS to run code:
Javascript
//main function change number of slider when dragging
(function() {
// function to round up number
function lamtronTien(number) {
// set rounded, currentForamt, tienFormat as varibale
var rounded = Math.round(number / 1000000) * 1000000;
var currentFormat = new Intl.NumberFormat("vn-VN");
var tienFormat = currentFormat.format(rounded);
//
return tienFormat;
}
//function to turn number into word
function docSoTien(number) {
// replace "," with ""
number = number.replaceAll(",", "");
// set variable ty and trieu as below
var ty = Math.pow(10, 9);
var trieu = Math.pow(10, 6);
// when number = 0 return 0
if (number === "0") {
return 0;
// else number is larger than ty
} else {
if (number >= ty) {
// set variable as floor of "number" devided by "ty"
var hangTy = Math.floor(number / ty);
// if hangTy is greater than 1 then result
if (hangTy >= 1) {
// set varibales
var hangTrieu = number % ty;
var hangTrieu = Math.floor(hangTrieu / trieu);
if (hangTrieu > 0) {
return (hangTy + " Tỷ " + hangTrieu + " Triệu");
// else
} else {
return (hangTy + " Tỷ");
}
}
} else {
// var hangTrieu = number % ty;
var hangTrieu = Math.floor(number / trieu);
if (hangTrieu > 0) {
return (hangTrieu + " Triệu");
}
}
}
}
// function to apply change when there is a change in number input
function rangeInputChangeEventHandler(e) {
// set attribute name as rangeGroup
var rangeGroup = $(this).attr('name'),
minBtn = $(this).parent().children('.min'),
maxBtn = $(this).parent().children('.max'),
// get value of range_min, range_max
range_min = $(this).parent().children('.range_min'),
range_max = $(this).parent().children('.range_max'),
minVal = parseInt($(minBtn).val()),
maxVal = parseInt($(maxBtn).val()),
origin = e.originalEvent.target.className;
// if origin
if (origin === 'min' && minVal > maxVal - 5) {
$(minBtn).val(maxVal - 5);
}
var minVal = parseInt($(minBtn).val());
$(range_min).html(docSoTien(lamtronTien(minVal)));
// if origin is max and maxVal minus 5 is smaller than minVal
if (origin === 'max' && maxVal - 5 < minVal) {
$(maxBtn).val(5 + minVal);
}
var maxVal = parseInt($(maxBtn).val());
if (docSoTien(lamtronTien(maxVal)) === '3 Tỷ') {
$(range_max).html('> 3 Tỷ');
} else {
// apply to range_max
$(range_max).html(docSoTien(lamtronTien(maxVal)));
};
}
// apply change to input type range
$('input[type="range"]').on('input', rangeInputChangeEventHandler);
})();
/* adjust */
input[type='range'] {
width: 210px;
height: 30px;
padding: 20px;
overflow: hidden;
cursor: pointer;
outline: none;
}
/* adjust */
input[type='range'],
input[type='range']::-webkit-slider-runnable-track,
input[type='range']::-webkit-slider-thumb {
-webkit-appearance: none;
background: none;
}
/* adjust */
input[type='range']::-webkit-slider-runnable-track {
width: 300px;
height: 1px;
background: #003D7C;
}
/* adjust */
input[type='range']:nth-child(2)::-webkit-slider-runnable-track {
background: none;
}
/* adjust */
input[type='range']::-webkit-slider-thumb {
position: relative;
height: 15px;
width: 15px;
margin-top: -7px;
background: #fff;
border: 1px solid #003D7C;
border-radius: 25px;
z-index: 1;
}
/* adjust */
input[type='range']:nth-child(1)::-webkit-slider-thumb {
z-index: 2;
}
.rangeslider {
height: 60px;
width: 210px;
display: inline-block;
margin-top: -5px;
margin-left: 20px;
}
/* adjust rangeslider input */
.rangeslider input {
position: absolute;
}
/* adjust rangeslider */
.rangeslider {
position: absolute;
}
/* adjust rangeslider span*/
.rangeslider span {
margin-top: 30px;
left: 0;
}
/* adjust rangeslider right thumb */
.rangeslider .right {
position: relative;
float: right;
margin-right: -70px;
margin-top: -3px;
}
<!-- slider -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!-- slider -->
<div class="slider-group">
<div class="rangeslider">
<input class="min" name="min" type="range" min="0" max="3000000000" value="0" />
<input class="max" name="max" type="range" min="0" max="3000000000" value="3000000000" />
<span class="range_min light left">0</span>
<span class="range_max light right"> > 3 Tỷ</span>
</div>
</div>
and my site: link
Can anyone tell me what is the problem and how to fix it? Thank you!

I am trying to make an object resize based on the distance between the cursor and said object. The Y value I get is always naN

This is my js code, I always get a naN as a result of my Y variable
var elm = document.getElementById("qrcode");
elm.addEventListener("mousemove",getcordd , false)
function getcordd(ev){
var bdns = ev.target.getBoundingClientRect();
var x = ev.clientx - bdns.left;
var y = ev.clienty - bdns.top;
console.log (`${y}`);
}
I got carried away here, but reading that you wanted to know about changing an element's size based on mouse movements, I threw this thing together. Take a look and if you have any questions about it, let me know in a comment. Cheers
var elm = document.getElementById("qrcode");
document.getElementById("mousecapture").addEventListener("mousemove", getcordd, false)
function getcordd(ev) {
var bdns = ev.target.getBoundingClientRect();
// console.log(bdns)
var x = ev.clientX - bdns.left;
var y = ev.clientY - bdns.top;
// console.log(`${y}`, `${x}`, bdns.left, bdns.top);
// resize the div
//console.log(ev.clientX, ev.clientX/bdns.width,ev.clientY, ev.clientY/bdns.height)
let min = 10,
max = 200; // min width/height;
elm.style.width = Math.max(min, Math.min(max, Math.round(max * Math.abs(x / bdns.width)))) + "px";
elm.style.height = Math.max(min, Math.min(max, Math.round(max * Math.abs(y / bdns.height)))) + "px";
}
html,
body,
#container {
width: 100%;
height: 100%;
background: #f0f0f0;
}
#qrcode {
width: 50px;
height: 50px;
background: #f00;
color: #fff;
text-align: center;
display: inline-block;
}
#mousecapture {
width: 100px;
height: 100px;
border: 1px solid #ccc;
background: #fff;
float: right;
}
<div id='container'>
Move the mouse in the white box
<hr>
<div id='mousecapture'></div>
<div id='qrcode'></div>
</div>

how to make a box reach the edge of a bigger box

javascript beginner here! so i'm trying to do a box(that is inside a larger box) move from the top to the edge of the box. Here's the code:
var boxcont = document.getElementById("boxcont");
var boxbtn = document.getElementById("boxbtn");
boxbtn.addEventListener("click", function() {
var loc = 0;
var timebox = setInterval(boxmove, 5);
function boxmove() {
if (loc == 320) {
clearInterval(timebox);
} else {
loc++;
boxcont.style.top = loc + "px";
boxcont.style.left = loc + "px";
}
}
});
#movebox {
width: 300px;
height: 350px;
background-color: grey;
}
#boxcont {
width: 30px;
height: 30px;
background-color: indianred;
position: relative;
}
<div id="movebox">
<div id="boxcont"></div>
</div>
<button id="boxbtn">Move the box</button>
The problem is that the small box doesn't exactly ends up at the edge, it goes more to the right. I tried doing
boxcont.style.left = (loc - 0.5) + "px";
but doesn't work. pretty sure the solution is simple but as a newbie here it's confusing me :p. Oh and i also tried doing ++ to the 0.5 and Number(0.5) so it reads it as a decimal but still doesn't work!
the big gray box is not set to the correct height and width that corresponds with the small red box's movement. You have it going down 1 and to the right 1 every 5 however, your actually going across a rectangle, not a square. set your width and height the same for the gray box and slightly adjust the stopping point to a little bit less.
var boxcont = document.getElementById("boxcont");
var boxbtn = document.getElementById("boxbtn");
boxbtn.addEventListener("click", function() {
var loc = 0;
var timebox = setInterval(boxmove, 5); // every five milliseconds
function boxmove() {
if (loc == 290) {
clearInterval(timebox);
} else {
loc++;
boxcont.style.top = loc + "px";
boxcont.style.left = loc + "px";
}
}
});
#movebox {
width: 300px;
height: 350px;
background-color: grey;
}
#boxcont {
width: 30px;
height: 30px;
background-color: indianred;
position: relative;
}
<div id="movebox" style = "height: 320px; width: 320px">
<div id="boxcont" ></div>
</div>
<button id="boxbtn">Move the box</button>
if (loc == 270) {
instead of
if (loc == 320) {
Gets you there.
300px is the width of the containing div and the moving div is 30px wide so 300-30=270px
var boxcont = document.getElementById("boxcont");
var boxbtn = document.getElementById("boxbtn");
boxbtn.addEventListener("click", function() {
var loc = 0;
var timebox = setInterval(boxmove, 5);
function boxmove() {
if (loc == 270) {
clearInterval(timebox);
} else {
loc++;
boxcont.style.top = loc + "px";
boxcont.style.left = loc + "px";
}
}
});
#movebox {
width: 300px;
height: 350px;
background-color: grey;
}
#boxcont {
width: 30px;
height: 30px;
background-color: indianred;
position: relative;
}
<div id="movebox">
<div id="boxcont"></div>
</div>
<button id="boxbtn">Move the box</button>

Check if element is partially in viewport

I'm trying to determine if an element is partially or fully in the viewport.
I've found this which will determine if an element is fully in view but kept getting confused when trying to determine partial visibility. I don't want to use jQuery.
Basically, the idea is that there will be an element on the page that could be out of view. Once the user scrolls that element into view, even partially, it should trigger an event. I'll handle the event trigger by binding an onscroll event. I just need the detection to work properly.
function isInViewport(element) {
var rect = element.getBoundingClientRect();
var html = document.documentElement;
return (
rect.top >= 0 &&
rect.left >= 0 &&
rect.bottom <= (window.innerHeight || html.clientHeight) &&
rect.right <= (window.innerWidth || html.clientWidth)
);
}
Any help would be greatly appreciated!
Late answer, but about a month ago I wrote a function that does exactly that, it determines how much an element is visible measured in percent in the viewport. Ive tested it in chrome, firefox, ie11, ios on iphone/ipad. The function returns true when X percent (as a number from 0 to 100) of the element is visible. Only determines if the measurements of the element are visible and not if the element is hidden with opacity, visibility etc..
const isElementXPercentInViewport = function(el, percentVisible) {
let
rect = el.getBoundingClientRect(),
windowHeight = (window.innerHeight || document.documentElement.clientHeight);
return !(
Math.floor(100 - (((rect.top >= 0 ? 0 : rect.top) / +-rect.height) * 100)) < percentVisible ||
Math.floor(100 - ((rect.bottom - windowHeight) / rect.height) * 100) < percentVisible
)
};
You need a solution based on element.offsetTop, element.offsetLeft, element.offsetHeight, element.offsetWidth, window.innerWidth and window.innerHeight
(depending on the situation, you might also want to take the scrolling position into consideration)
function isInViewport(element){
if(element.offsetTop<window.innerHeight &&
element.offsetTop>-element.offsetHeight
&& element.offsetLeft>-element.offsetWidth
&& element.offsetLeft<window.innerWidth){
return true;
} else {
return false;
}
}
function test(){
alert(isInViewport(document.getElementById("elem"))?"Yes":"No");
}
#elem{width: 20px; height: 20px; background: red; }
#elem{position: absolute;top: -9px;left: 600px;}
<div id="elem"></div>
<button onclick="test()">Check</button>
function partInViewport(elem) {
let x = elem.getBoundingClientRect().left;
let y = elem.getBoundingClientRect().top;
let ww = Math.max(document.documentElement.clientWidth, window.innerWidth || 0);
let hw = Math.max(document.documentElement.clientHeight, window.innerHeight || 0);
let w = elem.clientWidth;
let h = elem.clientHeight;
return (
(y < hw &&
y + h > 0) &&
(x < ww &&
x + w > 0)
);
}
document.addEventListener("scroll", ()=>{
let el = document.getElementById("test");
if (partInViewport(el)) {
document.getElementById("container").style.backgroundColor = "green";
} else {
document.getElementById("container").style.backgroundColor = "red";
}
});
#test {
height: 200px;
width: 145px;
background-color: grey;
}
#container {
height: 400px;
width: 345px;
transform: translate(400px, 360px);
background-color: red;
display: grid;
align-items: center;
justify-items: center;
}
body {
height: 1500px;
width: 1500px;
}
<div id="container">
<div id="test"></div>
</div>
My example for this code:
https://jsfiddle.net/xqpebwtv/27/
The modern way on how to handle this would be Intersection Observer (IO). With IO you can observe (as the name suggest) elements and trigger actions whenver an alement comes into view. You can set the percentages at which the observer is triggered (e.g. 10% in view, 90% in view, ... )
I really like this example from the linked page, there you have 4 different elements. Each with a different trigger percentage.
let observers = [];
startup = () => {
let wrapper = document.querySelector(".wrapper");
// Options for the observers
let observerOptions = {
root: null,
rootMargin: "0px",
threshold: []
};
// An array of threshold sets for each of the boxes. The
// first box's thresholds are set programmatically
// since there will be so many of them (for each percentage
// point).
let thresholdSets = [
[],
[0.5],
[0.0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0],
[0, 0.25, 0.5, 0.75, 1.0]
];
for (let i = 0; i <= 1.0; i += 0.01) {
thresholdSets[0].push(i);
}
// Add each box, creating a new observer for each
for (let i = 0; i < 4; i++) {
let template = document.querySelector("#boxTemplate").content.cloneNode(true);
let boxID = "box" + (i + 1);
template.querySelector(".sampleBox").id = boxID;
wrapper.appendChild(document.importNode(template, true));
// Set up the observer for this box
observerOptions.threshold = thresholdSets[i];
observers[i] = new IntersectionObserver(intersectionCallback, observerOptions);
observers[i].observe(document.querySelector("#" + boxID));
}
// Scroll to the starting position
document.scrollingElement.scrollTop = wrapper.firstElementChild.getBoundingClientRect().top + window.scrollY;
document.scrollingElement.scrollLeft = 750;
}
intersectionCallback = (entries) => {
entries.forEach((entry) => {
let box = entry.target;
let visiblePct = (Math.floor(entry.intersectionRatio * 100)) + "%";
box.querySelector(".topLeft").innerHTML = visiblePct;
box.querySelector(".topRight").innerHTML = visiblePct;
box.querySelector(".bottomLeft").innerHTML = visiblePct;
box.querySelector(".bottomRight").innerHTML = visiblePct;
});
}
startup();
body {
padding: 0;
margin: 0;
}
svg:not(:root) {
display: block;
}
.playable-code {
background-color: #f4f7f8;
border: none;
border-left: 6px solid #558abb;
border-width: medium medium medium 6px;
color: #4d4e53;
height: 100px;
width: 90%;
padding: 10px 10px 0;
}
.playable-canvas {
border: 1px solid #4d4e53;
border-radius: 2px;
}
.playable-buttons {
text-align: right;
width: 90%;
padding: 5px 10px 5px 26px;
}
.contents {
position: absolute;
width: 700px;
height: 1725px;
}
.wrapper {
position: relative;
top: 600px;
}
.sampleBox {
position: relative;
left: 175px;
width: 150px;
background-color: rgb(245, 170, 140);
border: 2px solid rgb(201, 126, 17);
padding: 4px;
margin-bottom: 6px;
}
#box1 {
height: 300px;
}
#box2 {
height: 175px;
}
#box3 {
height: 350px;
}
#box4 {
height: 100px;
}
.label {
font: 14px "Open Sans", "Arial", sans-serif;
position: absolute;
margin: 0;
background-color: rgba(255, 255, 255, 0.7);
border: 1px solid rgba(0, 0, 0, 0.7);
width: 3em;
height: 18px;
padding: 2px;
text-align: center;
}
.topLeft {
left: 2px;
top: 2px;
}
.topRight {
right: 2px;
top: 2px;
}
.bottomLeft {
bottom: 2px;
left: 2px;
}
.bottomRight {
bottom: 2px;
right: 2px;
}
<template id="boxTemplate">
<div class="sampleBox">
<div class="label topLeft"></div>
<div class="label topRight"></div>
<div class="label bottomLeft"></div>
<div class="label bottomRight"></div>
</div>
</template>
<main>
<div class="contents">
<div class="wrapper">
</div>
</div>
</main>
What your code is saying is that:
The top side of the element must be below the top side of the window,
The left of the element must be to the right of the left side of the window,
The bottom side of the element must be to the top of the bottom side of the window, AND
The right side of the element must be to the left of the right side of the window
What you want:
The top side of the element must be below the top side of the window OR the bottom side of the element must be above the bottom side of the window, AND
The left side of the element must be to the right of the left side of the window OR the right side of the element must be to the left of the right side of the window
Take what you will from that, the code should be simple enough from here.
This should do it, offsets are not needed, since we are comparing client rectangles.
function isPartiallyVisibleInViewport(element, viewport) {
var bound = element.getBoundingClientRect();
var bound2 = viewport.getBoundingClientRect();
return bound.bottom > bound2.top && bound.top < bound2.bottom;
}
This function only checks vertically and must be extended if you also want to check horizontally:
return bound.bottom > bound2.top && bound.top < bound2.bottom && bound.right > bound2.left && bound.left < bound2.right;

Resetting timer and score values to 0 before a new game starts

Im new to this but I've been having some trouble with trying to get my timer and score values back to 0 before a new game of memory starts. The values do reset, but don't show it until that value is affected. For example, the value for the number of matches never goes back to 0, it stays on 10(the max number of pairs) until you find the first match of the next game where it will then turn to 1. Does anybody know how to get the values to show 0 again when a new board is called up instead of just resetting when that value is affected?
I have already set
var turns = 0
var matches = 0
and called in them up as 0 in the function newBoard().
My timer code is:
var c = 0;
var t;
var timer_is_on = 0;
function timedCount() {
document.getElementById('txt').value = c;
c = c+1;
t = setTimeout(timedCount, 1000);
}
function startTimer() {
if (!timer_is_on) {
timer_is_on = 1;
timedCount();
}
}
function stopCount() {
clearTimeout(t);
timer_is_on = 0;
}
function resetTime(){
clearTimeout(t);
timer_is_on = 0;
c = 0
Where I have called up the resetTime() function in the function newBoard().
My full code is:
body{
background:#FFF;
font-family: Cooper Black;
}
h1{
font-family: Cooper Black;
text-align: center;
font-size: 64px;
color: #FF0066;
}
footer{
height: 150px;
background: -webkit-linear-gradient(#99CCFF, #FFF); /* For Safari 5.1 to 6.0 */
background: -o-linear-gradient(#99CCFF, #FFF); /* For Opera 11.1 to 12.0 */
background: -moz-linear-gradient(#99CCFF, #FFF); /* For Firefox 3.6 to 15 */
background: linear-gradient(#99CCFF, #FFF); /* Standard syntax (must be last) */
}
div#memory_board{
background: -webkit-radial-gradient(#FFF, #CC99FF); /* For Safari 5.1 to 6.0 */
background: -o-radial-gradient(#FFF, #CC99FF); /* For Opera 11.1 to 12.0 */
background: -moz-radial-gradient(#FFF, #CC99FF); /* For Firefox 3.6 to 15 */
background: radial-gradient(#FFF, #CC99FF); /* Standard syntax (must be last) */
border:#FF0066 10px ridge;
width:510px;
height:405px;
padding:24px;
}
div#memory_board > div{
background:url(tile_background.png) no-repeat;
border:#000 1px solid;
width:45px;
height:45px;
float:left;
margin:7px;
padding:20px;
cursor:pointer;
}
alert{
background: #FF0066;
}
button{
font-family: Cooper Black;
font-size: 20px;
color: #FF0066;
background: #5CE62E;
border: #C2E0FF 2px outset;
border-radius: 25px;
padding: 10px;
cursor: pointer;
}
input#txt{
background: yellow;
color: #FF0066;
font-family: Times New Roman;
font-size: 84px;
height: 150px;
width: 150px;
border-radius: 100%;
text-align: center;
border: none;
}
input#pause{
font-family: Cooper Black;
font-size: 18px;
color: #FF0066;
background: #C2E0FF;
border: #C2E0FF 2px outset;
border-radius: 25px;
padding: 10px;
cursor: pointer;
margin-top: 10px;
}
div.goes{
text-align: center;
border: #C2E0FF 5px double;
height: 160px;
width: 120px;
margin-top: 48px;
margin-left: 5px;
}
div.matches{
text-align: center;
border: #C2E0FF 5px double;
height: 160px;
width: 120px;
margin-top: 30px;
margin-left: 10px;
}
p{
font-size: 28px;
}
span{
font-family: Times New Roman;
font-size: 84px;
}
.sprite {
width:96px;
height:96px;
position: relative;
margin:15px;
}
.toon{
background: url(explode.png);
}
}
#dialogoverlay{
display: none;
opacity: 0.8;
position: fixed;
top: 0px;
left: 0px;
background: #FFF;
width: 100%;
z-index: 10;
}
#dialogbox{
display: none;
position: fixed;
background: #FF0066;
border-radius:7px;
width:400px;
z-index: 10;
}
#dialogbox > div{ background: #FFF; margin:8px; }
#dialogbox > div > #dialogboxhead{ background: linear-gradient(#99CCFF, #FFF); height: 40px; color: #CCC; }
#dialogbox > div > #dialogboxbody{ background: #FFF; color: #FF0066; font-size: 36px; text-align:center;}
#dialogbox > div > #dialogboxfoot{ background: linear-gradient(#FFF, #99CCFF); padding-bottom: 20px; text-align:center; }
<!DOCTYPE html>
<html>
<head>
<title>Memory Card Game</title>
<meta http-equiv="Content-type" content="text/html; charset=UTF-8" />
<link rel="stylesheet" type="text/css" href="reset.css" />
<link rel="stylesheet" type="text/css" href="text.css" />
<link rel="stylesheet" type="text/css" href="960.css" />
<link rel="stylesheet" type="text/css" href="mystyles.css" />
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script type='text/javascript' src='jquery.animateSprite.js'></script>
<script>
var memory_array = ['A','A','B','B','C','C','D','D','E','E','F','F','G','G','H','H','I','I','J','J'];
var memory_values = [];
var memory_tile_ids = [];
var tiles_flipped = 0;
var turns = 0
var matches = 0
Array.prototype.memory_tile_shuffle = function(){
var i = this.length, j, temp;
while(--i > 0){
j = Math.floor(Math.random() * (i+1));
temp = this[j];
this[j] = this[i];
this[i] = temp;
}
}
function newBoard(){
tiles_flipped = 0;
var output = '';
memory_array.memory_tile_shuffle();
for(var i = 0; i < memory_array.length; i++){
output += '<div id="tile_'+i+'" onclick="memoryFlipTile(this,\''+memory_array[i]+'\')"></div>';
}
document.getElementById('memory_board').innerHTML = output;
//fade in
$(document).ready(function () {
$('#memory_board > div').hide().fadeIn(1500).delay(6000)
});
resetTime();
turns = 0;
matches = 0;
}
function memoryFlipTile(tile,val){
startTimer();
playClick();
if(tile.innerHTML == "" && memory_values.length < 2){
tile.style.background = '#FFF';
tile.innerHTML = '<img src="' + val + '.png"/>';
if(memory_values.length == 0){
memory_values.push(val);
memory_tile_ids.push(tile.id);
} else if(memory_values.length == 1){
memory_values.push(val);
memory_tile_ids.push(tile.id);
if(memory_values[0] == memory_values[1]){
tiles_flipped += 2;
//sound
playMatch();
//animation
//number of clicks
turns = turns + 1;
document.getElementById("Count").innerHTML = turns;
//number of matches
matches = matches + 1;
document.getElementById("matchNumber").innerHTML = matches;
// Clear both arrays
memory_values = [];
memory_tile_ids = [];
// Check to see if the whole board is cleared
if(tiles_flipped == memory_array.length){
playEnd();
Alert.render("Congratulations! Board Cleared");
//resetTime()
//stopCount();
document.getElementById('memory_board').innerHTML = "";
newBoard();
}
} else {
function flipBack(){
// Flip the 2 tiles back over
var tile_1 = document.getElementById(memory_tile_ids[0]);
var tile_2 = document.getElementById(memory_tile_ids[1]);
tile_1.style.background = 'url(tile_background.png) no-repeat';
tile_1.innerHTML = "";
tile_2.style.background = 'url(tile_background.png) no-repeat';
tile_2.innerHTML = "";
//number of clicks
turns = turns + 1;
document.getElementById("Count").innerHTML = turns;
//clickNumber()
// Clear both arrays
memory_values = [];
memory_tile_ids = [];
}
setTimeout(flipBack, 700);
}
}
}
}
//timer
var c = 0;
var t;
var timer_is_on = 0;
function timedCount() {
document.getElementById('txt').value = c;
c = c+1;
t = setTimeout(timedCount, 1000);
}
function startTimer() {
if (!timer_is_on) {
timer_is_on = 1;
timedCount();
}
}
function stopCount() {
clearTimeout(t);
timer_is_on = 0;
}
function resetTime(){
clearTimeout(t);
timer_is_on = 0;
c = 0
}
//sound effects /*sounds from http://www.freesfx.co.uk*/
function playClick(){
var sound=document.getElementById("click");
sound.play();
}
function playMatch(){
var sound=document.getElementById("match_sound");
sound.play();
}
function playEnd(){
var sound=document.getElementById("finished");
sound.play();
}
//custom alert
function CustomAlert(){
this.render = function(dialog){
var winW = window.innerWidth;
var winH = window.innerHeight;
var dialogoverlay = document.getElementById('dialogoverlay');
var dialogbox = document.getElementById('dialogbox');
dialogoverlay.style.display = "block";
dialogoverlay.style.height = winH+"px";
dialogbox.style.left = (winW/2) - (400 * .5)+"px";
dialogbox.style.top = "200px";
dialogbox.style.display = "block";
document.getElementById('dialogboxhead').innerHTML = "";
document.getElementById('dialogboxbody').innerHTML = dialog;
document.getElementById('dialogboxfoot').innerHTML = '<button onclick="Alert.ok()">New Game</button>';
}
this.ok = function(){
document.getElementById('dialogbox').style.display = "none";
document.getElementById('dialogoverlay').style.display = "none";
}
}
var Alert = new CustomAlert();
</script>
<script>//sparkle effect: http://www.rigzsoft.co.uk/how-to-implement-animated-sprite-sheets-on-a-web-page/
$(document).ready(function(){
$("#memory_board").click(function animation(){
$(".toon").animateSprite({
columns: 10,
totalFrames: 50,
duration: 1000,
});
});
});
</script>
</head>
<body>
<audio id = "click" src = "click.mp3" preload = "auto"></audio>
<audio id = "match_sound" src = "match.mp3" preload = "auto"></audio>
<audio id = "finished" src = "finished.wav" preload = "auto"></audio>
<div id = "dialogoverlay"></div>
<div id = "dialogbox">
<div>
<div id = "dialogboxhead"></div>
<div id = "dialogboxbody"></div>
<div id = "dialogboxfoot"></div>
</div>
</div>
<div class = "container_16">
<div id = "banner" class = "grid_16">
<p><br></p>
<h1>Memory</h1>
</div>
<div class = "grid_3">
<input type="text" id="txt" value="0"/>
<p><br></p>
<p><br></p>
<div class = "goes">
<p>Turns <br><span id = "Count">0</span></p>
</div>
</div>
<div class = "grid_10">
<div id="memory_board"></div>
<script>newBoard();</script>
<div style="position: relative; height: 110px;">
<div class="sprite toon"></div>
</div>
</div>
<div class = "grid_3">
<button id = "new_game" onclick="newBoard()">New Game</button>
<input type="button" id="pause" value="Pause Game" onclick="stopCount()">
<p><br></p>
<p><br></p>
<p><br></p>
<div class = "matches">
<p>Matches <br><span id = "matchNumber">0</span></p>
</div>
</div>
</div>
<footer> </footer>
</body>
</html>
Both of the variables you are settings are displayed in HTML span objects.
What seems to be happening is that when you reset the Javascript variable, the value is being changed, but the span object where it is displayed to the user is being left at its previous value until it needs to be updated again.
As far as I can tell, your objects have the ids: matchNumber and Count for the match and turn variables respectively. If this is the case, try changing your code to reset the values to zero in the HTML when the variables are reset to zero.
For example:
// Reset the Javascript Count
var turns = 0
// Reset the HTML object
document.getElementById('Count').innerHTML = 0;
// Reset the Javascript Match Count
var matches = 0
// Reset the HTML object
document.getElementById('matchNumber').innerHTML = 0;
If I failed to explain this well, please comment and I'll try to clarify further.
I am not 100% sure, but you can try replacing your function with this one:
function timedCount() {
if(c>10){
//flipBack();
resetTime();
return;
}
document.getElementById('txt').value = c;
c = c+1;
t = setTimeout(timedCount, 1000);
}

Categories

Resources