TETRIS html5 GAME code check - javascript

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.

Related

init function TypeError: Cannot read property 'style' of null

No matter how I wrote the code, I received the same message and I've been trying to fix this since last night, but I don't understand why this is bothering me so much.
I get the message that all these lines are wrong
I work according to my course and this code is from a course that works on video and it doesn't work for me, I've tried a lot of changes but it doesn't work.
document.getElementById('dice-1').style.display = 'block';
document.getElementById('dice-2').style.display = 'block';
var scores, roundScore, activePlayer, gamePlaying;
var lastDice;
function init() {
scores = [0, 0];
activePlayer = 0;
roundScore = 0;
gamePlaying = true;
document.getElementById('dice-1').style.display = 'none';
document.getElementById('dice-2').style.display = 'none';
document.getElementById('score-0').textContent = '0';
document.getElementById('score-1').textContent = '0';
document.getElementById('current-0').textContent = '0';
document.getElementById('current-1').textContent = '0';
document.getElementById('name-0').textContent = 'Player 1';
document.getElementById('name-1').textContent = 'Player 2';
document.querySelector('.player-0-panel').classList.remove('winner');
document.querySelector('.player-1-panel').classList.remove('winner');
document.querySelector('.player-0-panel').classList.remove('active');
document.querySelector('.player-1-panel').classList.remove('active');
document.querySelector('.player-0-panel').classList.add('active');
}
document.querySelector('.btn-roll').addEventListener('click', function() {
if(gamePlaying) {
var dice1 = Math.floor(Math.random() * 6) + 1;
var dice2 = Math.floor(Math.random() * 6) + 1;
document.getElementById('dice-1').style.display = 'block';
document.getElementById('dice-2').style.display = 'block';
document.getElementById('dice-1').src = 'dice-' + dice1 + '.png';
document.getElementById('dice-2').src = 'dice-' + dice2 + '.png';
if (dice1 !== 1 && dice2 !== 1) {
roundScore += dice1 + dice2;
document.querySelector('#current-' + activePlayer).textContent = roundScore;
} else {
nextPlayer();
}
}
});
document.querySelector('.btn-hold').addEventListener('click', function() {
if (gamePlaying) {
scores[activePlayer] += roundScore;
document.querySelector('#score-' + activePlayer).textContent = scores[activePlayer];
var input = document.querySelector('.final-score').value;
var winningScore;
if(input) {
winningScore = input;
} else {
winningScore = 100;
}
// Check if player won the game
if (scores[activePlayer] >= winningScore) {
document.querySelector('#name-' + activePlayer).textContent = 'Winner!';
document.getElementById('dice-1').style.display = 'none';
document.getElementById('dice-2').style.display = 'none';
document.querySelector('.player-' + activePlayer + '-panel').classList.add('winner');
document.querySelector('.player-' + activePlayer + '-panel').classList.remove('active');
gamePlaying = false;
} else {
nextPlayer();
}
}
});
function nextPlayer() {
activePlayer === 0 ? activePlayer = 1 : activePlayer = 0;
roundScore = 0;
document.getElementById('current-0').textContent = '0';
document.getElementById('current-1').textContent = '0';
document.querySelector('.player-0-panel').classList.toggle('active');
document.querySelector('.player-1-panel').classList.toggle('active');
document.getElementById('dice-1').style.display = 'none';
document.getElementById('dice-2').style.display = 'none';
}
document.querySelector('.btn-new').addEventListener('click', init);
init();
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<link href="https://fonts.googleapis.com/css?family=Lato:100,300,600" rel="stylesheet" type="text/css">
<link href="http://code.ionicframework.com/ionicons/2.0.1/css/ionicons.min.css" rel="stylesheet" type="text/css">
<link type="text/css" rel="stylesheet" href="style.css">
<title>Pig Game</title>
</head>
<body>
<div class="wrapper clearfix">
<div class="player-0-panel active">
<div class="player-name" id="name-0">Player 1</div>
<div class="player-score" id="score-0">43</div>
<div class="player-current-box">
<div class="player-current-label">Current</div>
<div class="player-current-score" id="current-0">11</div>
</div>
</div>
<div class="player-1-panel">
<div class="player-name" id="name-1">Player 2</div>
<div class="player-score" id="score-1">72</div>
<div class="player-current-box">
<div class="player-current-label">Current</div>
<div class="player-current-score" id="current-1">0</div>
</div>
</div>
<button class="btn-new"><i class="ion-ios-plus-outline"></i>New game</button>
<button class="btn-roll"><i class="ion-ios-loop"></i>Roll dice</button>
<button class="btn-hold"><i class="ion-ios-download-outline"></i>Hold</button>
<input type="text" placeholder="Final Score" class="final-score">
<img src="dice-5.png" alt="Dice" class="dice">
</div>
<script type='text/javascript' src="challenges.js"></script>
</body>
</html>
/**********************************************
*** GENERAL
**********************************************/
.final-score {
position: absolute;
left: 50%;
transform: translateX(-50%);
top: 520px;
color: #555;
font-size: 18px;
font-family: 'Lato';
text-align: center;
padding: 10px;
width: 160px;
text-transform: uppercase;
}
.final-score:focus { outline: none; }
dice-1 { top: 120px; }
#dice-2 { top: 250px; }
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
.clearfix::after {
content: "";
display: table;
clear: both;
}
body {
background-image: linear-gradient(rgba(62, 20, 20, 0.4), rgba(62, 20, 20, 0.4)), url(back.jpg);
background-size: cover;
background-position: center;
font-family: Lato;
font-weight: 300;
position: relative;
height: 100vh;
color: #555;
}
.wrapper {
width: 1000px;
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
background-color: #fff;
box-shadow: 0px 10px 50px rgba(0, 0, 0, 0.3);
overflow: hidden;
}
.player-0-panel,
.player-1-panel {
width: 50%;
float: left;
height: 600px;
padding: 100px;
}
/**********************************************
*** PLAYERS
**********************************************/
.player-name {
font-size: 40px;
text-align: center;
text-transform: uppercase;
letter-spacing: 2px;
font-weight: 100;
margin-top: 20px;
margin-bottom: 10px;
position: relative;
}
.player-score {
text-align: center;
font-size: 80px;
font-weight: 100;
color: #EB4D4D;
margin-bottom: 130px;
}
.active { background-color: #f7f7f7; }
.active .player-name { font-weight: 300; }
.active .player-name::after {
content: "\2022";
font-size: 47px;
position: absolute;
color: #EB4D4D;
top: -7px;
right: 10px;
}
.player-current-box {
background-color: #EB4D4D;
color: #fff;
width: 40%;
margin: 0 auto;
padding: 12px;
text-align: center;
}
.player-current-label {
text-transform: uppercase;
margin-bottom: 10px;
font-size: 12px;
color: #222;
}
.player-current-score {
font-size: 30px;
}
button {
position: absolute;
width: 200px;
left: 50%;
transform: translateX(-50%);
color: #555;
background: none;
border: none;
font-family: Lato;
font-size: 20px;
text-transform: uppercase;
cursor: pointer;
font-weight: 300;
transition: background-color 0.3s, color 0.3s;
}
button:hover { font-weight: 600; }
button:hover i { margin-right: 20px; }
button:focus {
outline: none;
}
i {
color: #EB4D4D;
display: inline-block;
margin-right: 15px;
font-size: 32px;
line-height: 1;
vertical-align: text-top;
margin-top: -4px;
transition: margin 0.3s;
}
.btn-new { top: 45px;}
.btn-roll { top: 403px;}
.btn-hold { top: 467px;}
.dice {
position: absolute;
left: 50%;
top: 178px;
transform: translateX(-50%);
height: 100px;
box-shadow: 0px 10px 60px rgba(0, 0, 0, 0.10);
}
.winner { background-color: #f7f7f7; }
.winner .player-name { font-weight: 300; color: #EB4D4D; }
Please help me.
İn javascript , remove init(); or define init function.
try this:
function init() {
scores = [0, 0];
activePlayer = 0;
roundScore = 0;
gamePlaying = true;
document.getElementById('dice-1').style.display = 'none';
document.getElementById('dice-2').style.display = 'none';
document.getElementById('score-0').textContent = '0';
document.getElementById('score-1').textContent = '0';
document.getElementById('current-0').textContent = '0';
document.getElementById('current-1').textContent = '0';
document.getElementById('name-0').textContent = 'Player 1';
document.getElementById('name-1').textContent = 'Player 2';
document.querySelector('.player-0-panel').classList.remove('winner');
document.querySelector('.player-1-panel').classList.remove('winner');
document.querySelector('.player-0-panel').classList.remove('active');
document.querySelector('.player-1-panel').classList.remove('active');
document.querySelector('.player-0-panel').classList.add('active');
}
document.querySelector('.btn-roll').addEventListener('click', function() {
if(gamePlaying) {
var dice1 = Math.floor(Math.random() * 6) + 1;
var dice2 = Math.floor(Math.random() * 6) + 1;
document.getElementById('dice-1').style.display = 'block';
document.getElementById('dice-2').style.display = 'block';
document.getElementById('dice-1').src = 'dice-' + dice1 + '.png';
document.getElementById('dice-2').src = 'dice-' + dice2 + '.png';
if (dice1 !== 1 && dice2 !== 1) {
roundScore += dice1 + dice2;
document.querySelector('#current-' + activePlayer).textContent = roundScore;
} else {
nextPlayer();
}
}
});
document.querySelector('.btn-hold').addEventListener('click', function() {
if (gamePlaying) {
scores[activePlayer] += roundScore;
document.querySelector('#score-' + activePlayer).textContent = scores[activePlayer];
var input = document.querySelector('.final-score').value;
var winningScore;
if(input) {
winningScore = input;
} else {
winningScore = 100;
}
// Check if player won the game
if (scores[activePlayer] >= winningScore) {
document.querySelector('#name-' + activePlayer).textContent = 'Winner!';
document.getElementById('dice-1').style.display = 'none';
document.getElementById('dice-2').style.display = 'none';
document.querySelector('.player-' + activePlayer + '-panel').classList.add('winner');
document.querySelector('.player-' + activePlayer + '-panel').classList.remove('active');
gamePlaying = false;
} else {
nextPlayer();
}
}
});
function nextPlayer() {
activePlayer === 0 ? activePlayer = 1 : activePlayer = 0;
roundScore = 0;
document.getElementById('current-0').textContent = '0';
document.getElementById('current-1').textContent = '0';
document.querySelector('.player-0-panel').classList.toggle('active');
document.querySelector('.player-1-panel').classList.toggle('active');
document.getElementById('dice-1').style.display = 'none';
document.getElementById('dice-2').style.display = 'none';
}
document.querySelector('.btn-new').addEventListener('click', init);
function init(){
}
I don't see any HTML elements with id="dice-1" nor id="dice-2", which would explain the error you're receiving.
I don't see element with id="dice-1" or id="dice-2" in your template (HTML), so the error just means, that element with that id doesn't exist, so it's value is null.

Unable to add text into slideshow li element

I am unable to add text into slideshow li element. Its not my slideshow i downloaded it from codepen https://codepen.io/team/moderndeveloper/pen/MKgqzq?q=imageslider&limit=team&team_name=moderndeveloper . When i add some text into li element entire slideshow disappear. I tried to add div into li element but nothing help. So, is there any solution for this?
HTML
<div class="ImageSlider">
<div class="ImageSlider-scroller">
<ul class="ImageSlider-items">
<li class="ImageSlider-item" style="background-image: url(https://farm6.staticflickr.com/5076/14164379250_71c3a5b32a_b.jpg);"></li>
<li class="ImageSlider-item" style="background-image: url(https://farm3.staticflickr.com/2937/14371160993_186df4a083_b.jpg);"></li>
<li class="ImageSlider-item" style="background-image: url(https://farm3.staticflickr.com/2914/14185397280_e51c40b1df_b.jpg);"></li>
</ul>
<nav class="ImageSlider-indicators">
</nav>
</div>
</div>
CSS
body {
margin: 0;
}
.ImageSlider {
display: flex;
align-items: stretch;
}
.ImageSlider-button {
width: 40px;
border: none;
background: transparent;
color: #000000;
font-size: 40px;
text-align: center;
outline: none;
opacity: 0.5;
transition: opacity 300ms ease-out;
}
.ImageSlider-button:hover {
opacity: 1;
}
.ImageSlider-scroller {
flex: 1;
overflow: hidden;
position: relative;
}
.ImageSlider-items {
margin: 0;
padding: 0;
list-style: none;
white-space: nowrap;
font-size: 0;
line-height: 0;
transition: transform 0.6s cubic-bezier(1, 0, 0, 1);
}
.ImageSlider-item {
display: inline-block;
padding-bottom: 31.25%;
width: 100%;
height: 100%;
background-size: cover;
background-position: 50% 50%;
}
.ImageSlider-indicators {
list-style: none;
padding: 0;
position: absolute;
bottom: 0;
left: 0;
right: 0;
display: block;
text-align: right;
padding: 40px 140px;
font-size: 0;
}
.ImageSlider-indicator {
display: inline-block;
text-decoration: none;
color: #FFFFFF;
font-weight: bold;
border: 2px solid #FFFFFF;
width: 14px;
height: 14px;
border-radius: 16px;
margin: 0 4px;
background-color: rgba(255, 255, 255, 0);
transition: background-color 0.4s ease-in-out;
}
.ImageSlider-indicator:hover,
.ImageSlider-indicator--is-active {
background-color: #FFFFFF;
}
JS
/* global Modernizr */
if (!Object.assign) {
Object.defineProperty(Object, 'assign', {
enumerable: false,
configurable: true,
writable: true,
value: function(target) {
'use strict';
if (target === undefined || target === null) {
throw new TypeError('Cannot convert first argument to object');
}
var to = Object(target);
for (var i = 1; i < arguments.length; i++) {
var nextSource = arguments[i];
if (nextSource === undefined || nextSource === null) {
continue;
}
nextSource = Object(nextSource);
var keysArray = Object.keys(nextSource);
for (var nextIndex = 0, len = keysArray.length; nextIndex < len; nextIndex++) {
var nextKey = keysArray[nextIndex];
var desc = Object.getOwnPropertyDescriptor(nextSource, nextKey);
if (desc !== undefined && desc.enumerable) {
to[nextKey] = nextSource[nextKey];
}
}
}
return to;
}
});
}
(function(window, document, Modernizr) {
"use strict";
var d = document;
var transform = Modernizr.prefixed('transform');
function ImageSliderIndicators(imageSlider, options) {
this.imageSlider = imageSlider;
this.options = Object.assign({}, ImageSliderIndicators.DEFAULTS, options || {});
this.el = d.querySelector('.' + this.options.indicatorsClass);
this.indicators = [].slice.call(d.querySelectorAll('.' + this.options.indicatorClass));
this.imageSlider.el.addEventListener('positionChanged', this.onPositionChanged.bind(this));
this.el.addEventListener('click', this.onIndicatorClick.bind(this), false);
this.onPositionChanged();
}
ImageSliderIndicators.DEFAULTS = {
indicatorsClass: 'ImageSlider-indicators',
indicatorClass: 'ImageSlider-indicator',
indicatorActiveClass: 'ImageSlider-indicator--is-active'
};
ImageSliderIndicators.prototype.onIndicatorClick = function onIndicatorClick(event) {
var position = this.indicators.indexOf(event.target);
if (position !== -1) {
this.imageSlider.goto(position);
}
};
ImageSliderIndicators.prototype.onPositionChanged = function onPositionChanged() {
var self = this;
this.indicators.forEach(function(element, index) {
var action = index === self.imageSlider.position ? 'add' : 'remove';
element.classList[action](self.options.indicatorActiveClass);
});
};
function ImageSlider(options) {
this.options = Object.assign({}, ImageSlider.DEFAULTS, options || {});
this.position = 0;
this.el = d.querySelector('.' + this.options.imageSliderClass);
this.items = d.querySelector('.' + this.options.itemsClass);
this.itemCount = d.querySelectorAll('.' + this.options.itemClass).length;
this.scroller = d.querySelector('.' + this.options.scrollerClass);
this.previousButton = d.querySelector('.' + this.options.previousButtonClass);
this.nextButton = d.querySelector('.' + this.options.nextButtonClass);
this.indicators = new ImageSliderIndicators(this, this.options.indicators);
window.addEventListener('resize', this.render.bind(this));
this.nextButton && this.nextButton.addEventListener('click', this.next.bind(this));
this.previousButton && this.previousButton.addEventListener('click', this.previous.bind(this));
}
ImageSlider.DEFAULTS = {
imageSliderClass: 'ImageSlider',
itemsClass: 'ImageSlider-items',
itemClass: 'ImageSlider-item',
scrollerClass: 'ImageSlider-scroller',
previousButtonClass: 'js-ImageSlider-button--previous',
nextButtonClass: 'js-ImageSlider-button--next'
};
ImageSlider.prototype.render = function render() {
this.items.style[transform] = 'translate3d(' + (-this.position * this.items.offsetWidth) + 'px,0,0)';
};
ImageSlider.prototype.goto = function goto(position) {
var event = d.createEvent('Event');
event.initEvent('positionChanged', true, true);
this.position = position;
this.el.dispatchEvent(event);
this.render();
};
ImageSlider.prototype.previous = function previous() {
this.goto((this.position + (this.itemCount - 1)) % this.itemCount);
};
ImageSlider.prototype.next = function next() {
this.goto((this.position + 1) % this.itemCount);
};
window.ImageSlider = ImageSlider;
}).call(this, window, window.document, Modernizr);
new ImageSlider();
Durinko.
The slideshow doesn't disappear. The content is pushed down.
The secret is in the CSS code.
Try this:
HTML
<li class="ImageSlider-item" style="background-image: url(https://farm6.staticflickr.com/5076/14164379250_71c3a5b32a_b.jpg);"><p>Some Text</p></li>
CSS:
p {
position: absolute;
font-size: 30px;
}

How do I make my jquery game's gameboard responsive?

I'm trying to create a game using Jquery however I have an issue when trying to make the webpage responsive. The issue is that I'm unable to make my game-board "spelplan" responsive, I know the reason this happens is because parts of my script is connected to the "width" of the game-board so when I remove the "width" and replace it with <div id="spelplan" class="col-6 col-m-6"> these parts get completely messed up. So what I need help with is how I make my game-board "spelplan" responsive, I would really appreciate any help I can get with this.
function updateClock() {
var currentTime = new Date();
var currentHours = currentTime.getHours();
var currentMinutes = currentTime.getMinutes();
var currentSeconds = currentTime.getSeconds();
currentMinutes = (currentMinutes < 10 ? "0" : "") + currentMinutes;
currentSeconds = (currentSeconds < 10 ? "0" : "") + currentSeconds;
var timeOfDay = (currentHours < 12) ? "AM" : "PM";
currentHours = (currentHours > 12) ? currentHours - 12 : currentHours;
currentHours = (currentHours == 0) ? 12 : currentHours;
var currentTimeString = currentHours + ":" + currentMinutes + ":" + currentSeconds + " " + timeOfDay;
document.getElementById("clock").firstChild.nodeValue = currentTimeString;
}
* {
box-sizing: border-box;
margin: 0;
padding: 0;
}
body {
background-color: black;
}
header {
position: absolute;
top: 50px;
color: white;
text-align: center;
}
#clock {
font-size: 25px;
position: absolute;
color: white;
}
#rand_pos {
position: absolute;
top: 20%;
left: 30%;
z-index: 10;
}
.player {
background-color: red;
height: 50px;
width: 50px;
position: absolute;
top: 100px;
left: 100px;
z-index: 100;
}
p {
position: relative;
left: 10px;
color: white;
}
#spelplan {
position: relative;
left: 35%;
top: 200px;
height: 600px;
width: 600px;
background-color: blue;
border-style: double;
border-radius: 40px;
}
.rand {
background-color: green;
height: 15px;
width: 15px;
position: absolute;
left: 30%;
top: 150px;
z-index: 3;
}
.new_pos {
background: #ccc;
border: 1px solid #000;
padding: 5px;
box-shadow: 0 0 20px #555;
-webkit-transition: all .2s ease-in;
transition: all .2s ease-in;
}
.new_pos:hover {
background: #bbb;
box-shadow: 0 0 20px #222;
}
.new_pos:active {
box-shadow: 0 0 20px #000;
background: #aaa;
}
*:focus {
outline: none;
}
.new_pos {
position: fixed;
left: 0;
bottom: 0;
cursor: pointer;
}
#footer {
position: absolute;
top: 80vh;
color: white;
text-align: center;
}
/* For mobile phones: */
[class*="col-"] {
width: 100%;
}
#media only screen and (min-width: 600px) {
/* For tablets: */
.col-m-1 {
width: 8.33%;
}
.col-m-2 {
width: 16.66%;
}
.col-m-3 {
width: 25%;
}
.col-m-4 {
width: 33.33%;
}
.col-m-5 {
width: 41.66%;
}
.col-m-6 {
width: 50%;
}
.col-m-7 {
width: 58.33%;
}
.col-m-8 {
width: 66.66%;
}
.col-m-9 {
width: 75%;
}
.col-m-10 {
width: 83.33%;
}
.col-m-11 {
width: 91.66%;
}
.col-m-12 {
width: 100%;
}
img {
width: 80%;
height: auto;
}
}
#media only screen and (min-width: 768px) {
/* For desktop: */
.col-1 {
width: 8.33%;
}
.col-2 {
width: 16.66%;
}
.col-3 {
width: 25%;
}
.col-4 {
width: 33.33%;
}
.col-5 {
width: 41.66%;
}
.col-6 {
width: 50%;
}
.col-7 {
width: 58.33%;
}
.col-8 {
width: 66.66%;
}
.col-9 {
width: 75%;
}
.col-10 {
width: 83.33%;
}
.col-11 {
width: 91.66%;
}
.col-12 {
width: 100%;
}
img {
width: 100%;
height: auto;
}
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta charset="utf-8">
<link rel="stylesheet" type="text/css" href="style20.css">
<script type='text/javascript' src='eventjavascript6.js'></script>
<title>Jquery spel</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script>
$(document).ready(function() {
var sprites = [];
var enemies = [];
var game = $("#spelplan");
var score = 0;
var el_score = $("#score")
function SCORE(pts) {
score += pts
el_score.text(score);
}
function RND(min, max) {
return parseInt(Math.random() * (max - min) + min);
}
var sprite = function(id, x, y, w, h, _class, view, collisionDetect, options) {
this.view = view;
this.id = id
this.x = x + "px";
this.y = y + "px";
this.width = w;
this.height = h;
this.options = options;
this.el = $("<div id='" + this.id + "' class='" + _class + "'></div>").css('left', this.x).css('top', this.y);
view.append(this.el);
this.x = function() {
return this.el.position().left;
}
this.y = function() {
return this.el.position().top;
}
this.up = function() {
if (this.y() > 0) {
this.el.animate({
top: '-=25px'
}, 0);
if (collisionDetect) collisionDetect(this);
}
};
this.down = function() {
if (this.y() < this.view.height() - this.height) {
this.el.animate({
top: '+=25px'
}, 0);
if (collisionDetect) collisionDetect(this);
}
};
this.left = function() {
if (this.x() > 0) {
this.el.animate({
left: '-=25px'
}, 0);
if (collisionDetect) collisionDetect(this);
}
};
this.right = function() {
if (this.x() + this.width < this.view.width()) {
this.el.animate({
left: '+=25px'
}, 0);
if (collisionDetect) collisionDetect(this);
}
this.destroy = function() {
this.el.remove();
for (var i = 0; i < sprites.length; i++) {
if (data[i].id == this.id) {
sprites.splice(i, 1);
break;
}
}
}
};
this.getPos = function() {
var pos, width, height;
pos = this.el.position();
width = this.el.width();
height = this.el.height();
return [
[pos.left, pos.left + width],
[pos.top, pos.top + height]
];
};
this.comparePos = function(p1, p2) {
var r1, r2;
r1 = p1[0] < p2[0] ? p1 : p2;
r2 = p1[0] < p2[0] ? p2 : p1;
return r1[1] > r2[0] || r1[0] === r2[0];
};
this.collidesWith = function(sprite) {
if (sprite.destroyed === true) return;
var pos1 = this.getPos(),
pos2 = sprite.getPos();
return this.comparePos(pos1[0], pos2[0]) && this.comparePos(pos1[1], pos2[1]);
};
if (this.options && this.options.init) this.options.init(this);
sprites.push(this);
};
function spawnrand() {
if (sprites.length > 100) return
var points = [50, 100, 200, 300, 400, 500];
var spelplanWidth = game.width();
var spelplanHeight = game.height();
var randPosY = Math.floor((Math.random() * spelplanHeight));
var randPosX = Math.floor((Math.random() * spelplanWidth));
var enemy = new sprite("enemy" + sprites.length + 1, randPosY, randPosX, 15, 15, "rand", game, null, {
PTS: points[RND(0, 5)],
init: function(sprite) {
sprite.selfDestruct = setTimeout(function() {
sprite.el.fadeOut(1000, function() {});
}, 5000);
}
});
enemies.push(enemy);
}
SCORE(0);
var player = new sprite("box1", 200, 200, 50, 50, "player", game,
function(sprite) {
sprites.forEach(function(sprite) {
if (sprite.id !== "box1" && player.collidesWith(sprite)) {
sprite.destroyed = true;
clearTimeout(sprite.selfDestruct);
sprite.el.fadeOut(100, function() {});
SCORE(sprite.options.PTS);
}
})
});
setInterval(spawnrand, 250);
$(document).keydown(function(e) {
if (e.keyCode == 37) {
player.left();
} else if (e.keyCode == 39) {
player.right();
} else if (e.keyCode == 38) {
player.up();
} else if (e.keyCode == 40) {
player.down();
}
});
});
</script>
</head>
<body onload="updateClock(); setInterval('updateClock()', 1000 )">
<span id="clock"> </span>
<header class="col-12 col-m-12">
<h1>Samla så mycket poäng du hinner genom att ta de gröna bollarna innan de försvinner</h1>
</header>
<div id="spelplan" class="col-6 col-m-6">
<div>
<p>Score:<span id="score"></span></p>
</div>
</div>
<section id="footer" class="col-12 col-m-12">
<h1>Använd piltangenterna för att styra den röda kuben </h1>
</section>
</body>
</html>
So again what I need help with is making the game-board "spelplan" responsive, any help is appreciated!

how to change image in JavaScript using an array of image sources

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>

JS slider tooltip

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;
}

Categories

Resources