I was working on a jquery clicker game when I added a line of code and suddenly all of my javascript stopped showing up in my html, however I looked through all of my code and it seems all correct.
$(document).ready(function() {
var credits = 0;
var creditstarter = 1;
var hanzounlocked = 0;
var hanzocost = 100;
var numsonicarrow = 0;
var sonicarrowcost = 50;
var numscatterarrow = 0;
var scatterarrowcost = 280;
var numdragonstrike = 0;
var dragonstrikecost = 1000;
var junkratunlocked = 0;
var junkratcost = 4500;
var numtrap = 0;
var trapcost = 5000;
var numconcussionmine = 0;
var concussionminecost = 8000;
var numriptire = 0;
var riptirecost = 16000;
var tracerunlocked = 0;
var tracercost = 50000;
var numblink = 0;
var blinkcost = 15000;
var numrecall = 0;
var recallcost = 40000;
var numpulsebomb = 0;
var pulsebombcost = 100000;
var dvaunlocked = 0;
var dvacost = 400000;
var numdefencematrix = 0;
var defencematrixcost = 100000;
var nummicromissiles = 0;
var micromissilescost = 185000;
var numselfdestruct = 0;
var selfdestructcost = 900000;
$('#openlootbox').on('click', function () {
credits = credits + creditstarter + numdragonstrike + numriptire +
numpulsebomb + numselfdestruct;
});
$('#hanzo').on('click', function (){
hanzounlocked++;
credits -= hanzocost;
});
$('#sonicarrow').on('click', function () {
numsonicarrow++;
credits -= sonicarrowcost;
sonicarrowcost = Math.ceil(sonicarrowcost * 1.2);
});
$('#scatterarrow').on('click', function () {
numscatterarrow++;
credits -= scatterarrowcost;
scatterarrowcost = Math.ceil(scatterarrowcost * 1.2);
});
$('#dragonstrike').on('click', function() {
numdragonstrike++;
credits -= dragonstrikecost;
dragonstrikecost = Math.ceil(dragonstrikecost * 1.2);
});
window.setInterval(function () {
if(hanzounlocked > 0){
$('#hanzo').prop('disabled', true);
$('#scatterarrow').prop('disabled', false);
$('#sonicarrow').prop('disabled', false);
$('#dragonstrike').prop('disabled', false);
}
if(hanzounlocked === 0){
$('#sonicarrow').prop('disabled', true);
$('#hanzo').prop('disabled', false);
$('#dragonstrike').prop('disabled', true);
$('#scatterarrow').prop('disabled', true);
}
if(credits < hanzocost){
$('#hanzo').prop('disabled', true);
}
if(credits < scatterarrowcost){
$('#scatterarrow').prop('disabled', true);
}
if(credits < sonicarrowcost){
$('#sonicarrow').prop('disabled', true);
}
if(credits < dragonstrikecost){
$('#dragonstrike').prop('disabled', true);
}
//Update the text showing how many coins you have and round down
$('#credits').text(Math.floor(credits));
credits += (numsonicarrow * 1 / 100);
//scatterarrow adds 5 per second (5/100 every 10ms)
credits += (numscatterarrow * 5 / 100);
credits += (numconcussionmine * 15 / 100);
credits += (numtrap * 50 / 100);
credits += (numblink * 150 / 100);
credits += (numrecall * 390 / 100);
credits += (numdefencematrix * 1170 / 100);
credits += (nummicriomissiles * 3120 / 100);
});
});
And now the HTML.
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>OW Clicker</title>
<link rel="stylesheet" href="clicker.css" type="text/css">
<script
src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.js">
</script>
<script type="text/javascript" src="newgame.js"></script>
<link rel="stylesheet" type="text/css" href="//fonts.googleapis.com/css?
family=Luckiest+Guy" />
<style type="text/css">
</style>
<body>
<button id="openlootbox"></button>
<button id="hanzo"></button>
<button id="sonicarrow"></button>
<button id="scatterarrow"></button>
<button id="dragonstrike"></button>
</body>
</html>
I know that I may have formatted this question wrong, but I truly do not understand why my buttons are not showing up with my .text functions. Any help or suggestions would be appreciated. Thanks.
nummicromissiles is misspelled as nummicriomissiles. You can open your browser dev tools by pressing f12 to see any errors in the console.
There is no element with an id of credits so $('#credits').text(Math.floor(credits)); does not do anything.
Related
I'm trying to make a small version of "duck hunt" I want to add a scoreboard when every time you hit the duck its +1 and when you miss its -1 but the score cant go lower than 0 (so not -1 for example) when you have tried 20 times the game stops and you will see your score so the hit and miss clicked times will show on the screen. How do I add this to my code so far I have got this:
var duck = document.getElementById('duck');
duck.style.position = 'relative';
var hit = 0;
var miss = 0
var count = 0;
var timing = setInterval(moveduck, 5000);
var button1 = document.getElementById("button1");
var button2 = document.getElementById("button2");
duck.addEventListener('click', moveduck);
function moveduck() {
var top = Math.floor(Math.random() * 750);
var left = Math.floor(Math.random() * 750);
var right = Math.floor(Math.random() * 750);
var bottom = Math.floor(Math.random() * 750);
var vertical = Math.floor(Math.random() * 750);
var horizontal = Math.floor(Math.random() * 750);
duck.style.top = top + 'px';
duck.style.left = left + 'px';
duck.style.right = right + 'px';
duck.style.bottom = bottom + 'px';
duck.style.vertical = vertical + 'px';
duck.style.horizontal = horizontal + 'px';
};
button1.onclick = succesfullhit;
function succesfullhit() {
hit++;
button1.innerHTML = hit;
}
button2.onclick = failedhit;
function failedhit() {
miss--;
button2.innerHTML = miss;
}
#duck { height:50px; }
<!DOCTYPE html>
<html lang="en">
<head>
<title>Duck hunt</title>
<link rel="stylesheet" type="text/css" href="Duckhunt.css">
</head>
<body>
<div class="container">
<input type="image" src="https://www.iconsdb.com/icons/preview/orange/duck-xxl.png" name="duck" id="duck" />
<button id="button1">Hit: </button>
<p></p>
<button id="button2">Miss: </button>
</div>
<script src="Duckhunt.js"></script>
</body>
</html>
I guess you want to do something like this :
i changed the hit and miss and i did only score.
i added event listener to the document, if you hit the duck score++ if not score--
and i display the score.
i added if statement, if score is === -1 game over.
if score === 20 win
Of course you need to do a bit work to make it perfect for your need, this is just for the beginning.
var duck = document.getElementById('duck');
duck.style.position = 'relative';
var score = 0
var timing = setInterval(moveduck, 5000);
var button1 = document.getElementById("button1");
var button2 = document.getElementById("button2");
function moveduck() {
var top = Math.floor(Math.random() * 750);
var left = Math.floor(Math.random() * 750);
var right = Math.floor(Math.random() * 750);
var bottom = Math.floor(Math.random() * 750);
var vertical = Math.floor(Math.random() * 750);
var horizontal = Math.floor(Math.random() * 750);
duck.style.top = top + 'px';
duck.style.left = left + 'px';
duck.style.right = right + 'px';
duck.style.bottom = bottom + 'px';
duck.style.vertical = vertical + 'px';
duck.style.horizontal = horizontal + 'px';
score++
};
document.addEventListener("click", function(e){
if(score === -1){
score = 0
document.getElementById('score').innerHTML = 'Game over'
console.log('game over')
}
if(score === 20){
document.getElementById('score').innerHTML = 'Win'
console.log('Win')
}
if (e.target.id === 'duck'){
moveduck()
document.getElementById('score').innerHTML = score
}else {
score--
document.getElementById('score').innerHTML = score
}
})
#duck { height:50px; }
<!DOCTYPE html>
<html lang="en">
<head>
<title>Duck hunt</title>
<link rel="stylesheet" type="text/css" href="Duckhunt.css">
</head>
<body>
<div id="scoreBoard">Score: <p id="score"></p></div>
<div class="container">
<input type="image" src="https://www.iconsdb.com/icons/preview/orange/duck-xxl.png" name="duck" id="duck" />
</div>
<script src="Duckhunt.js"></script>
</body>
</html>
Here is a start
var duck = document.getElementById('duck');
duck.style.position = 'relative';
var hit = 0;
var miss = 0
var count = 0;
var timing = setInterval(moveduck, 5000);
var button1 = document.getElementById("button1");
var button2 = document.getElementById("button2");
document.body.addEventListener('click', function(e) {
if (hit+miss >= 20) return
const tgt = e.target;
if (tgt.id ==="duck") succesfullhit()
else failedhit();
if (hit+miss === 20) clearInterval(timing)
else moveduck();
});
function moveduck() {
var top = Math.floor(Math.random() * 750);
var left = Math.floor(Math.random() * 750);
var right = Math.floor(Math.random() * 750);
var bottom = Math.floor(Math.random() * 750);
var vertical = Math.floor(Math.random() * 750);
var horizontal = Math.floor(Math.random() * 750);
duck.style.top = top + 'px';
duck.style.left = left + 'px';
duck.style.right = right + 'px';
duck.style.bottom = bottom + 'px';
duck.style.vertical = vertical + 'px';
duck.style.horizontal = horizontal + 'px';
};
function succesfullhit() {
hit++;
button1.innerHTML = hit;
}
function failedhit() {
miss++;
button2.innerHTML = -1*miss;
}
#duck { height:50px; }
<div class="container">
<input type="image" src="https://www.iconsdb.com/icons/preview/orange/duck-xxl.png" name="duck" id="duck" /><br/>
<button id="button1">Hit: </button>
<p></p>
<button id="button2">Miss: </button>
</div>
I'm making a game with Javascript. I have functions for moving left, right, gravity and down. The gravity function makes the player's location go to the bottom of the screen once it goes off the platform (div). When the gravity() function is called when you are moving right (OnButtonDownr()) it stops the move up from working. What I mean is that when I go right and off the platform and then try to go up it doesn't work but I can go up before I go off the platform. When I try to go up (and it doesn't work) it has a weird effect which looks like its position is being set to 0 but moving up at the same time. My code:
HTML (index.htm):
<html>
<head><link rel='stylesheet' href='style.css'></head>
<body>
<div id='level' class='level'>
<div class='start_platform' id='plat1'></div>
<div class='platform' style='
'></div>
</div>
<img id='player' src='img/player.png' style='height:64px;'></img>
<div class='buttons'>
<button id='moveleft' onmousedown="OnButtonDownl (this)" onmouseup="OnButtonUpl (this)"><--</button>
<button id='moveup' onmousedown="OnButtonDownu (this)" onmouseup="OnButtonUpu (this)">^</button>
<button id='moveright' onmousedown="OnButtonDownr (this)" onmouseup="OnButtonUpr (this)">--></button>
</div>
</body>
<script type='text/javascript' src='scripts/move.js'></script>
<script type='text/javascript' src='scripts/gravity.js'></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
</html>
JS (move.js):
//move left
var elem = document.getElementById("player");
function OnButtonDownl (button) {
var posl = parseInt(document.getElementById("player").style.left, 10) || 0;
window.idl = setInterval(framel, 5);
function framel() {
posl--;
elem.style.left = posl + 'px';
gravityCheck();
}}
function OnButtonUpl (button) {
clearInterval(idl);
}
//move right
var elem = document.getElementById("player");
function OnButtonDownr (button) {
var posr = parseInt(document.getElementById("player").style.left, 10) || 0;
window.idr = setInterval(framer, 5);
function framer() {
posr++;
elem.style.left = posr + 'px';
gravityCheck();
}}
function OnButtonUpr (button) {
clearInterval(idr);
}
//move up
var elem = document.getElementById("player");
function OnButtonDownu () {
var posu = parseInt(document.getElementById("player").style.bottom, 10) || 0;
window.idu = setInterval(frameu, 5);
elem.style.bottom = 0;
function frameu() {
gravity = false;
posu++;
elem.style.bottom = posu + 'px';
}}
function OnButtonUpu (button) {
clearInterval(idu);
}
JS (gravity.js):
var gravity = true;
function gravityCheck() {
var player = parseInt(document.getElementById("player").style.left, 10) || 0;
var plat1 = parseInt(document.getElementById("plat1").style.left, 10) || 0;
var width = player - plat1;
var elem = document.getElementById("player");
var pos = parseInt(document.getElementById("player").style.bottom, 10) || 0;
window.id = setInterval(frame, 5);
function frame() {
if(width > 100 && width < 164) {
if(gravity = true) {
pos--;
elem.style.bottom = pos + 'px';
if(elem.style.bottom = 0) {
clear();
}
}
}
}
function clear() {
clearInterval(id);
}}
How do I fix this. Thanks in advance.
You may not be clearing properly. Before setting interval clear any previously set one.
if(window.idl) clearInterval(window.idl);
window.idl = setInterval(framel, 5);
The code below runs as far as alert("click on extra image on the left") then it does nothing upon clicking on the extra image that is added to the left div. Upon clicking on the extra image (id="extraImage") I would like JS to change the color of the "extraImage" element to red. Also, I need to change the sequence in which the code is executed and run the alert("click on extra image on the left") AFTER pictures have been added. Any thoughts greatly appreciated.
<html>
<head> </head>
<body>
<div id="containerLeft">
</div>
<div id="containerRight">
</div>
<script>
var i = 1
var pocetSmilikov = prompt("enter number of smiley faces");
alert("i will add" + pocetSmilikov);
while (i <= pocetSmilikov)
{
insert();
i++;
}
insertExtraToLeft();
function insert() {
var imgDestination = document.getElementById("containerRight");
var imgAdded = document.createElement("img");
imgAdded.src = "smiley.png";
imgDestination.appendChild(imgAdded);
var left = Math.floor((Math.random() * 50) + 1) + "px";
var top = Math.floor((Math.random() * 50) + 1) + "px";
var imagestyle = imgAdded.style;
imagestyle.position = "relative";
imagestyle.top = top;
imagestyle.left = left;
var the_node = document.getElementById("containerRight").lastChild;
var the_clone = the_node.cloneNode(true);
document.getElementById("containerLeft").appendChild(the_clone);
}
function insertExtraToLeft() {
var imgDestinationExtra = document.getElementById("containerLeft");
var imgAddedExtra = document.createElement("img");
imgAddedExtra.src = "smiley.png";
imgAddedExtra.id = "extraImage"
imgDestinationExtra.appendChild(imgAddedExtra);
var left = Math.floor((Math.random() * 50) + 1) + "px";
var top = Math.floor((Math.random() * 50) + 1) + "px";
var imagestyle = imgAddedExtra.style;
imagestyle.position = "relative";
imagestyle.top = top;
imagestyle.left = left;
}
alert("click on extra image on the left");
extraImage.onclick = extraImgFound();
function extraImgFound() {
document.getElementById("extraImage").style.color = "red";
}
</script>
</body>
</html>
extraImage is not defined anywhere. Add imgAddedExtra.onclick = extraImgFound(); in your insertExtraToLeft() function.
Try:
function insertExtraToLeft()
{
var imgDestinationExtra = document.getElementById("containerLeft");
var imgAddedExtra = document.createElement("img");
imgAddedExtra.src = "smiley.png";
imgAddedExtra.id ="extraImage"
imgDestinationExtra.appendChild(imgAddedExtra);
imgAddedExtra.onclick = extraImgFound();
var left = Math.floor((Math.random() * 50) + 1)+"px";
var top = Math.floor((Math.random() * 50) + 1)+"px";
var imagestyle = imgAddedExtra.style;
imagestyle.position = "relative";
imagestyle.top = top;
imagestyle.left = left;
}
My problem is that I'm using the same js file with different name. The function of both files is the same. The first js file is sliding the 5 images (black and white) and the other js is sliding only two images (colored) on different links on the same page.
But both are not working properly means if one slider for black and white image is working then the other one for colored images is not working. please help me.
Js is referenced in a script file named as: coverflow-color.js
var min = 1; //minimum number of image
var max = 3; //maximum number of images
var current = 2; //image number that is at the center of the coverflow
var currPos = 0; //custom attribute that stores current TranslateX position of each image
var newPos = 0; //custom attribute that stores new TranslateX position of each image, i.e after movement
var currAngle = 0; //custom attribute that stores current RotationY angle of each image
var newAngle = 0; //custom attribute that stores new RotationY angle of each image
var gap = 75;
var clickedIndex = 0; //index of the image tapped
var isMouseDown = false; //has the user interacted
var swipeStartX = 0;
var swipeDistanceX = 0;
var diff = 0;
var imageTapStartX = 0;
var imageTapEndX = 0;
var imageTapDistanceX= 0;
var coverFlowContainerElement = null;
var thresholdDistanceSingleSlide = 0; //this measures the distance
window.addEventListener("load",function(){
/* Hide the browser address bar. This will give a native feel to the app */
setTimeout(function() { window.scrollTo(0, 1); }, 20);
/* Get the pointer to the coverflow holder */
coverFlowContainerElement = document.getElementById("coverflow");
moveImagesFromRight(); //help comments are there in the function definition
addEventsToImageHolders(); //help comments are there in the function definition
addEventToCoverflowHolder(); //help comments are there in the function definition
thresholdDistanceSingleSlide = parseInt(300 / max);
disablePageScroll(); //help comments are there in the function definition
},false);
/*
Give the initial thrust to the slides from the right. I have just given it an effect of the images being
thrown into the center from the right.
*/
function moveImagesFromRight()
{
setTimeout(function() {
document.getElementById("fig1").style.webkitTransform = "translateX(-150px) rotateY(30deg)";
document.getElementById("fig2").style.webkitTransform = "translateX(0px) rotateY(0deg) translateZ(200px)";
document.getElementById("fig3").style.webkitTransform = "translateX(150px) rotateY(-30deg)";
}, 150);
}
/* Register touch event listener to the image holders i.e the <div> holding each images */
function addEventsToImageHolders()
{
var imageHolders = coverFlowContainerElement.getElementsByTagName("div");
for(var i=0;i<imageHolders.length;i++)
{
//console.log(imageHolders[i]);
imageHolders[i].addEventListener("touchstart",handleImageTapStart,false);
imageHolders[i].addEventListener("touchend",handleImageTapEnd,false);
}
}
/*
Add touch events to the <div id='coverflow' /> container. So the container registers the finger movements
and acts accordingly
*/
function addEventToCoverflowHolder()
{
coverFlowContainerElement.addEventListener("touchstart", handleFingerSwipeStart, false);
coverFlowContainerElement.addEventListener("touchmove", handleFingerSwipeMove, false);
coverFlowContainerElement.addEventListener("touchend", handleFingerSwipeEnd, false);
}
/* The default behavior of the browser is to scroll when you swipe. This line is to prevent scrolling */
function disablePageScroll() {
document.ontouchmove = function(event) {
event.preventDefault();
}
}
/* Events for the <div id='coverflow'></div> holder */
function handleFingerSwipeStart(event) {
isMouseDown = true;
swipeStartX = event.changedTouches[0].pageX;
event.preventDefault();
}
function handleFingerSwipeMove(event) {
if (isMouseDown) {
swipeDistanceX = parseInt(event.changedTouches[0].pageX - swipeStartX);//
var netDistance = Math.abs(swipeDistanceX);
//console.log("Move: " + swipeDistanceX + " Net distance: " + netDistance); //changedTouches[0].
if (netDistance >= thresholdDistanceSingleSlide) {
//console.log(thresholdDistanceSingleSlide + " covered");
if (swipeDistanceX < 0) {
right();
swipeStartX = event.changedTouches[0].pageX;
}
else {
left();
swipeStartX = event.changedTouches[0].pageX;
}
}
}
}
function handleFingerSwipeEnd(event) {
if (isMouseDown) {
isMouseDown = false;
swipeStartX = 0;
}
}
/*
Events for the <div id="fig"></div> elements where fig starts from 1 to 7. The images are
inside these element
*/
function handleImageTapStart(event) {
imageTapStartX = event.changedTouches[0].pageX;
}
function handleImageTapEnd(event) {
imageTapEndX = event.changedTouches[0].pageX;
imageTapDistanceX = imageTapEndX - imageTapStartX;
var targetObj = event.currentTarget;
if (imageTapDistanceX == 0) {
clickedIndex = parseInt(targetObj.id.slice(3, 4));
if (clickedIndex > current) {
//move right to the clicked index
diff = clickedIndex - current;
for (var i = 1; i <= diff; i++) {
right();
}
}
else if (clickedIndex < current) {
//move left to the clicked index
diff = (current - clickedIndex);
for (var i = 1; i <= diff; i++) {
left();
}
}
else {
//same element is clicked....do nothing
//alert(clickedIndex);
document.getElementById("coverflow").style.display="none";
document.getElementById("fig"+clickedIndex+"_content").style.display="block";
}
}
}
/* Functions - left() & right() for actually moving the images when user interacts*/
/* Move an image from L -> R i.e you are swiping from L->R across the screen */
function left() {
if (current > min) {
current--;
for (var i = 1; i <= max; i++) {
currPos = document.getElementById("fig" + i).getAttribute("cp");
currAngle = document.getElementById("fig" + i).getAttribute("a");
if (currPos == "-150" || currPos == "0") {
newPos = parseInt(currPos) + (gap * 2) * (1);
if (currPos == "0") {
newAngle = -30;
}
else if (currPos = "-150") {
newAngle = 0;
}
else {
}
}
else {
newPos = parseInt(currPos) + (gap) * (1);
newAngle = parseInt(currAngle);
}
if (i == current) {
document.getElementById("fig" + i).style.webkitTransform = "translateX(" + newPos + "px) rotateY(" + newAngle + "deg) translateZ(200px)";
}
else {
document.getElementById("fig" + i).style.webkitTransform = "translateX(" + newPos + "px) rotateY(" + newAngle + "deg)";
}
document.getElementById("fig" + i).setAttribute("cp", newPos);
document.getElementById("fig" + i).setAttribute("a", newAngle);
}
}
}
/* Move an image from R -> L i.e you are swiping from R->L across the screen */
function right() {
if (current < max) {
current++;
for (var i = 1; i <= max; i++) {
currPos = document.getElementById("fig" + i).getAttribute("cp");
currAngle = document.getElementById("fig" + i).getAttribute("a");
if (currPos == "150" || currPos == "0") {
newPos = parseInt(currPos) + (gap * 2) * (-1);
if (currPos == "0") {
newAngle = 30;
}
else if (currPos = "150") {
newAngle = 0;
}
else {
}
}
else {
newPos = parseInt(currPos) + (gap) * (-1);
newAngle = parseInt(currAngle);
}
if (i == current) {
document.getElementById("fig" + i).style.webkitTransform = "translateX(" + newPos + "px) rotateY(" + newAngle + "deg) translateZ(200px)";
}
else {
document.getElementById("fig" + i).style.webkitTransform = "translateX(" + newPos + "px) rotateY(" + newAngle + "deg)";
}
document.getElementById("fig" + i).setAttribute("cp", newPos);
document.getElementById("fig" + i).setAttribute("a", newAngle);
}
}
}
and the other Js is referenced in a script file named as: coverflow-type.js
var min = 1; //minimum number of image
var max = 5; //maximum number of images
var current = 3; //image number that is at the center of the coverflow
var currPos = 0; //custom attribute that stores current TranslateX position of each image
var newPos = 0; //custom attribute that stores new TranslateX position of each image, i.e after movement
var currAngle = 0; //custom attribute that stores current RotationY angle of each image
var newAngle = 0; //custom attribute that stores new RotationY angle of each image
var gap = 75;
var clickedIndex = 0; //index of the image tapped
var isMouseDown = false; //has the user interacted
var swipeStartX = 0;
var swipeDistanceX = 0;
var diff = 0;
var imageTapStartX = 0;
var imageTapEndX = 0;
var imageTapDistanceX= 0;
var coverFlowContainerElement = null;
var thresholdDistanceSingleSlide = 0; //this measures the distance
window.addEventListener("load",function(){
/* Hide the browser address bar. This will give a native feel to the app */
setTimeout(function() { window.scrollTo(0, 1); }, 20);
/* Get the pointer to the coverflow holder */
coverFlowContainerElement = document.getElementById("coverflow");
moveImagesFromRight(); //help comments are there in the function definition
addEventsToImageHolders(); //help comments are there in the function definition
addEventToCoverflowHolder(); //help comments are there in the function definition
thresholdDistanceSingleSlide = parseInt(300 / max);
disablePageScroll(); //help comments are there in the function definition
},false);
/*
Give the initial thrust to the slides from the right. I have just given it an effect of the images being
thrown into the center from the right.
*/
function moveImagesFromRight()
{
setTimeout(function() {
document.getElementById("fig1").style.webkitTransform = "translateX(-225px) rotateY(30deg)";
document.getElementById("fig2").style.webkitTransform = "translateX(-150px) rotateY(30deg)";
document.getElementById("fig3").style.webkitTransform = "translateX(0px) rotateY(0deg) translateZ(200px)";
document.getElementById("fig4").style.webkitTransform = "translateX(150px) rotateY(-30deg)";
document.getElementById("fig5").style.webkitTransform = "translateX(225px) rotateY(-30deg)";
}, 150);
}
/* Register touch event listener to the image holders i.e the <div> holding each images */
function addEventsToImageHolders()
{
var imageHolders = coverFlowContainerElement.getElementsByTagName("div");
for(var i=0;i<imageHolders.length;i++)
{
//console.log(imageHolders[i]);
imageHolders[i].addEventListener("touchstart",handleImageTapStart,false);
imageHolders[i].addEventListener("touchend",handleImageTapEnd,false);
}
}
/*
Add touch events to the <div id='coverflow' /> container. So the container registers the finger movements
and acts accordingly
*/
function addEventToCoverflowHolder()
{
coverFlowContainerElement.addEventListener("touchstart", handleFingerSwipeStart, false);
coverFlowContainerElement.addEventListener("touchmove", handleFingerSwipeMove, false);
coverFlowContainerElement.addEventListener("touchend", handleFingerSwipeEnd, false);
}
/* The default behavior of the browser is to scroll when you swipe. This line is to prevent scrolling */
function disablePageScroll() {
document.ontouchmove = function(event) {
event.preventDefault();
}
}
/* Events for the <div id='coverflow'></div> holder */
function handleFingerSwipeStart(event) {
isMouseDown = true;
swipeStartX = event.changedTouches[0].pageX;
event.preventDefault();
}
function handleFingerSwipeMove(event) {
if (isMouseDown) {
swipeDistanceX = parseInt(event.changedTouches[0].pageX - swipeStartX);//
var netDistance = Math.abs(swipeDistanceX);
//console.log("Move: " + swipeDistanceX + " Net distance: " + netDistance); //changedTouches[0].
if (netDistance >= thresholdDistanceSingleSlide) {
//console.log(thresholdDistanceSingleSlide + " covered");
if (swipeDistanceX < 0) {
right();
swipeStartX = event.changedTouches[0].pageX;
}
else {
left();
swipeStartX = event.changedTouches[0].pageX;
}
}
}
}
function handleFingerSwipeEnd(event) {
if (isMouseDown) {
isMouseDown = false;
swipeStartX = 0;
}
}
/*
Events for the <div id="fig"></div> elements where fig starts from 1 to 7. The images are
inside these element
*/
function handleImageTapStart(event) {
imageTapStartX = event.changedTouches[0].pageX;
}
function handleImageTapEnd(event) {
imageTapEndX = event.changedTouches[0].pageX;
imageTapDistanceX = imageTapEndX - imageTapStartX;
var targetObj = event.currentTarget;
if (imageTapDistanceX == 0) {
clickedIndex = parseInt(targetObj.id.slice(3, 4));
if (clickedIndex > current) {
//move right to the clicked index
diff = clickedIndex - current;
for (var i = 1; i <= diff; i++) {
right();
}
}
else if (clickedIndex < current) {
//move left to the clicked index
diff = (current - clickedIndex);
for (var i = 1; i <= diff; i++) {
left();
}
}
else {
//same element is clicked....do nothing
// alert(clickedIndex);
console.log(targetObj);
var thumbfile=targetObj.getAttribute("rel");
document.getElementById("coverflow").style.display="none";
document.getElementById("content").style.display="block";
var thumbList=show(thumbfile);
document.getElementById("Tlist").innerHTML=thumbList;
window.mySwipe = new Swipe(document.getElementById('slider'),{
callback: function(e, pos) {
var i = bullets.length;
while (i--) {
bullets[i].className = '';
}
bullets[pos].className = 'on';
}
}),
bullets = document.getElementById('position').getElementsByTagName('span');
}
}
}
/* Functions - left() & right() for actually moving the images when user interacts*/
/* Move an image from L -> R i.e you are swiping from L->R across the screen */
function left() {
if (current > min) {
current--;
for (var i = 1; i <= max; i++) {
currPos = document.getElementById("fig" + i).getAttribute("cp");
currAngle = document.getElementById("fig" + i).getAttribute("a");
if (currPos == "-150" || currPos == "0") {
newPos = parseInt(currPos) + (gap * 2) * (1);
if (currPos == "0") {
newAngle = -30;
}
else if (currPos = "-150") {
newAngle = 0;
}
else {
}
}
else {
newPos = parseInt(currPos) + (gap) * (1);
newAngle = parseInt(currAngle);
}
if (i == current) {
document.getElementById("fig" + i).style.webkitTransform = "translateX(" + newPos + "px) rotateY(" + newAngle + "deg) translateZ(200px)";
}
else {
document.getElementById("fig" + i).style.webkitTransform = "translateX(" + newPos + "px) rotateY(" + newAngle + "deg)";
}
document.getElementById("fig" + i).setAttribute("cp", newPos);
document.getElementById("fig" + i).setAttribute("a", newAngle);
}
}
}
/* Move an image from R -> L i.e you are swiping from R->L across the screen */
function right() {
if (current < max) {
current++;
for (var i = 1; i <= max; i++) {
currPos = document.getElementById("fig" + i).getAttribute("cp");
currAngle = document.getElementById("fig" + i).getAttribute("a");
if (currPos == "150" || currPos == "0") {
newPos = parseInt(currPos) + (gap * 2) * (-1);
if (currPos == "0") {
newAngle = 30;
}
else if (currPos = "150") {
newAngle = 0;
}
else {
}
}
else {
newPos = parseInt(currPos) + (gap) * (-1);
newAngle = parseInt(currAngle);
}
if (i == current) {
document.getElementById("fig" + i).style.webkitTransform = "translateX(" + newPos + "px) rotateY(" + newAngle + "deg) translateZ(200px)";
}
else {
document.getElementById("fig" + i).style.webkitTransform = "translateX(" + newPos + "px) rotateY(" + newAngle + "deg)";
}
document.getElementById("fig" + i).setAttribute("cp", newPos);
document.getElementById("fig" + i).setAttribute("a", newAngle);
}
}
}
// show thumbnails functions
//function show(dname){
// if(window.XMLHttpRequest){
// xhttp=new XMLHttpRequest();
// }
// else{
// xhttp=new ActiveXObject(Microsoft.XMLHTTP);
// }
// xhttp.open("GET",dname,false);
// xhttp.send();
// var xmlDoc=xhttp.responseXML;
// var thumblist=xmlDoc.getElementsByTagName("asset");
// //str="";
// str="<li>";
// var image= new Array();
// for(i=0, tc=1; i<thumblist.length;i++){
// var x=thumblist[i].childNodes;
// for(j=0,index=0; j<x.length;j++){
// if(x[j].nodeType==1){
// image[index]=(x[j].firstChild.nodeValue);
// index++;
// }
// x[j]=x[j].nextSibling;
// }
// str+='<div><img src="'+image[0]+'"><span>'+image[1]+'</span></div>';
// // tc<thumblist.length check for the last node
// if(tc%6==0&& tc<thumblist.length){
// str+="</li><li>";
// }
// tc++;
// // str+='<div class="thumbwrapper"><img src="'+image[0]+'">'+image[1]+'</div>';
// //str+='<li><img src="'+image[0]+'"><span>'+image[1]+'</span></li>';
// }
// str+="</li>";
// //alert(str);
// console.log(str);
// return str;
// }
function show(dname){
if(window.XMLHttpRequest){
xhttp=new XMLHttpRequest();
}
else{
xhttp=new ActiveXObject(Microsoft.XMLHTTP);
}
xhttp.open("GET",dname,false);
xhttp.send();
var xmlDoc=xhttp.responseXML;
var thumblist=xmlDoc.getElementsByTagName("asset");
//str="";
str="<li>";
var image= new Array();
for(i=0, tc=1; i<thumblist.length;i++){
// getting the attribute node of every assets
var thumb=thumblist[i].attributes;
str+='<div><img src="'+thumb.getNamedItem("thumbnail").nodeValue+'"><span>'+thumb.getNamedItem("title").nodeValue+'</span></div>';
// (tc<thumblist.length) check for the last node
if(tc%6==0&& tc<thumblist.length){
str+="</li><li>";
}
tc++;
}
str+="</li>";
//alert(str);
console.log(str);
return str;
}
Here's my HTML:
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0,maximum-scale=1.0, user-scalable=no">
<title>GRAAVAA HTML5</title>
<link href="css/bgLandscape.css" rel="stylesheet" type="text/css">
<link href="css/bgLandscape.css" media="screen and (device-width:768px) and (orientation:landscape) or (-webkit-min-device-pixel-ratio: 2)" rel="stylesheet" type="text/css">
<link rel="stylesheet" type="text/css" href="css/login.css" />
<link href="css/coverflow.css" type="text/css" rel="stylesheet"/>
<script type="text/javascript" src="js/modernizr.custom.86080.js"></script>
<script src="js/jquery-1.8.2.min.js"></script>
</head>
<body>
<div class="bg">
<ul class="cb-slideshow">
<li><span></span></li>
<li><span></span></li>
<li><span></span></li>
<li><span></span></li>
<li><span></span></li>
<li><span></span></li>
<li><span></span></li>
</ul>
<div id="formContainer" class="formContainer">
<form id="login" method="post" action="index.html" class="login">
<span id="msg" class="error"></span>
<!-- <input type="email" name="email" id="email" value="Email Address" class="stored" required="required" placeholder="admin#mail.com"/>-->
<input type="email" name="email" id="email" placeholder="Email Address" class="email" style="top:176px;" />
<input type="text" name="name" id="name" placeholder="Full Name" class="stored"/>
<!--<input type="reset" name="reset" value="Skip" />-->
<input type="button" name="skip" id="skip" value="Skip" class="skip" />
<input type="submit" name="submit" value="Save" class="submit" />
</form>
</div>
<!-- Collection By Type -->
<div id="wrapperType" class="collectionTypeWrapper">
<div class="container">
<div id="coverflow">
<div id="fig1" cp="-225" a="30" rel="xml/granite.xml"><img src="collectionType/granite.jpg" /></div>
<div id="fig2" cp="-150" a="30" rel="xml/marble.xml"><img src="collectionType/marble.jpg" /></div>
<div id="fig3" cp="0" a="0" rel="xml/onyx.xml"><img src="collectionType/onyx.jpg" /></div>
<div id="fig4" cp="150" a="-30" rel="xml/travertine.xml"><img src="collectionType/travertine.jpg" /></div>
<div id="fig5" cp="225" a="-30" rel="xml/limitededition.xml"><img src="collectionType/limited.jpg" /></div>
</div>
</div>
</div>
<!-- Collection By Color -->
<div id="wrapperColor" class="collectionColorWrapper">
<div class="container">
<div id="coverflow">
<div id="fig1" cp="-150" a="30" rel="xml/natural.xml"><img src="collectionColor/neutral.jpg" /></div>
<div id="fig2" cp="0" a="0" rel="xml/dark.xml"><img src="collectionColor/dark.jpg" /></div>
<div id="fig3" cp="150" a="-30" rel="xml/vivid.xml"><img src="collectionColor/vivid.jpg" /></div>
</div>
</div>
</div>
<div id="popupicon">
<img id="collectionColor" src="images/1.png" style="margin-left:15px" />
<img id="collectionType" src="images/2.png" style="margin:0px 0px 5px 35px" />
</div>
<div id="bottomImgWrapper" class="bottomImgWrapper"></div>
<div id="bottomImg" class="bottomImg" >
<img src="images/collection.png" class="graavaaImag" id="collection" />
<img src="images/application.png" class="graavaaImag" />
<img src="images/showrooms.png" class="graavaaImag"/>
<img src="images/menuLogo.png" class="graavaaIcon" />
</div>
</div>
<script type="text/javascript">
$("img#collection").click(function(e){
e.preventDefault();
$("#popupicon").fadeToggle("slow");
});
$('#skip').click(function(){
//localStorage.clear();
$("#formContainer").css("display","none");
$("#bottomImgWrapper").css("display","block");
$("#bottomImg").css("display","block");
// setting the skip flag
sessionStorage.setItem('flag','true');
});
$('.login').submit(function() {
var email=$(this).children("#email").val();
var name=$(this).children("#name").val();
var result=validateEmail($(this).children("#email").val());
if(result==false){
//$(this).focus();
$(".error").html('Invalid Email Address');
$(".email").focus();
return false;
}
if(result==true){
$(".error").html('');
localStorage[$("#email").attr('name')] = email;
localStorage[$("#name").attr('name')] = name;
alert('Thank You for saving information');
$("#formContainer").css("display","none");
$(".bottomImgWrapper").css("display","block");
$(".bottomImg").css("display","block");
// Dont submit the form in any condition : as it refresh the page
return false;
//return true;
}
return false;
});
$('#collectionType').click(function(){
$(".collectionTypeWrapper").css("display","block");
$(".collectionColorWrapper").css("display","none");
$("#collectionColor").hide(".collectionTypeWrapper");
$("#collectionColor").show(".collectionTypeWrapper");
//$(".collectionTypeWrapper").fadeIn("slow");
//$(".collectionColorWrapper").fadeOut("slow");
$("#popupicon").fadeToggle("slow");
});
$('#collectionColor').click(function(){
$(".collectionColorWrapper").css("display","block");
$(".collectionTypeWrapper").css("display","none");
//$(".collectionTypeWrapper").fadeOut("slow");
//$(".collectionColorWrapper").fadeIn("slow");
$("#popupicon").fadeToggle("slow");
});
function validateEmail(txtEmail){
var filter = /^((\w+([-+.']\w+)*#\w+([-.]\w+)*\.\w+([-.]\w+)*?)\s*;?\s*)+/;
if(filter.test(txtEmail)){
return true;
}
else{
return false;
}
}
$(document).ready(function(e) {
function init() {
//localStorage.clear();
// show the login form if localstorage not persent
if(!localStorage["email"]){
$("#formContainer").css({"display":"block"});
// hide the bottom images initially
$("#bottomImgWrapper").css("display","none");
$("#bottomImg").css("display","none");
}
// storing the value into application session
if(sessionStorage.flag=="true"){
$("#formContainer").css({"display":"none"});
$("#bottomImgWrapper").css("display","block");
$("#bottomImg").css("display","block");
}
if(localStorage["email"]){
$("#formContainer").css("display","none");
alert('You are already saved as : '+ localStorage["email"]);
}
}
init();
});
</script>
<script type="text/javascript" src="js/coverflow-color.js"></script>
<script type="text/javascript" src="js/coverflow-type.js"></script>
</body>
</html>
It is not going to work because of global variables. The second one overwrites the first one. You also make multiple elements with the same ids. Ids are SINGULAR, you can not have more than one element with the same id.
I'm trying to have a function that does setTimeout, then changes the innerHTML:
<script type="text/javascript">
$(document).ready(function(){
setTimeout(function(){
document.getElementById("middlecolor").innerHTML='new text new text';
}, 1000);
});
</script>
Question: How could I animate the new text that appears, i.e. line by line as opposed to being written all at once?
Thanks for any suggestions!!
Try something like this:
<div id="text">
</div>
$(document).ready(function () {
var interval = setInterval(function () {
$('#text').append('<p style="display: none;">new text</p>');
$('#text p:last').fadeIn('slow');
}, 5000);
});
See the example here
If you want to kill the interval, can be doing this:
clearInterval(interval);
Greatings.
Line-by-line is a bit tricky, but possible.
var ps = document.getElementById("text").children;
var i = 0;
var $p = $(ps[i]);
setTimeout(function newline(){
$p.css("height", function(index, h){
h = parseInt(h);
h += parseInt($p.css("line-height"));
console.log(h, ps[i].scrollHeight);
if (h > ps[i].scrollHeight)
$p = $(ps[++i]);
return h;
});
if (i < ps.length)
setTimeout(newline, 200);
}, 200);
I'd suggest to use a typewriter effect, which is also very likable: http://jsfiddle.net/pZb8W/1/
var ps = document.getElementById("text").children;
var i = 0;
var $p, text;
var speed = 20;
setTimeout(function newchar(){
if (!text) {
$p = $(ps[i++]);
text = $p.text();
$p.empty().show();
}
$p.append(document.createTextNode(text.charAt(0)));
text = text.slice(1);
if (text.length || i < ps.length)
setTimeout(newchar, Math.random()*speed+speed);
}, 3*speed);
Here's a function that would animate in multiple lines of text, one after the other:
<script type="text/javascript">
$(document).ready(function(){
function animateAddText(id, text, delta) {
var lines = text.split("\n");
var lineCntr = 0;
var target = $("#" + id);
function addLine() {
if (lineCntr < lines.length) {
var nextLine = "";
if (lineCntr != 0) {
nextLine = "<br>";
}
nextLine += lines[lineCntr++];
$("<span>" + nextLine + "</span>").hide().appendTo(target).fadeIn(1000);
setTimeout(addLine, delta);
}
}
addLine();
}
var multilineText = "First line\nSecond Line\nThird Line\nFourth Line\nFifth Line";
animateAddText("middlecolor", multilineText, 1000);
});
</script>
And a working demo: http://jsfiddle.net/jfriend00/Gcg5T/