here is my html code:
var picList = ["http://www.acidre.com/dummy/16:9x1080", "http://www.nexusnetsolutions.com/image/product.png", "http://lehmanlaw.mn/wp-content/uploads/2016/03/vga-1.png"];
function nextPic() {
var cur = 0;
var f = 0;
var x = document.getElementById("pics").src;
for (cur = 0; cur < picList.length; cur++) {
if (x == picList[cur]) {
f = 1;
break;
}
}
if (f == 1) {
if (cur < picList.length - 1) {
document.getElementById("pics").src = picList[cur + 1];
}
}
}
function prevPic() {
var cur = 0;
var f = 0;
var x = document.getElementById("pics").src;
for (cur = 0; cur < picList.length; cur++) {
if (x == picList[cur]) {
f = 1;
break;
}
}
if (f == 1) {
if (cur > 0) {
document.getElementById("pics").src = picList[cur - 1];
}
}
}
header {
position: absolute;
display: block;
background: cyan;
height: 150px;
width: 1350px;
box-shadow: 0 4px 8px 0 rgba(0, 0, 0, 0.2), 0 6px 20px 0 rgba(0, 0, 0, 0.19);
}
h1 {
color: white;
position: absoute;
padding-left: 450px;
padding-top: 15px;
font-family: 'Cabin', sans-serif;
font-size: 50px;
font-variant: small-caps;
}
#pics {
margin-top: 170px;
margin-left: 270px;
}
#bnext {
position: absolute;
margin-left: 100px;
margin-top: 400px;
width: 80px;
}
#bprev {
position: absolute;
margin-left: -980px;
margin-top: 400px;
width: 80px;
}
<header>
<h1>Image Showcase</h1>
</header>
<img id="pics" src="http://lehmanlaw.mn/wp-content/uploads/2016/03/vga-1.png" alt="Forms" width="800px" height="500px"></img>
<button id="bnext" type="button" onclick="nextPic()">Next</input>
<button id="bprev" type="button" onclick="prevPic()">Previous</input>
nothing is happening on clicking the next and previous buttons. cant understand why.. would be very helpful if anyone gives a solution
Why would you want to check for the images source?
if (x == picList[cur]) {
f = 1;
break;
}
and I can't see where u changed your image, except on some conditions:
if (cur ...) {
document.getElementById("pics").src = ...;
}
All this are not needed. U only need to switch images based on the array content and add your conditions to safeguard against 'undefined' array index.
Here is a simple working sample code:
<!DOCTYPE html>
<html>
<body>
<header>
<h1>Image Showcase</h1>
</header>
<img id="pics" src="http://lehmanlaw.mn/wp-content/uploads/2016/03/vga-1.png" alt="Forms" width="800px" height="500px"></img>
<button id="bnext" type="button">Next</input>
<button id="bprev" type="button">Previous</input>
<script>
(function(){
var images = ["http://www.w3schools.com/images/w3schoolscom_gray.gif", "none"];
var index = 0;
function prevImage() {
index--;
index = index < 0 ? 0 : index;
return images[index];
}
function nextImage() {
index++;
index = index >= images.length ? images.length - 1 : index;
return images[index];
}
document.querySelector("#bprev").onclick= function() {
document.querySelector("#pics").src = prevImage();
}
document.querySelector("#bnext").onclick= function() {
document.querySelector("#pics").src = nextImage();
}
})();
</script>
</body>
</html>
var picList = ["http://allwebco-templates.com/support/picts/sample-image.jpg",
"http://mfs1.cdnsw.com/fs/cc0/normal/cx0ms-193.jpg",
"https://freethumbs.dreamstime.com/114/big/free_1145336.jpg",
"http://images.all-free-download.com/images/graphicthumb/male_lion_193754.jpg"
];
var currentIndex = 0;
var pic = document.getElementById("pics");
function nextPic() {
pic.src = picList[(currentIndex++) % picList.length];
}
function prevPic() {
if (currentIndex == 0)
currentIndex = picList.length - 1;
else
currentIndex = currentIndex - 1;
pic.src = picList[currentIndex];
}
header {
position: absolute;
display: block;
background: cyan;
height: 150px;
width: 1350px;
box-shadow: 0 4px 8px 0 rgba(0, 0, 0, 0.2), 0 6px 20px 0 rgba(0, 0, 0, 0.19);
}
h1 {
color: white;
position: absoute;
padding-left: 450px;
padding-top: 15px;
font-family: 'Cabin', sans-serif;
font-size: 50px;
font-variant: small-caps;
}
#pics {
margin-top: 170px;
margin-left: 270px;
}
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Image Showcase</title>
<link rel="stylesheet" type="text/css" href="imgShow.css"></link>
<script src="imgShow.js"></script>
</head>
<body>
<header>
<h1>Image Showcase</h1>
</header>
<img id="pics" src="http://allwebco-templates.com/support/picts/sample-image.jpg" alt="Forms" width="300px" height="200px" /></img>
<button id="bnext" type="button" onclick="nextPic()">Next</input>
<button id="bprev" type="button" onclick="prevPic()">Previous</input>
</body>
</html>
The Html for you button is incorrect,change it to .
<button id="bnext" type="button" onclick="nextPic()">Next</button >
<button id="bprev" type="button" onclick="prevPic()">Previous</button>
Here is an example to do this in a slightly different way. One thing is that I removed the invocation back in JS file instead of calling the prevPic() nextPic() inline.
JS
var picList = [
'http://orig10.deviantart.net/78b3/f/2009/025/0/0/0044146485035ccdcc4f99a681af80c6.jpg',
'http://pre15.deviantart.net/39b2/th/pre/i/2012/221/3/3/square_2_by_lilith1995-d5ag32b.jpg',
'http://img15.deviantart.net/4e63/i/2010/188/6/c/fly__fly_away___sqaure_crop_by_tagirocks.jpg',
'http://img13.deviantart.net/036f/i/2016/287/c/3/harley_quinn_by_mz09-dakslb5.jpg',
];
function imageShowCase(list) {
var cur = 0;
var img = document.getElementById('pics');
/* Use controls element to delegate from buttons */
var controls = document.getElementById('controls');
/* Update the image src */
var update = function(index) {
img.src = list[index];
};
/* Count up on the current index, reset to 0 if reaced the total length of array */
var next = function() {
cur = (cur < list.length - 1) ? (cur + 1) : 0;
};
/* Count down, reset to length of array, minus 1 */
var prev = function() {
cur = (cur === 0) ? (cur = list.length - 1) : cur - 1;
};
/* Delegate to the controls elememt */
controls.addEventListener('click', function(e) {
/* Stop any event bubling */
e.stopPropagation();
/* Check which element was clicked by comparing IDs */
if (e.target.id === 'bnext') { next(); }
else if (e.target.id === 'bprev') { prev(); }
else { return; }
/* Render the image with new src */
update(cur);
});
}
imageShowCase(picList);
CSS
header{
display: block;
background: cyan;
height: 150px;
width: 1350px;
box-shadow: 0 4px 8px 0 rgba(0, 0, 0, 0.2), 0 6px 20px 0 rgba(0, 0, 0, 0.19);
}
h1{
color: white;
position: absoute;
padding-left: 450px;
padding-top: 15px;
font-family: 'Cabin', sans-serif;
font-size: 50px;
font-variant: small-caps;
}
.wrapper {
margin: 0 auto;
max-width: 400px;
}
#pics{
width: 100%;
}
#bnext{
width: 80px;
}
#bprev{
width: 80px;
}
HTML
<header>
<h1>Image Showcase</h1>
</header>
<div class="wrapper">
<div id="controls">
<button id="bprev" type="button">Previous</button>
<button id="bnext" type="button">Next</button>
</div>
<br>
<img id="pics" src="http://orig10.deviantart.net/78b3/f/2009/025/0/0/0044146485035ccdcc4f99a681af80c6.jpg"/>
</div>
Related
Clicking on the Home button at the end of this project brings it to the beginning, but no function is reset. Level buttons are not also being enabled anew. If I enable those level buttons by writing some extra code for enabling, then the number of buttons given for each level will be doubled after selecting the level. In other words, for the first time due to selecting the basic level, there were 4 options, But when I click on the last home button and then select the medium level to play the game from the beginning, it becomes 16 options instead of 8.
//VARIABLE DECLARATION PART
let frontpage = document.querySelector(".front-page");
let playbutton = document.querySelector(".play");
let levelpage = document.querySelector(".levelpg");
let startbtn = document.querySelector(".startbtn");
let maingame = document.querySelector(".maingame");
let easybtn = document.querySelector(".easy");
let mediumbtn = document.querySelector(".medium");
let hardbtn = document.querySelector(".hard");
let nextbtn = document.querySelector(".nextbtn");
let pagecount = document.querySelector('.gamepagecount');
let getnumberdiv = document.querySelector('.numberbtn').children;
let resultpg = document.querySelector('.resultpage');
let backhome = document.querySelector('.backhome');
let finalscore = document.querySelector('.score');
let resulttext = resultpg.children[1];
let changeimg = document.querySelector('.resultpage img');
// PLAYBUTTON CLICK
playbutton.addEventListener("click", () => {
frontpage.classList.add("hidden");
levelpage.classList.remove("hidden");
levelpage.classList.add("visibility");
});
//GAME START FUNCTION
function startGame(level) {
if (level == "easy") {
mediumbtn.disabled = true;
hardbtn.disabled = true;
easybtn.disabled = true;
easybtn.classList.add('levelcolor');
startbtn.addEventListener("click", () => {
pagecount.innerHTML = `1 of 10`;
nextbtn.disabled = true
levelChange(4);
gameInterfaceChange()
mainGame(10);
//NEXTBUTTON FUNCTION
nextbtn.addEventListener('click', () => {
enableBtn(4)
pageCount(10);
mainGame(10);
})
});
}
else if (level == "medium") {
mediumbtn.disabled = true;
hardbtn.disabled = true;
easybtn.disabled = true;
mediumbtn.classList.add('levelcolor');
startbtn.addEventListener("click", () => {
pagecount.innerHTML = `1 of 15`;
nextbtn.disabled = true
levelChange(8);
gameInterfaceChange();
maingame.style.top = "20%";
mainGame(20);
//NEXTBUTTON FUNCTION
nextbtn.addEventListener('click', () => {
enableBtn(8)
pageCount(15)
mainGame(20);
})
});
}
else if (level == "hard") {
mediumbtn.disabled = true;
hardbtn.disabled = true;
easybtn.disabled = true;
hardbtn.classList.add('levelcolor');
startbtn.addEventListener("click", () => {
pagecount.innerHTML = `1 of 20`;
nextbtn.disabled = true
levelChange(12);
gameInterfaceChange();
maingame.style.top = "12%";
mainGame(30);
//NEXTBUTTON FUNCTION
nextbtn.addEventListener('click', () => {
enableBtn(12)
pageCount(20)
mainGame(30);
})
});
}
}
//PAGE SLIDING FUNCTION
function gameInterfaceChange() {
levelpage.classList.remove("hidden");
levelpage.classList.add("hidden");
maingame.classList.remove("hidden");
maingame.style.top = "25%";
maingame.classList.add("visibility");
}
// FUNCTION OF RANDOM INPUTING NUMBER IN DIV
function mainGame(maxnum) {
let numboxlen = getnumberdiv.length;
let wrongnum = Math.floor(Math.random() * maxnum) + 1;
let getnumber = [];
//DUPLICATE RANDOM NUMBER CHECKING
for (let i = 0; i < numboxlen; i++) {
let check = getnumber.includes(wrongnum);
if (check === false) {
getnumber.push(wrongnum);
}
else {
while (check === true) {
wrongnum = Math.floor(Math.random() * maxnum) + 1;
check = getnumber.includes(wrongnum);
if (check === false) {
getnumber.push(wrongnum);
}
}
}
}
// NUMBER PUTTING IN InnerHtml
for (var j = 0; j < numboxlen; j++) {
if (getnumber[j] < 10) {
getnumberdiv[j].innerHTML = '0' + getnumber[j];
}
else {
getnumberdiv[j].innerHTML = getnumber[j];
}
}
}
// BUTTON ADDING ACCORDING TO THE LEVEL
function levelChange(divnum) {
for (let index = 0; index < divnum; index++) {
let newBtn = document.createElement('button');
let newbtnNode = document.createTextNode('');
newBtn.appendChild(newbtnNode);
let gamebtn = document.getElementById('numbrbtn');
gamebtn.appendChild(newBtn);
newBtn.setAttribute("onclick", `numberClick(${index},${divnum})`);
}
}
//RIGHT - WRONG CHECKING FUNTION
var right = 0;
var wrong = 0;
function numberClick(index, divnum) {
let rightnumberindex = Math.floor(Math.random() * divnum);
if (index == rightnumberindex) {
nextbtn.disabled = false
right++;
//RIGHT AND WRONG BACKGROUND ADDING AND BUTTON DISABLE
getnumberdiv[index].classList.add("rightans");
for (let i = 0; i < divnum; i++) {
getnumberdiv[i].disabled = true;
}
}
else {
nextbtn.disabled = false
wrong++;
//RIGHT AND WRONG BACKGROUND ADDING AND BUTTON DISABLE
getnumberdiv[rightnumberindex].classList.add("rightans");
getnumberdiv[index].classList.add("wrongans");
for (let i = 0; i < divnum; i++) {
getnumberdiv[i].disabled = true;
}
}
}
// BUTTON ENABLE ON NEXT BUTTION CLICK
function enableBtn(divnum) {
for (let i = 0; i < divnum; i++) {
nextbtn.disabled = true
getnumberdiv[i].disabled = false;
getnumberdiv[i].classList.remove("wrongans");
getnumberdiv[i].classList.remove("rightans");
}
}
//PAGE COUNTING ACCORDING TO THE LEVEL
let currentpg = 1;
function pageCount(levelPg) {
currentpg++;
if (currentpg <= levelPg) {
if (currentpg == levelPg) {
nextbtn.innerHTML = 'Result'
pagecount.innerHTML = `${currentpg} of ${levelPg}`;
}
else {
pagecount.innerHTML = `${currentpg} of ${levelPg}`;
}
}
else {
result();
}
}
//FINAL RESULT FUNTION
function result() {
maingame.classList.remove("visibility");
maingame.classList.add("hidden");
resultpg.classList.remove('hidden')
resultpg.classList.add('visibility')
if (right > wrong) {
changeimg.setAttribute('src', 'trophy.png')
resulttext.innerHTML = `You Win`;
finalscore.innerHTML = `Your Right Score is : ${right} out of ${right + wrong}`;
}
else if (right == wrong) {
changeimg.setAttribute('src', 'draw.png')
resulttext.innerHTML = `It's Draw`;
finalscore.innerHTML = `Your Right Score is : ${right} out of ${right + wrong}`;
}
else if (right < wrong) {
changeimg.setAttribute('src', 'lose.png')
resulttext.innerHTML = `You Lose`;
finalscore.innerHTML = `Your Right Score is : ${right} out of ${right + wrong}`;
}
}
//BACK TO THE HOME FUNCTION
backhome.addEventListener('click', () => {
frontpage.classList.add("visibility");
frontpage.classList.remove("hidden");
resultpg.classList.add('hidden')
resultpg.classList.remove('visibility')
// enable level button
mediumbtn.disabled = false;
hardbtn.disabled = false;
easybtn.disabled = false;
})
* {
margin: 0;
padding: 0;
box-sizing: border-box;
font-family: "Poppins", sans-serif;
}
body {
margin-top: 50px;
}
.guessing-game {
position: relative;
color: white;
text-align: center;
margin: auto;
width: 350px;
height: 600px;
border-radius: 25px;
padding: 50px 30px;
background: linear-gradient(to right, #bd3f32, #cb356b);
}
.guessing-game .front-page .front-img {
height: 160px;
text-align: center;
}
.guessing-game .front-page img {
max-height: 100%;
}
.guessing-game .front-page .front-text h1 {
margin-top: 50px;
font-size: 1.8em;
}
.guessing-game .front-page .front-text p {
margin-top: 10px;
font-size: 1em;
}
.guessing-game .front-page .front-text button,
.resultpage button ,
.levelpg .easy,
.levelpg .medium,
.levelpg .hard,
.maingame .nextbtn {
margin-top: 30px;
width: 100%;
color: white;
padding: 15px;
outline: 0;
border: 0;
border-radius: 50px;
font-size: 0.9em;
background-color: #d64d5d;
box-shadow: rgba(17, 17, 26, 0.1) 0px 1px 0px,
rgba(17, 17, 26, 0.144) 0px 8px 24px, rgba(17, 17, 26, 0.1) 0px 16px 48px;
}
.guessing-game .front-page .front-text button:hover,
.maingame .nextbtn:hover,
.resultpage button:hover {
transition: 0.5s;
background-color: #c22f40;
}
/* Level page */
.visiblepg {
position: absolute;
top: 12%;
width: 290px;
}
.levelpg h1 {
margin: 45px 0 40px 0;
font-weight: 600;
font-size: 2.4em;
border: 1px solid white;
}
.levelpg .easy,
.levelpg .medium,
.levelpg .hard {
display: block;
margin-top: 15px;
padding: 12px;
background: white;
font-size: 1em;
border-radius: 10px;
font-weight: 400;
color: #c22f40;
}
.startbtn {
background: transparent;
border: 0;
outline: 0;
}
.levelpg i {
color: white;
margin-top: 50px;
font-size: 70px;
border-radius: 50%;
border: 2px solid transparent;
}
.levelpg i:hover {
background-color: white;
border: 2px solid white;
color: #c22f40;
transition: 0.5s;
}
/* GAME PART */
.maingame .gamepagecount {
background-color: #d64d5d;
color: white;
padding: 4px;
border-radius: 6px;
font-size: 0.8em;
font-weight: 600;
}
.maingame .gametext {
margin-top: 15px;
font-size: 1.2em;
}
.maingame .numberbtn {
display: flex;
justify-content: space-around;
flex-wrap: wrap;
}
.maingame .numberbtn button {
margin-top: 40px;
width: 50px;
height: 50px;
background-color: white;
display: flex;
align-content: space-around;
justify-content: center;
align-items: center;
flex-wrap: wrap;
flex: 1 0 21%;
margin-left: 10px;
border: 0;
outline: 0;
border-radius: 10px;
font-size: 1em;
color: #c22f40;
font-weight: 600;
}
.maingame .numberbtn button:nth-child(1),
.maingame .numberbtn button:nth-child(5),
.maingame .numberbtn button:nth-child(9) {
margin-left: 0;
}
.resultpage h1 {
margin: 0px 0 40px 0;
}
.resultpage img {
margin-top: 45px;
width: 50%;
}
/* PRE DEFINE CSS */
.visibility {
visibility: visiible;
opacity: 2s;
transition: 0.5s;
transform: translateX(0px);
}
.hidden {
visibility: hidden;
opacity: 0;
transition: 0.5s;
transform: translateX(-30px);
}
.levelcolor {
transition: 0.5s;
color: white !important;
background-color: #c22f40 !important;
}
.rightans {
background-color: #27ae60 !important;
color: white !important;
transition: 0.5s;
}
.wrongans {
background-color: #fd4631 !important;
color: white !important;
transition: 0.5s;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<link rel="preconnect" href="https://fonts.googleapis.com" />
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />
<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" />
<link rel="stylesheet" href="https://pro.fontawesome.com/releases/v5.10.0/css/all.css"
integrity="sha384-AYmEC3Yw5cVb3ZcuHtOA93w35dYTsvhLPVnYs9eStHfGJvOvKxVfELGroGkvsg+p" crossorigin="anonymous" />
<title>Guessing Game</title>
<link rel="stylesheet" href="style.css" />
</head>
<body>
<div class="guessing-game">
<div class="front-page">
<div class="front-img">
<img src="./question.png" alt="" />
</div>
<div class="front-text">
<h1>Guessing Game</h1>
<p>
You just need to chose the right number from the option. If your
guess is right more than wrong , you will win otherwise you will
fail! Let's see how good your sixth sense is!!!
</p>
<button class="play">Let's play</button>
</div>
</div>
<div class="levelpg hidden visiblepg">
<h1>Game level</h1>
<button class="easy" onclick="startGame('easy')">Easy</button>
<button class="medium" onclick="startGame('medium')">Medium</button>
<button class="hard" onclick="startGame('hard')">Hard</button>
<button class="startbtn"><i class="fas fa-play-circle"></i></button>
</div>
<div class="maingame visiblepg hidden">
<p class="gamepagecount">1</p>
<p class="gametext">Guess the number you think is right</p>
<div class="numberbtn" id="numbrbtn"></div>
<button class="nextbtn">Next</button>
</div>
<div class="resultpage levelpg hidden visiblepg">
<img src="" alt="" />
<h1></h1>
<div class="score"></div>
<button class="backhome">Home</button>
</div>
</div>
<script src="./main.js"></script>
</body>
</html>
In short, as soon as I click on the home button, I want the game to start anew, all the functions will be reset anew, and the HTML will be reset anew also. I hope my problem is enough clear to understand.
I have solved the problem.
I just add a reload function to solve this problem.
backhome.addEventListener('click', () => {
frontpage.classList.add("visibility");
frontpage.classList.remove("hidden");
resultpg.classList.add('hidden')
resultpg.classList.remove('visibility')
//reload function
window.location.reload();
})
I am working on a prototype that can enable drag & drop actions between containers. However, I have a conflict case in this :
when I use position: absolute for the draggable items, they are draggable but they are on top of each other :/
when I use position: relative, they are distributed evenly in their container but they are not draggable :/
I collected the code in the below chuck to be testable; please let me know what you think how I can fix this.
<!DOCTYPE html>
<html>
<head>
<style>
html,
body {
width: 100%;
height: 100%;
overflow: hidden;
}
.lang1Container {
width: 100%;
height: 100%;
display: flex;
flex-direction: column;
justify-content: flex-start;
}
.meaningContainer {
border: 1px solid rgba(15, 15, 15, 0.2);
box-shadow: 0px 0px 5px 10px rgba(138, 57, 57, 0.2);
}
.lang1Item {
width: 300px;
height: 20px;
position: absolute;
background-color: #f44336;
color: #ffffff;
font-family: Oxygen, sans-serif;
font-size: px;
padding: 7px;
box-shadow: inset 1px 1px 10px 0 rgba(138, 57, 57, 0.2);
border-radius: 3px;
cursor: pointer;
}
.snap {
width: 301px;
height: 30px;
margin-top: 25px;
margin-bottom: 25px;
}
.over {
background-color: rgb(158, 89, 87, 0.2);
border: 1px solid #7c5b59;
border-radius: 3px;
border-style: dashed;
}
</style>
</head>
<body>
<div style="display: flex; flex-direction: column">
<div
id="lang1MeaningContainer"
style="
background-color: bisque;
min-width: 300px;
min-height: 400px;
border-color: red;
border-style: dashed;
margin: 10px;
"
>
<div class="header">lang1MeaningContainer - Meaning Container</div>
<div class="snap"></div>
<div class="snap"></div>
<div class="snap"></div>
<div class="snap"></div>
<div class="snap"></div>
<div class="snap"></div>
</div>
<div
id="lang1Container"
style="
background-color: bisque;
min-width: 300px;
min-height: 400px;
border-color: red;
border-style: dashed;
margin: 10px;
display: flex;
flex-direction: column;
"
>
<div class="header">lang1Container - English Words</div>
<div id="item1" class="lang1Item">Lang Item 1</div>
<div id="item2" class="lang1Item">Lang Item 2</div>
<span id="item3" class="lang1Item">Lang Item 3</span>
<span id="item4" class="lang1Item">Lang Item 4</span>
</div>
</div>
<script>
let lang1Container = document.getElementById("lang1Container");
let meaningContainer = document.getElementById("lang1MeaningContainer");
let lang1Items = document.getElementsByClassName("lang1Item");
console.log("length:" + lang1Items.length);
for (let i = 0; i < lang1Items.length; i++) {
let item = lang1Items[i];
item.addEventListener("mousedown", (e) => {
onMouseDown(e, item);
});
document.body.addEventListener("mousemove", (e) => {
onMouseMove(e, item);
});
item.addEventListener("mouseup", (e) => {
onMouseUp(e, item);
});
}
let mouseOffset = { x: 0, y: 0 };
let isMouseDown = false;
// for (let i = 0; i < 6; i++) {
// let snap = document.createElement("div");
// snap.className = "snap";
// meaningContainer.appendChild(snap);
// }
let doElsCollide = function (el1, el2) {
el1.offsetBottom = el1.offsetTop + el1.offsetHeight;
el1.offsetRight = el1.offsetLeft + el1.offsetWidth;
el2.offsetBottom = el2.offsetTop + el2.offsetHeight;
el2.offsetRight = el2.offsetLeft + el2.offsetWidth;
return !(
el1.offsetBottom < el2.offsetTop ||
el1.offsetTop > el2.offsetBottom ||
el1.offsetRight < el2.offsetLeft ||
el1.offsetLeft > el2.offsetRight
);
};
function snapMeaning(item, container) {
let box = container.getBoundingClientRect();
item.style.left = box.x + "px";
item.style.top = box.y + "px";
}
function onMouseDown(e, item) {
isMouseDown = true;
mouseOffset = {
x: item.offsetLeft - e.clientX,
y: item.offsetTop - e.clientY,
};
item.style.backgroundColor = "red";
}
function onMouseMove(e, item) {
e.preventDefault();
if (isMouseDown) {
item.style.left = e.clientX + mouseOffset.x + "px";
let tmpStyle = getComputedStyle(item);
let strMarginTop = tmpStyle.marginTop;
let tmpMarginTop = strMarginTop.replace("px", "");
item.style.top = e.clientY - tmpMarginTop + mouseOffset.y + "px"; // zero margin is used in CSS definition, otherwise margin amount need to be subtracted from the item.style.top value to have a proper event reaction. UU
// checking collusions with snaps
let snaps = document.getElementsByClassName("snap");
//console.log("Started checking");
for (let i = 0; i < snaps.length; i++) {
if (doElsCollide(item, snaps[i])) {
snaps[i].className = "snap over";
//console.log("[" + Date.now() + "]", "Collides with " + i);
} else {
snaps[i].className = "snap";
}
}
//console.log("Ended checking");
}
}
function onMouseUp(e, item) {
isMouseDown = false;
let snaps = document.getElementsByClassName("snap");
for (let i = 0; i < snaps.length; i++) {
if (doElsCollide(item, snaps[i])) {
snapMeaning(item, snaps[i]);
}
}
item.className = "lang1Item";
}
</script>
</body>
</html>
I'm converting a player in html into a Vue component.
Half of the component is already created, only the time control slider is missing.
Here is the html player code (Lines with multiple tabs are already implemented in the Vue component):
var audioPlayer = document.querySelector('.green-audio-player');
var playPause = audioPlayer.querySelector('#playPause');
var playpauseBtn = audioPlayer.querySelector('.play-pause-btn');
var loading = audioPlayer.querySelector('.loading');
var progress = audioPlayer.querySelector('.progress');
var sliders = audioPlayer.querySelectorAll('.slider');
var player = audioPlayer.querySelector('audio');
var currentTime = audioPlayer.querySelector('.current-time');
var totalTime = audioPlayer.querySelector('.total-time');
var speaker = audioPlayer.querySelector('#speaker');
var draggableClasses = ['pin'];
var currentlyDragged = null;
window.addEventListener('mousedown', function(event) {
if(!isDraggable(event.target)) return false;
currentlyDragged = event.target;
let handleMethod = currentlyDragged.dataset.method;
this.addEventListener('mousemove', window[handleMethod], false);
window.addEventListener('mouseup', () => {
currentlyDragged = false;
window.removeEventListener('mousemove', window[handleMethod], false);
}, false);
});
playpauseBtn.addEventListener('click', togglePlay);
player.addEventListener('timeupdate', updateProgress);
player.addEventListener('loadedmetadata', () => {
totalTime.textContent = formatTime(player.duration);
});
player.addEventListener('canplay', makePlay);
player.addEventListener('ended', function(){
playPause.attributes.d.value = "M18 12L0 24V0";
player.currentTime = 0;
});
sliders.forEach(slider => {
let pin = slider.querySelector('.pin');
slider.addEventListener('click', window[pin.dataset.method]);
});
function isDraggable(el) {
let canDrag = false;
let classes = Array.from(el.classList);
draggableClasses.forEach(draggable => {
if(classes.indexOf(draggable) !== -1)
canDrag = true;
})
return canDrag;
}
function inRange(event) {
let rangeBox = getRangeBox(event);
let rect = rangeBox.getBoundingClientRect();
let direction = rangeBox.dataset.direction;
if(direction == 'horizontal') {
var min = rangeBox.offsetLeft;
var max = min + rangeBox.offsetWidth;
if(event.clientX < min || event.clientX > max) return false;
} else {
var min = rect.top;
var max = min + rangeBox.offsetHeight;
if(event.clientY < min || event.clientY > max) return false;
}
return true;
}
function updateProgress() {
var current = player.currentTime;
var percent = (current / player.duration) * 100;
progress.style.width = percent + '%';
currentTime.textContent = formatTime(current);
}
function getRangeBox(event) {
let rangeBox = event.target;
let el = currentlyDragged;
if(event.type == 'click' && isDraggable(event.target)) {
rangeBox = event.target.parentElement.parentElement;
}
if(event.type == 'mousemove') {
rangeBox = el.parentElement.parentElement;
}
return rangeBox;
}
function getCoefficient(event) {
let slider = getRangeBox(event);
let rect = slider.getBoundingClientRect();
let K = 0;
if(slider.dataset.direction == 'horizontal') {
let offsetX = event.clientX - slider.offsetLeft;
let width = slider.clientWidth;
K = offsetX / width;
} else if(slider.dataset.direction == 'vertical') {
let height = slider.clientHeight;
var offsetY = event.clientY - rect.top;
K = 1 - offsetY / height;
}
return K;
}
function rewind(event) {
if(inRange(event)) {
player.currentTime = player.duration * getCoefficient(event);
}
}
function formatTime(time) {
var min = Math.floor(time / 60);
var sec = Math.floor(time % 60);
return min + ':' + ((sec<10) ? ('0' + sec) : sec);
}
function togglePlay() {
if(player.paused) {
playPause.attributes.d.value = "M0 0h6v24H0zM12 0h6v24h-6z";
player.play();
} else {
playPause.attributes.d.value = "M18 12L0 24V0";
player.pause();
}
}
function makePlay() {
playpauseBtn.style.display = 'block';
loading.style.display = 'none';
}
.audio.green-audio-player {
width: 400px;
min-width: 300px;
height: 56px;
box-shadow: 0 4px 16px 0 rgba(0, 0, 0, 0.07);
display: flex;
justify-content: space-between;
align-items: center;
padding-left: 24px;
padding-right: 24px;
border-radius: 4px;
user-select: none;
-webkit-user-select: none;
background-color: #fff;
}
.audio.green-audio-player .play-pause-btn {
display: none;
cursor: pointer;
}
.audio.green-audio-player .spinner {
width: 18px;
height: 18px;
background-image: url(https://s3-us-west-2.amazonaws.com/s.cdpn.io/355309/loading.png);
background-size: cover;
background-repeat: no-repeat;
animation: spin 0.4s linear infinite;
}
.audio.green-audio-player .slider {
flex-grow: 1;
background-color: #D8D8D8;
cursor: pointer;
position: relative;
}
.audio.green-audio-player .slider .progress {
background-color: #44BFA3;
border-radius: inherit;
position: absolute;
pointer-events: none;
}
.audio.green-audio-player .slider .progress .pin {
height: 16px;
width: 16px;
border-radius: 8px;
background-color: #44BFA3;
position: absolute;
pointer-events: all;
box-shadow: 0px 1px 1px 0px rgba(0, 0, 0, 0.32);
}
.audio.green-audio-player .controls {
font-family: 'Roboto', sans-serif;
font-size: 16px;
line-height: 18px;
color: #55606E;
display: flex;
flex-grow: 1;
justify-content: space-between;
align-items: center;
margin-left: 24px;
}
.audio.green-audio-player .controls .slider {
margin-left: 16px;
margin-right: 16px;
border-radius: 2px;
height: 4px;
}
.audio.green-audio-player .controls .slider .progress {
width: 0;
height: 100%;
}
.audio.green-audio-player .controls .slider .progress .pin {
right: -8px;
top: -6px;
}
.audio.green-audio-player .controls span {
cursor: default;
}
svg, img {
display: block;
}
#keyframes spin {
from {
transform: rotateZ(0);
}
to {
transform: rotateZ(1turn);
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div class="audio green-audio-player">
<div class="loading">
<div class="spinner"></div>
</div>
<div class="play-pause-btn">
<svg xmlns="http://www.w3.org/2000/svg" width="18" height="24" viewBox="0 0 18 24">
<path fill="#566574" fill-rule="evenodd" d="M18 12L0 24V0" class="play-pause-icon" id="playPause"/>
</svg>
</div>
<div class="controls">
<span class="current-time">0:00</span>
<div class="slider" data-direction="horizontal">
<div class="progress">
<div class="pin" id="progress-pin" data-method="rewind"></div>
</div>
</div>
<span class="total-time">0:00</span>
</div>
<audio>
<source src="https://s3-us-west-2.amazonaws.com/s.cdpn.io/355309/Swing_Jazz_Drum.mp3" type="audio/mpeg">
</audio>
</div>
Html Codepen: https://codepen.io/caiokawasaki/pen/JwVwry
Here is the Vue component:
Vue.component('audio-player', {
props: ['message'],
data: () => ({
audio: undefined,
loaded: false,
playing: false,
currentTime: '00:00',
totalTime: '00:00',
percent: '0%',
draggableClasses: ['pin'],
currentlyDragged: null
}),
computed: {},
methods: {
formatTime(time) {
var min = Math.floor(time / 60);
var sec = Math.floor(time % 60);
return min + ':' + ((sec < 10) ? ('0' + sec) : sec);
},
loadedMetaData() {
this.totalTime = this.formatTime(this.audio.duration)
},
canPlay() {
this.loaded = true
},
timeUpdate(){
var current = this.audio.currentTime;
var percent = (current / this.audio.duration) * 100;
this.percent = percent + '%';
this.currentTime = this.formatTime(current);
},
ended(){
this.playing = false
this.audio.currentTime = 0
},
isDraggable(el) {
let canDrag = false;
let classes = Array.from(el.classList);
this.draggableClasses.forEach(draggable => {
if (classes.indexOf(draggable) !== -1)
canDrag = true;
})
return canDrag;
},
inRange(event) {
let rangeBox = getRangeBox(event);
let rect = rangeBox.getBoundingClientRect();
let direction = rangeBox.dataset.direction;
if (direction == 'horizontal') {
var min = rangeBox.offsetLeft;
var max = min + rangeBox.offsetWidth;
if (event.clientX < min || event.clientX > max) return false;
} else {
var min = rect.top;
var max = min + rangeBox.offsetHeight;
if (event.clientY < min || event.clientY > max) return false;
}
return true;
},
togglePlay() {
if (this.audio.paused) {
this.audio.play();
this.playing = true;
} else {
this.audio.pause();
this.playing = false;
}
},
makePlay() {
playpauseBtn.style.display = 'block';
loading.style.display = 'none';
},
getRangeBox(event) {
let rangeBox = event.target;
let el = currentlyDragged;
if (event.type == 'click' && isDraggable(event.target)) {
rangeBox = event.target.parentElement.parentElement;
}
if (event.type == 'mousemove') {
rangeBox = el.parentElement.parentElement;
}
return rangeBox;
},
getCoefficient(event) {
let slider = getRangeBox(event);
let rect = slider.getBoundingClientRect();
let K = 0;
if (slider.dataset.direction == 'horizontal') {
let offsetX = event.clientX - slider.offsetLeft;
let width = slider.clientWidth;
K = offsetX / width;
} else if (slider.dataset.direction == 'vertical') {
let height = slider.clientHeight;
var offsetY = event.clientY - rect.top;
K = 1 - offsetY / height;
}
return K;
},
rewind(event) {
if (this.inRange(event)) {
this.audio.currentTime = this.audio.duration * getCoefficient(event);
}
}
},
mounted() {
this.audio = this.$refs.audio
},
template: `<div class="audio-message-content">
<a v-if="loaded" class="play-pause-btn" href="#" :title="playing ? 'Clique aqui para pausar o audio' : 'Clique aqui ouvir o audio'" #click.prevent="togglePlay">
<svg key="pause" v-if="playing" x="0px" y="0px" viewBox="0 0 18 20" style="width: 18px; height: 20px; margin-top: -10px">
<path d="M17.1,20c0.49,0,0.9-0.43,0.9-0.96V0.96C18,0.43,17.6,0,17.1,0h-5.39c-0.49,0-0.9,0.43-0.9,0.96v18.07c0,0.53,0.4,0.96,0.9,0.96H17.1z M17.1,20"/>
<path d="M6.29,20c0.49,0,0.9-0.43,0.9-0.96V0.96C7.19,0.43,6.78,0,6.29,0H0.9C0.4,0,0,0.43,0,0.96v18.07C0,19.57,0.4,20,0.9,20H6.29z M6.29,20"/>
</svg>
<svg key="play" v-else x="0px" y="0px" viewBox="0 0 18 22" style="width: 18px; height: 22px; margin-top: -11px">
<path d="M17.45,10.01L1.61,0.14c-0.65-0.4-1.46,0.11-1.46,0.91V20.8c0,0.81,0.81,1.32,1.46,0.91l15.84-9.87C18.1,11.43,18.1,10.41,17.45,10.01L17.45,10.01z M17.45,10.01"/>
</svg>
</a>
<div v-else class="loading">
<div class="spinner"></div>
</div>
<div class="controls">
<span class="current-time">{{ currentTime }}</span>
<div class="slider" data-direction="horizontal" #click="">
<div class="progress" :style="{width: percent}">
<div class="pin" id="progress-pin" data-method="rewind"></div>
</div>
</div>
<span class="total-time">{{ totalTime }}</span>
</div>
<audio ref="audio" src="https://s3-us-west-2.amazonaws.com/s.cdpn.io/355309/Swing_Jazz_Drum.mp3" #loadedmetadata="loadedMetaData" #canplay="canPlay" #timeupdate="timeUpdate" #ended="ended"></audio>
</div>`
})
var app = new Vue({
el: '#app'
})
.audio-message-content {
width: 400px;
min-width: 300px;
height: 56px;
box-shadow: 0 4px 16px 0 rgba(0, 0, 0, 0.07);
display: flex;
justify-content: space-between;
align-items: center;
padding-left: 24px;
padding-right: 24px;
border-radius: 4px;
user-select: none;
-webkit-user-select: none;
background-color: #fff;
}
.audio-message-content .play-pause-btn {
position: relative;
width: 18px;
height: 22px;
cursor: pointer;
}
.audio-message-content .play-pause-btn svg {
display: block;
position: absolute;
top: 50%;
left: 50%;
margin-left: -9px;
}
.audio-message-content .spinner {
width: 18px;
height: 18px;
background-image: url(https://s3-us-west-2.amazonaws.com/s.cdpn.io/355309/loading.png);
background-size: cover;
background-repeat: no-repeat;
animation: spin 0.4s linear infinite;
}
.audio-message-content .slider {
flex-grow: 1;
background-color: #D8D8D8;
cursor: pointer;
position: relative;
}
.audio-message-content .slider .progress {
background-color: #44BFA3;
border-radius: inherit;
position: absolute;
pointer-events: none;
}
.audio-message-content .slider .progress .pin {
height: 16px;
width: 16px;
border-radius: 8px;
background-color: #44BFA3;
position: absolute;
pointer-events: all;
box-shadow: 0px 1px 1px 0px rgba(0, 0, 0, 0.32);
}
.audio-message-content .controls {
font-family: 'Roboto', sans-serif;
font-size: 16px;
line-height: 18px;
color: #55606E;
display: flex;
flex-grow: 1;
justify-content: space-between;
align-items: center;
margin-left: 24px;
}
.audio-message-content .controls .slider {
margin-left: 16px;
margin-right: 16px;
border-radius: 2px;
height: 4px;
}
.audio-message-content .controls .slider .progress {
width: 0;
height: 100%;
}
.audio-message-content .controls .slider .progress .pin {
right: -8px;
top: -6px;
}
.audio-message-content .controls span {
cursor: default;
}
svg, img {
display: block;
}
#keyframes spin {
from {
transform: rotateZ(0);
}
to {
transform: rotateZ(1turn);
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
<audio-player></audio-player>
</div>
Vue Component Codepen: https://codepen.io/caiokawasaki/pen/QzRMwz
Functions like the following I could not understand nor find anything on the internet:
window[handleMethod]
window[pin.dataset.method]
Can anyone help me finalize this component?
Edit
I've converted all of the html and javascript into a Vue component but anyway it still is not working properly.
The only thing that is not working properly is the progress bar. It needs to perform two functions:
Clicking it should go to the desired time.
When clicking on the pin and drag it should go to the desired time.
I use Vue Cli, neither of the above two work in the form of .vue files, but in Codepen normally written only function 2 works.
Codepen: https://codepen.io/caiokawasaki/pen/VqOqBQ
The function: window[handleMethod] is executed by deriving the name of the method off of the data- property from the pin element:
<div class="pin" id="progress-pin" data-method="rewind"></div>
So window[handleMethod] is equivalent to window.rewind()
The same is true for window[pin.dataset.method].
So in your case:
this[handleMethod](event)
and:
this[pin.dataset.method](event)
Should be suitable replacements.
Im working on a tetris project for uni. I have got most of the function to work except one. The intended flow is as follows:
Index page with a button to load the game
On clicking the button the game starts with a background audio(sample audio for now)
on pause/play of the game the audio also should stop
Once the audio is over, the game should stop and change to a div element with some text/questionnaire.
I have got steps 1-3 working, but kind of hit a bump at step 4. The page is rendered using js. I have added $('.tetrisGame').innerHTML = '<H1>GAME OVER</H1>'; to the music.oneded function. It does not render the innerHTML. So after the music stops, the console displays the message and that is it.
Also I have tried to add a hidden div element in the html file and display it after the music has ended, but the innerhtml returns null(probably because the js replaces the elements from the html file with the element rendered in the js file.
HELP NEEDED: Please check the code and let me know how to show a div element after the music stops.
Code added for verfification. Any further info in regards to code, let me know.
Thanks
var NUM_ROWS = 20;
var NUM_COLS = 10;
var BLOCK_WIDTH = 30;
var BLOCK_HEIGHT = 30;
var TICK_MS = 400;
var pieces = [
[
[0, 0, 0, 0],
[0, 1, 1, 0],
[0, 1, 1, 0],
[0, 0, 0, 0]
],
[
[0, 0, 1, 0],
[0, 0, 1, 0],
[0, 0, 1, 0],
[0, 0, 1, 0]
],
[
[0, 0, 1, 0],
[0, 1, 1, 0],
[0, 0, 1, 0],
[0, 0, 0, 0]
],
[
[0, 0, 0, 0],
[0, 0, 1, 1],
[0, 1, 1, 0],
[0, 0, 0, 0]
],
[
[0, 0, 0, 0],
[0, 1, 1, 0],
[0, 0, 1, 1],
[0, 0, 0, 0]
],
[
[0, 0, 1, 0],
[0, 0, 1, 0],
[0, 1, 1, 0],
[0, 0, 0, 0]
],
[
[0, 1, 0, 0],
[0, 1, 0, 0],
[0, 1, 1, 0],
[0, 0, 0, 0]
]
];
var KEY_ENTER = 13;
var KEY_SPACE = 32;
var KEY_LEFT = 37;
var KEY_RIGHT = 39;
var KEY_DOWN = 40;
var KEY_A = 65;
var KEY_D = 68;
var KEY_R = 82;
var music = new Audio('http://www.sample-videos.com/audio/mp3/india-national-anthem.mp3');
//music = new Audio('http://techslides.com/demos/samples/sample.mp3');
function rotateLeft(piece) {
return [
[piece[0][3], piece[1][3], piece[2][3], piece[3][3]],
[piece[0][2], piece[1][2], piece[2][2], piece[3][2]],
[piece[0][1], piece[1][1], piece[2][1], piece[3][1]],
[piece[0][0], piece[1][0], piece[2][0], piece[3][0]]
];
}
function rotateRight(piece) {
return [
[piece[3][0], piece[2][0], piece[1][0], piece[0][0]],
[piece[3][1], piece[2][1], piece[1][1], piece[0][1]],
[piece[3][2], piece[2][2], piece[1][2], piece[0][2]],
[piece[3][3], piece[2][3], piece[1][3], piece[0][3]]
];
}
function intersects(rows, piece, y, x) {
for (var i = 0; i < 4; i++)
for (var j = 0; j < 4; j++)
if (piece[i][j])
if (y + i >= NUM_ROWS || x + j < 0 || x + j >= NUM_COLS || rows[y + i][x + j])
return true;
return false;
}
function apply_piece(rows, piece, y, x) {
var newRows = [];
for (var i = 0; i < NUM_ROWS; i++)
newRows[i] = rows[i].slice();
for (var i = 0; i < 4; i++)
for (var j = 0; j < 4; j++)
if (piece[i][j])
newRows[y + i][x + j] = 1;
return newRows;
}
function kill_rows(rows) {
var newRows = [];
var k = NUM_ROWS;
for (var i = NUM_ROWS; i-- > 0;) {
for (var j = 0; j < NUM_COLS; j++) {
if (!rows[i][j]) {
newRows[--k] = rows[i].slice();
break;
}
}
}
for (var i = 0; i < k; i++) {
newRows[i] = [];
for (var j = 0; j < NUM_COLS; j++)
newRows[i][j] = 0;
}
return {
'rows': newRows,
'numRowsKilled': k,
};
}
function randomPiece() {
return pieces[Math.floor(Math.random() * pieces.length)];
}
function TetrisGame() {
this.gameOver = false;
this.score = 0;
this.currentPiece = randomPiece();
this.nextPiece = randomPiece();
this.pieceY = 0;
this.pieceX = 3;
this.rows = [];
for (var i = 0; i < NUM_ROWS; i++) {
this.rows[i] = []
for (var j = 0; j < NUM_COLS; j++) {
this.rows[i][j] = 0;
}
}
playMusic();;
}
TetrisGame.prototype.tick = function() {
if (this.gameOver)
return false;
if (intersects(this.rows, this.currentPiece, this.pieceY + 1, this.pieceX)) {
/* burn current piece into board */
this.rows = apply_piece(this.rows, this.currentPiece, this.pieceY, this.pieceX);
var r = kill_rows(this.rows);
this.rows = r.rows;
this.score += r.numRowsKilled;
/* fetch next piece */
if (intersects(this.rows, this.nextPiece, 0, NUM_COLS / 2 - 2)) {
this.gameOver = true;
} else {
this.currentPiece = this.nextPiece;
this.pieceY = 0;
this.pieceX = NUM_COLS / 2 - 2;
this.nextPiece = randomPiece();
}
} else {
this.pieceY += 1;
}
return true;
}
TetrisGame.prototype.steerLeft = function() {
if (!intersects(this.rows, this.currentPiece, this.pieceY, this.pieceX - 1))
this.pieceX -= 1;
}
TetrisGame.prototype.steerRight = function() {
if (!intersects(this.rows, this.currentPiece, this.pieceY, this.pieceX + 1))
this.pieceX += 1;
}
TetrisGame.prototype.steerDown = function() {
if (!intersects(this.rows, this.currentPiece, this.pieceY + 1, this.pieceX))
this.pieceY += 1;
}
TetrisGame.prototype.rotateLeft = function() {
var newPiece = rotateLeft(this.currentPiece);
if (!intersects(this.rows, newPiece, this.pieceY, this.pieceX))
this.currentPiece = newPiece;
}
TetrisGame.prototype.rotateRight = function() {
var newPiece = rotateRight(this.currentPiece);
if (!intersects(this.rows, newPiece, this.pieceY, this.pieceX))
this.currentPiece = newPiece;
}
TetrisGame.prototype.letFall = function() {
while (!intersects(this.rows, this.currentPiece, this.pieceY + 1, this.pieceX))
this.pieceY += 1;
this.tick();
}
TetrisGame.prototype.get_rows = function() {
return apply_piece(this.rows, this.currentPiece, this.pieceY, this.pieceX);
}
TetrisGame.prototype.get_next_piece = function() {
return this.nextPiece;
}
TetrisGame.prototype.get_score = function() {
return this.score;
}
TetrisGame.prototype.get_game_over = function() {
return this.gameOver;
}
function draw_blocks(rows, num_rows, num_cols) {
var boardElem = document.createElement('div');
for (var i = 0; i < num_rows; i++) {
for (var j = 0; j < num_cols; j++) {
var blockElem = document.createElement('div');
blockElem.classList.add('tetrisBlock');
if (rows[i][j])
blockElem.classList.add('habitated');
blockElem.style.top = (i * BLOCK_HEIGHT) + 'px';
blockElem.style.left = (j * BLOCK_WIDTH) + 'px';
boardElem.appendChild(blockElem);
}
}
return boardElem;
}
function draw_tetrisGame(game, isPaused) {
var leftPaneElem = draw_tetrisLeftPane(game, isPaused);
var rightPaneElem = draw_tetrisRightPane(game);
var gameElem = document.createElement('div');
gameElem.classList.add('tetrisGame');
gameElem.appendChild(leftPaneElem);
gameElem.appendChild(rightPaneElem);
return gameElem;
}
function draw_tetrisLeftPane(game, isPaused) {
var scoreElem = draw_tetrisScore(game, isPaused);
var previewElem = draw_tetrisPreview(game);
var usageElem = draw_tetrisUsage(game);
var leftPaneElem = document.createElement('div');
leftPaneElem.classList.add('tetrisLeftPane');
leftPaneElem.appendChild(previewElem);
leftPaneElem.appendChild(scoreElem);
leftPaneElem.appendChild(usageElem);
return leftPaneElem;
}
function draw_tetrisRightPane(game) {
var boardElem = draw_tetrisBoard(game);
var rightPaneElem = document.createElement('div');
rightPaneElem.classList.add('tetrisRightPane');
rightPaneElem.appendChild(boardElem);
return rightPaneElem;
}
function draw_tetrisBoard(game) {
var rows = game.get_rows();
var boardElem = draw_blocks(rows, NUM_ROWS, NUM_COLS);
boardElem.classList.add('tetrisBoard');
return boardElem;
}
function draw_tetrisScore(game, isPaused) {
var score = game.get_score();
var scoreElem = document.createElement('div');
scoreElem.classList.add('tetrisScore');
scoreElem.innerHTML = '<p>SCORE: ' + score + '</p>';
//showscore = "YOUR SCORE: " + score;
if (isPaused)
scoreElem.innerHTML += '<p class="blink_text">PAUSED</p>'
if (game.get_game_over())
scoreElem.innerHTML += '<p>GAME OVER</p>' + '<h4 class= "blink_text">PRESS <b>R</b> TO RESTART</h4>';
return scoreElem;
}
function draw_tetrisPreview(game) {
var piece = game.get_next_piece();
var pieceElem = draw_blocks(piece, 4, 4);
var previewElem = document.createElement('div');
previewElem.classList.add('tetrisPreview');
previewElem.appendChild(pieceElem);
return previewElem;
}
function draw_tetrisUsage(game) {
var usageElem = document.createElement('div');
usageElem.classList.add('tetrisUsage');
usageElem.innerHTML =
"<table>" +
"<tr><th>Keyboard Keys</th><td>Function</td></tr>" +
"<tr><th>a/d</th><td>Rotate</td></tr>" +
"<tr><th>Space bar</th><td>Let fall</td></tr>" +
"<tr><th>Enter</th><td>Toggle pause</td></tr>" +
"<tr><th>r</th><td>Restart game</td></tr>" +
"</table>";
return usageElem;
}
function redraw(game, isPaused, containerElem) {
var gameElem = draw_tetrisGame(game, isPaused);
containerElem.innerHTML = "<center style='margin-top:0;'><font size='15'>TETRIS</font><h3>Test your active listening skills</h3></center><br>";
containerElem.appendChild(gameElem);
}
function playMusic(game) {
music.play();
music.onended = function(game) {
var msg = "audio playback has ended";
console.log(msg);
$('.tetrisGame').innerHTML = '<H1>GAME OVER</H1>';
//location.href = "intrimlandingpage.html";
}
}
function tetris_run(containerElem) {
var game = new TetrisGame();
play1();
playMusic();
function play1() {
var intervalHandler = setInterval(
function() {
if (game.tick())
redraw(game, false, containerElem);
},
TICK_MS
);
function keyHandler(kev) {
if (kev.shiftKey || kev.altKey || kev.metaKey)
return;
var consumed = true;
var mustpause = false;
if (kev.keyCode === KEY_ENTER) {
mustpause = true;
music.pause();
} else if (kev.keyCode === KEY_R) {
location.replace(location);
} else if (kev.keyCode === KEY_LEFT) {
game.steerLeft();
} else if (kev.keyCode === KEY_RIGHT) {
game.steerRight();
} else if (kev.keyCode === KEY_DOWN) {
game.steerDown();
} else if (kev.keyCode === KEY_A) {
game.rotateLeft();
} else if (kev.keyCode === KEY_D) {
game.rotateRight();
} else if (kev.keyCode === KEY_SPACE) {
game.letFall();
} else {
consumed = false;
}
if (consumed) {
kev.preventDefault();
if (mustpause) {
containerElem.removeEventListener('keydown', keyHandler);
clearInterval(intervalHandler);
pause();
} else {
redraw(game, false, containerElem);
}
}
}
containerElem.addEventListener('keydown', keyHandler);
}
function pause() {
function keyHandler(kev) {
if (kev.keyCode == KEY_ENTER) {
containerElem.removeEventListener('keydown', keyHandler);
play1();
music.play();
}
}
containerElem.addEventListener('keydown', keyHandler);
redraw(game, true, containerElem);
}
}
div.tetrisGame {
position: relative;
margin: auto;
padding: auto;
border: none;
width: 600px;
height: 600px;
float: left;
right: -27%;
}
#audio1 {
display: none;
}
div.tetrisGame div.tetrisLeftPane {
position: absolute;
top: 0;
left: 0;
width: 300px;
}
div.tetrisLeftPane div.tetrisScore {
position: absolute;
top: 150px;
left: 0;
font-size: 20pt;
}
div.tetrisLeftPane div.tetrisPreview {
position: absolute;
left: 150px;
width: 120px;
/* 4 cols * 30px */
height: 120px;
/* 4 rows * 30px */
}
div.tetrisLeftPane div.tetrisUsage {
position: absolute;
left: 0;
top: 350px;
}
div.tetrisLeftPane div.tetrisUsage th,
div.tetrisLeftPane div.tetrisUsage td {
text-align: left;
}
div.tetrisLeftPane div.tetrisUsage td {
padding-left: 1em;
}
div.tetrisRightPane {
position: absolute;
left: 300px;
top: 0px;
width: 300px;
/* 10 cols * 30px */
height: 600px;
/* 20 rows * 30px */
}
div.tetrisRightPane div.tetrisBoard {
position: absolute;
left: 0;
top: 0;
width: 300px;
/* 10 cols * 30px */
height: 600px;
/* 20 rows * 30px */
}
div.tetrisBlock {
position: absolute;
width: 29px;
height: 29px;
border: 1px solid black;
background-color: #EAEAEA;
}
div.tetrisBlock.habitated {
border: 1px solid black;
background-color: black;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.2/jquery.min.js"></script>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="author" content="Andrew Patrick">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Tetris</title>
<link rel="stylesheet" type="text/css" href="tetris.css">
<link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<link rel="stylesheet" type="text/css" href="https://fonts.googleapis.com/css?family=Roboto:300,400,500,700">
<link rel="stylesheet" type="text/css" href="https://fonts.googleapis.com/icon?family=Material+Icons">
<style>
#footer {
position: absolute;
bottom: 0;
width: 100%;
height: 60px;
/* Height of the footer */
}
body {
color: #666;
font-family: sans-serif;
line-height: 1.4;
}
h1 {
color: #444;
font-size: 1.2em;
padding: 14px 2px 12px;
margin: 0px;
}
h1 em {
font-style: normal;
color: #999;
}
a {
color: #888;
text-decoration: none;
}
#player {
width: 400px;
margin: auto;
}
ol {
padding: 0px;
margin: 0px;
list-style: decimal-leading-zero inside;
color: #ccc;
width: 460px;
border-top: 1px solid #ccc;
font-size: 0.9em;
}
ol li {
position: relative;
margin: 0px;
padding: 9px 2px 10px;
border-bottom: 1px solid #ccc;
cursor: pointer;
}
ol li a {
display: block;
text-indent: -3.3ex;
padding: 0px 0px 0px 20px;
}
li.playing {
color: #aaa;
text-shadow: 1px 1px 0px rgba(255, 255, 255, 0.3);
}
li.playing a {
color: #000;
}
li.playing:before {
content: '♬';
width: 14px;
height: 14px;
padding: 3px;
line-height: 14px;
margin: 0px;
position: absolute;
left: -24px;
top: 17px;
color: #000;
font-size: 13px;
text-shadow: 1px 1px 0px rgba(0, 0, 0, 0.2);
}
#shortcuts {
position: fixed;
bottom: 0px;
width: 100%;
color: #666;
font-size: 0.9em;
margin: 60px 0px 0px;
padding: 20px 20px 15px;
background: #f3f3f3;
background: rgba(240, 240, 240, 0.7);
}
#shortcuts div {
width: 460px;
margin: 0px auto;
}
#shortcuts h1 {
margin: 0px 0px 6px;
}
#shortcuts p {
margin: 0px 0px 18px;
}
#shortcuts em {
font-style: normal;
background: #d3d3d3;
padding: 3px 9px;
position: relative;
left: -3px;
-webkit-border-radius: 4px;
-moz-border-radius: 4px;
-o-border-radius: 4px;
border-radius: 4px;
-webkit-box-shadow: 1px 1px 2px rgba(0, 0, 0, 0.1);
-moz-box-shadow: 1px 1px 2px rgba(0, 0, 0, 0.1);
-o-box-shadow: 1px 1px 2px rgba(0, 0, 0, 0.1);
box-shadow: 1px 1px 2px rgba(0, 0, 0, 0.1);
}
#media screen and (max-device-width: auto) {
#player {
position: relative;
}
}
.blink_text {
animation: 1s blinker linear infinite;
-webkit-animation: 1s blinker linear infinite;
-moz-animation: 1s blinker linear infinite;
color: red;
}
#-moz-keyframes blinker {
0% {
opacity: 1.0;
}
50% {
opacity: 0.0;
}
100% {
opacity: 1.0;
}
}
#-webkit-keyframes blinker {
0% {
opacity: 1.0;
}
50% {
opacity: 0.0;
}
100% {
opacity: 1.0;
}
}
#keyframes blinker {
0% {
opacity: 1.0;
}
50% {
opacity: 0.0;
}
100% {
opacity: 1.0;
}
}
</style>
<script type='text/javascript' src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.2/jquery.min.js"></script>
<script src="tetris.js"></script>
</head>
<body>
<div id="header" style="margin-top:600px; background-image:url('Header.jpg');background-size: contain; display: block; width: 100%; height: auto; padding: 0px; margin: 0px; border: none;">
<br><br><br><br><br><br><br><br><br><br><br><br />
<center>
<font size="15" color="white">TETRIS</font>
<h3>
<font color="white">Test your active listening skills</h3>
</font>
</center>
</div><br>
<div class="container">
<center>
<div class="col-xs-12">
<button id="gamerun" type="button" style="margin-top:1px ; margin-bottom:1px" onclick="tetris_run(document.body)" class="btn btn-raised btn-success btn-lg"> Start Game</button>
</div>
</center>
</div>
<center>
<div id="footer"><b>Project Tertris 2017</b></div>
</center>
</body>
</html>
Calling $('.tetrisGame') will give back an array like jQuery object that is a list of elements that match that given class - and you will not be able to call innerHTML on that. Call instead something like this:
$('.tetrisGame')[0].innerHTML = '<H1>GAME OVER</H1>'
Or if you have multiple tetris games, then you can call the each function like so :
$('.tetrisGame').each((callback, args) => { /* do stuff */ })
Or use Array.prototype.slice.call($('.tetrisGame')) to get an Array instead to run forEach on.
I have a slider with a pop-up that shows the current value of the slider.
but I want it only appears if I click on the slider and disappears when I do not click
is there a way to do it?
Below is my css js and html code
html:
<input type="range" id="myrange" name="myrange" class="zoom-range" min="0.25" max="2.00" step="0.01"/>
<output id="rangeHover" for="myrange" onmouseover="value = myrange.valueAsNumber;"></output>
js:
function modifyOffset() {
var el, newPoint, newPlace, offset, siblings, k;
width = this.offsetWidth;
newPoint = (this.value - this.getAttribute("min")) / (this.getAttribute("max") - this.getAttribute("min"));
offset = -1;
if (newPoint < 0) { newPlace = 0; }
else if (newPoint > 1) { newPlace = width; }
else { newPlace = width * newPoint + offset; offset -= newPoint;}
siblings = this.parentNode.childNodes;
for (var i = 0; i < siblings.length; i++) {
sibling = siblings[i];
if (sibling.id == this.id) { k = true; }
if ((k == true) && (sibling.nodeName == "OUTPUT")) {
outputTag = sibling;
}
}
outputTag.style.left = newPlace + "px";
outputTag.style.marginLeft = offset + "%";
outputTag.innerHTML = this.value;
}
function modifyInputs() {
var inputs = document.getElementsByTagName("input");
for (var i = 0; i < inputs.length; i++) {
if (inputs[i].getAttribute("type") == "range") {
inputs[i].onchange = modifyOffset;
// the following taken from http://stackoverflow.com/questions/2856513/trigger-onchange-event-manually
if ("fireEvent" in inputs[i]) {
inputs[i].fireEvent("onchange");
} else {
var evt = document.createEvent("HTMLEvents");
evt.initEvent("change", false, true);
inputs[i].dispatchEvent(evt);
}
}
}
}
window.onload = modifyInputs;
css:
output {
position: absolute;
background-image: linear-gradient(#FAFAD2, #FAFAD2);
width: 30px;
height: 15px;
text-align: center;
color: black;
border-radius: 5px;
display: block;
bottom: 120%;
margin-top:5000px;
font-size:11px;
left: 100%;
}
output:after {
content: "";
position: absolute;
width: 0px;
height: 0px;
border-top: 10px solid #FAFAD2;
border-left: 5px solid transparent;
border-right: 5px solid transparent;
top: 100%;
left: 100%;
margin-left: -26px;
margin-top: -1px;
}
#rangeHover{
display: block;
position: relative;
margin: -50px;
padding-right:10px;
padding-left:10px;
}
Thanks for help!
you could add to css:
output
{
display:none
}
input:hover + output
{
display:block;
}
UPDATE
tooltip visible on click:
input:active+ output
{
display:block;
}