Custom divs with right arrow shape - javascript

Please I need I help on how to implement something like this responsively using bootstrap
html code for is displayed below
<div class="wrapper">
<div class="container">
<div class="special">
<div id="counter">
<div id="shading"></div>
</div>
</div>
</div>
please below is the css file for the above html code
.special
{
position: relative;
width: 840px;
height: 247px;
background-image: url('https://www.jqueryscript.net/demo/Colorful-Countdown-Timer/images/special_offer_bg.png');
background-position: -10px 74px;
background-repeat: no-repeat;
}
#counter
{
position: absolute;
top: 135px;
left: 279px;
z-index: 4000;
}
.digit-separator
{
position: relative;
float: left;
width: 17px;
height: 44px;
overflow: hidden;
background-image: url('https://www.jqueryscript.net/demo/Colorful-Countdown-Timer/images/digit_separator.png');
background-repeat: no-repeat;
background-position: 0px 0px;
}
.digit
{
background-image: url('https://www.jqueryscript.net/demo/Colorful-Countdown-Timer/images/digits.png');
}
#shading
{
background-image: url('https://www.jqueryscript.net/demo/Colorful-Countdown-Timer/images/sprites.png');
background-position: 0px -396px;
background-repeat: repeat-x;
float: left;
height: 44px;
position: absolute;
width: 291px;
z-index: 4100;
top: 0;
left: 0;
}
please this is the JavaScript code for the above html code
function C3Counter(id, opt) {
this.options = {
stepTime: 60, // not used
format: "dd:hh:mm:ss", // not used
startTime: "01:04:40:59",
digitImages: 1,
digitWidth: 30,
digitHeight: 44,
digitSlide : true,
digitSlideTime : 200,
digitImageHeight : 484,
digitAnimationHeight : 44,
timerEnd: function(){},
image: "digits.png",
updateInterval : 1000
};
var s;
if (typeof opt != "undefined") {
for (s in this.options) {
if (typeof opt[s] != "undefined") {
this.options[s] = opt[s];
}
}
}
if (String(options.startTime).indexOf(":") == -1) {
options.tempStartTime = options.startTime;
} else {
//TODO - does not convert time with : to seconds to count
var td = new Date(options.startTime);
}
this.pad2 = function(number) {
return (number < 10 ? '0' : '') + number;
}
var timer = setInterval( "this.updateCounter()", options.updateInterval);
var startTime = new Date().getTime();
var secNo = 0;
var timerSingle = new Array();
var dc = 0;
var digits = new Array();
var d = new Date();
var lastTime = d.getTime();
this.calculateTime = function() {
var tempTime = options.tempStartTime;
if (String(options.tempStartTime).indexOf(":") == -1) {
var seconds=Math.round(options.tempStartTime % 60);
options.tempStartTime=Math.floor(options.tempStartTime/60);
var minutes=Math.round(options.tempStartTime % 60);
options.tempStartTime=Math.floor(options.tempStartTime/60);
var hours=Math.round(options.tempStartTime % 24);
options.tempStartTime=Math.floor(options.tempStartTime/24);
var days=Math.round(options.tempStartTime);
options.timeStr = this.pad2(days)+this.pad2(hours)+this.pad2(minutes)+this.pad2(seconds);
}
var currTime = new Date().getTime();
var diff = currTime - startTime;
options.tempStartTime = options.startTime - Math.round(diff/1000);
}
this.calculateTime();
for (dc=0; dc<8; dc++) {
digits[dc] = { digit: this.options.timeStr.charAt(dc)};
$("#"+id).append("<div id='digit"+dc+"' style='position:relative;float:left;width:"+this.options.digitWidth+"px;height:"+this.options.digitHeight+"px;overflow:hidden;'><div class='digit' id='digit-bg"+dc+"' style='position:absolute; top:-"+digits[dc].digit*this.options.digitAnimationHeight+"px; width:"+this.options.digitWidth+"px; height:"+this.options.digitImageHeight+"px; '></div></div>");
if (dc % 2 == 1 && dc < 6) {
$("#"+id).append("<div class='digit-separator' style='float:left;'></div>");
}
}
$("#"+id).append("<div style='clear:both'></div>");
this.animateDigits = function() {
for (var dc=0; dc<8; dc++) {
digits[dc].digitNext = Number(this.options.timeStr.charAt(dc));
digits[dc].digitNext = (digits[dc].digitNext + 10)%10;
var no = dc;
if (digits[no].digit == 0) $("#digit-bg"+no).css("top", -this.options.digitImageHeight+this.options.digitHeight + "px");
if (digits[no].digit != digits[no].digitNext) {
$("#digit-bg"+no).animate( { "top" : -digits[no].digitNext*options.digitHeight+"px"}, options.digitSlideTime);
digits[no].digit = digits[no].digitNext;
}
}
var end = this.checkEnd();
}
this.checkEnd = function() {
for (var i = 0; i < digits.length; i++) {
if (digits[i].digit != 0) {
return false;
}
}
clearInterval(timer);
this.options.timerEnd();
return true;
}
this.updateCounter = function() {
d = new Date();
if ((d.getTime() - lastTime) < (options.updateInterval - 50)) {
return;
}
lastTime = d.getTime();
this.calculateTime();
this.animateDigits();
}
}
C3Counter("counter", { startTime :16100 });

Note* you need to use Bootstrap v3.3.4 or higher and jQuery v2.1.3 or higher
Note* This doesnt look like the exact example you linked to. Its not posible to achieve that with default boostrap library.
html:
<div class="wrapper">
<div class="special">
<span id="clock"></span>
</div>
</div>
js:
$('#clock').countdown('2020/10/10', function(event) {
$(this).html(event.strftime('%D days %H:%M:%S'));
});
css:
.wrapper
{
width: 100%;
height: auto;
background-color: #dc403b;
}
.special
{
width:100%;
background-image: url('https://www.jqueryscript.net/demo/Colorful-Countdown-Timer/images/special_offer_bg.png');
background-position: cover;
background-repeat: no-repeat;
text-align: center;
padding: 50px 0;
font-size: 18px;
}

Related

A div is bigger than what I made it

I am making a John Conway's game of life and when I try run it by pressing space, it is actually bigger than what the console shows it to be. I set the div to be exactly 0.1% of the bigger grid which is in dark blue. But it seems to just be bigger or smaller. I also use panning and zooming for the project
//Important variable
var mainGrid = document.querySelector(".main-grid")
var windowWidth = document.documentElement.clientWidth
var windowHeight = document.documentElement.clientHeight
var time = 500
var Data = {
livingCells: [
[3,0],
[5,0],
[4,1],
[5,1]
]
}
//functions
var updateCells = (rle) => {
if (!rle) {
$(".main-grid").empty()
for (let i = 0; i < Data.livingCells.length; i++) {
const element = Data.livingCells[i];
$(".main-grid").append('<div id="'+i+'" class="on"></div>')
$('#'+i+'').css({ 'left': element[0]/10+'%', 'top': element[1]/10+'%' ,})
console.log(element[1])
}
}
}
var ID;
var cellInterval = () => {
ID = setInterval(() => {
updateCells()
}, time)
}
var intervalOn = false;
//listeners
document.body.onkeyup = function(e) {
if (e.key == " " ||
e.code == "Space" ||
e.keyCode == 32
) {
if(!intervalOn){
cellInterval()
intervalOn = true;
console.log("interval on")
} else {
clearInterval(ID)
intervalOn = false;
console.log("interval off")
}
}
}
// panzoom
panzoom(mainGrid, {
minZoom: 0.3,
maxZoom: 10,
initialZoom: 1.5,
initialX: mainGrid.offsetWidth/2,
initialY: mainGrid.offsetWidth,
bounds: true,
boundsPadding: 0.3
});
* {
padding: 0;
margin: 0;
outline: 0;
overflow: hidden;
}
html, body {
margin: 0;
padding: 0;
width: 100%;
height: 100%;
overflow: hidden;
background-color: gray;
}
.main-grid{
width: 100vw;
height: 100vw;
background-color: rgb(0, 0, 0);
}
.hover:hover{
transition: 0.3s;
background-color: rgb(79, 124, 182);
transform: scale(1.2);
}
.on{
position: fixed;
height: 0.1%;
width: 0.1%;
background-color: white;
}
<body>
<div class="main-grid">
</div>
<script src="https://code.jquery.com/jquery-3.6.0.min.js" integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4="crossorigin="anonymous"></script>
<script src='https://unpkg.com/panzoom#9.4.0/dist/panzoom.min.js'></script>
<script src="app.js"></script>
</body>
Have you tried Include
{
box-sizing: border-box;
}

How to make this picture slider puzzle start shuffling without button press?

Goodday Coders, Im struggling with this puzzle script that I want to use for a website's "meet the team" page.
I would like the puzzle to scramble as the page loads instead of having to press the shuffle button.
If people press the "Wie ben ik" button, the puzzle should solve, like it is doing right now.
Somehow I cant get it to work, it would be great if someone could help me out.
Here's the codepen link:
https://codepen.io/verberne/pen/WNxyprV
// Begin game once DOM loaded
document.addEventListener("DOMContentLoaded", game);
// document.addEventListener("DOMContentLoaded", shuffleTimeouts);
function game() {
// Data structure to hold positions of tiles
var parentX = document.querySelector(".sliding-puzzle").clientHeight;
var baseDistance = 38;
var tileMap = {
1: {
tileNumber: 1,
position: 1,
top: 0,
left: 0
},
2: {
tileNumber: 2,
position: 2,
top: 0,
left: baseDistance * 1
},
3: {
tileNumber: 3,
position: 3,
top: 0,
left: baseDistance * 2
},
4: {
tileNumber: 4,
position: 4,
top: baseDistance,
left: 0
},
5: {
tileNumber: 5,
position: 5,
top: baseDistance,
left: baseDistance
},
6: {
tileNumber: 6,
position: 6,
top: baseDistance,
left: baseDistance * 2
},
7: {
tileNumber: 7,
position: 7,
top: baseDistance * 2,
left: 0
},
8: {
tileNumber: 8,
position: 8,
top: baseDistance * 2,
left: baseDistance
},
empty: {
position: 9,
top: baseDistance * 2,
left: baseDistance * 2
}
}
// Array of tileNumbers in order of last moved
var history = [];
// Movement map
function movementMap(position) {
if (position == 9) return [6, 8];
if (position == 8) return [5, 7, 9];
if (position == 7) return [4, 8];
if (position == 6) return [3, 5, 9];
if (position == 5) return [2, 4, 6, 8];
if (position == 4) return [1, 5, 7];
if (position == 3) return [2, 6];
if (position == 2) return [1, 3, 5];
if (position == 1) return [2, 4];
}
// Board setup according to the tileMap
document.querySelector('#shuffle').addEventListener('click', shuffle, true);
document.querySelector('#solve').addEventListener('click', solve, true);
var tiles = document.querySelectorAll('.tile');
var delay = -50;
for (var i = 0; i < tiles.length; i++) {
tiles[i].addEventListener('click', tileClicked, true);
var tileId = tiles[i].innerHTML;
delay += 50;
setTimeout(setup, delay, tiles[i]);
}
function setup(tile) {
var tileId = tile.innerHTML;
// tile.style.left = tileMap[tileId].left + '%';
// tile.style.top = tileMap[tileId].top + '%';
var xMovement = parentX * (tileMap[tileId].left / 100);
var yMovement = parentX * (tileMap[tileId].top / 100);
var translateString = "translateX(" + xMovement + "px) " + "translateY(" + yMovement + "px)"
tile.style.webkitTransform = translateString;
recolorTile(tile, tileId);
}
function tileClicked(event) {
var tileNumber = event.target.innerHTML;
moveTile(event.target);
if (checkSolution()) {
console.log("You win!");
}
}
// Moves tile to empty spot
// Returns error message if tile cannot be moved
function moveTile(tile, recordHistory = true) {
// Check if Tile can be moved
// (must be touching empty tile)
// (must be directly perpendicular to empty tile)
var tileNumber = tile.innerHTML;
if (!tileMovable(tileNumber)) {
console.log("Tile " + tileNumber + " can't be moved.");
return;
}
// Push to history
if (recordHistory == true) {
if (history.length >= 3) {
if (history[history.length - 1] != history[history.length - 3]) history.push(tileNumber);
} else {
history.push(tileNumber);
}
}
// Swap tile with empty tile
var emptyTop = tileMap.empty.top;
var emptyLeft = tileMap.empty.left;
var emptyPosition = tileMap.empty.position;
tileMap.empty.top = tileMap[tileNumber].top;
tileMap.empty.left = tileMap[tileNumber].left;
tileMap.empty.position = tileMap[tileNumber].position;
// tile.style.top = emptyTop + '%';
// tile.style.left = emptyLeft + '%';
var xMovement = parentX * (emptyLeft / 100);
var yMovement = parentX * (emptyTop / 100);
var translateString = "translateX(" + xMovement + "px) " + "translateY(" + yMovement + "px)"
tile.style.webkitTransform = translateString;
tileMap[tileNumber].top = emptyTop;
tileMap[tileNumber].left = emptyLeft;
tileMap[tileNumber].position = emptyPosition;
recolorTile(tile, tileNumber);
}
// Determines whether a given tile can be moved
function tileMovable(tileNumber) {
var selectedTile = tileMap[tileNumber];
var emptyTile = tileMap.empty;
var movableTiles = movementMap(emptyTile.position);
if (movableTiles.includes(selectedTile.position)) {
return true;
} else {
return false;
}
}
// Returns true/false based on if the puzzle has been solved
function checkSolution() {
if (tileMap.empty.position !== 9) return false;
for (var key in tileMap) {
if ((key != 1) && (key != "empty")) {
if (tileMap[key].position < tileMap[key - 1].position) return false;
}
}
// Clear history if solved
history = [];
return true;
}
// Check if tile is in correct place!
function recolorTile(tile, tileId) {
if (tileId == tileMap[tileId].position) {
tile.classList.remove("error");
} else {
tile.classList.add("error");
}
}
// Shuffles the current tiles
shuffleTimeouts = [];
function shuffle() {
clearTimers(solveTimeouts);
var boardTiles = document.querySelectorAll('.tile');
var shuffleDelay = 200;
shuffleLoop();
var shuffleCounter = 0;
while (shuffleCounter < 20) {
shuffleDelay += 200;
shuffleTimeouts.push(setTimeout(shuffleLoop, shuffleDelay));
shuffleCounter++;
}
}
var lastShuffled;
function shuffleLoop() {
var emptyPosition = tileMap.empty.position;
var shuffleTiles = movementMap(emptyPosition);
var tilePosition = shuffleTiles[Math.floor(Math.floor(Math.random() * shuffleTiles.length))];
var locatedTile;
for (var i = 1; i <= 8; i++) {
if (tileMap[i].position == tilePosition) {
var locatedTileNumber = tileMap[i].tileNumber;
locatedTile = tiles[locatedTileNumber - 1];
}
}
if (lastShuffled != locatedTileNumber) {
moveTile(locatedTile);
lastShuffled = locatedTileNumber;
} else {
shuffleLoop();
}
}
function clearTimers(timeoutArray) {
for (var i = 0; i < timeoutArray.length; i++) {
clearTimeout(timeoutArray[i])
}
}
// Temporary function for solving puzzle.
// To be reimplemented with a more sophisticated algorithm
solveTimeouts = []
function solve() {
clearTimers(shuffleTimeouts);
repeater = history.length;
for (var i = 0; i < repeater; i++) {
console.log("started");
solveTimeouts.push(setTimeout(moveTile, i * 100, tiles[history.pop() - 1], false));
}
}
}
body {
font-family: 'Roboto Condensed', sans-serif;
font-weight: 700;
font-size: 24px;
background-color: #ECF0F1;
-webkit-tap-highlight-color: transparent;
khtml-tap-highlight-color: transparent;
}
.sliding-puzzle-figure {
margin: auto;
height: 360px;
width: 360px;
padding-bottom: 50vh;
padding-top: 10vh;
}
.sliding-puzzle-figure a {
cursor: pointer;
}
.sliding-puzzle-figure a#shuffle {
color: #E74C3C;
}
.sliding-puzzle-figure a#solve {
color: #3498DB;
}
.sliding-puzzle-figure .sliding-puzzle {
list-style-type: none;
position: relative;
margin-left: 0;
margin-right: 00;
width: 360px;
height: 360px;
box-sizing: border-box;
background-clip: border-box;
/* Firefox 4, Safari 5, Opera 10, IE 9 */
border: 18px solid #2C3E50;
border-radius: 10px;
background-color: #2C3E50;
}
.sliding-puzzle-figure .sliding-puzzle .tile {
position: absolute;
background: url(https://simonwiddowson.typepad.com/files/countryside360x360.jpg);
border-radius: 2px;
cursor: pointer;
width: 120px;
height: 120px;
display: flex;
justify-content: center;
align-items: center;
font-size: 0px;
left: 0%;
top: 0%;
transition: all 0.5s linear;
transition-timing-function: ease;
box-sizing: border-box;
}
.sliding-puzzle-figure .sliding-puzzle .tile.error {
background-color: #F0867D;
}
#tile1 {
background-position: left top;
}
#tile2 {
background-position: center top;
}
#tile3 {
background-position: right top;
}
#tile4 {
background-position: left center;
}
#tile5 {
background-position: center center;
}
#tile6 {
background-position: right center;
}
#tile7 {
background-position: left bottom;
}
#tile8 {
background-position: center bottom;
}
#media only screen and (max-width: 650px) {
.sliding-puzzle-figure {
width: 90vw;
height: 90vw;
max-height: 100vh;
}
.sliding-puzzle-figure .sliding-puzzle {
border-width: 10px;
border-radius: 14px;
}
.sliding-puzzle-figure .tile {
font-size: 1em;
}
}
/*# sourceMappingURL=style.css.map */
<link href="https://fonts.googleapis.com/css?family=Roboto+Condensed:400,700" rel="stylesheet">
<figure class="sliding-puzzle-figure">
<div class="sliding-puzzle">
<div class="tile" id="tile1">1</div>
<div class="tile" id="tile2">2</div>
<div class="tile" id="tile3">3</div>
<div class="tile" id="tile4">4</div>
<div class="tile" id="tile5">5</div>
<div class="tile" id="tile6">6</div>
<div class="tile" id="tile7">7</div>
<div class="tile" id="tile8">8</div>
</div>
<figcaption><br><br> Barry Paling | <a id="shuffle">Shuffle</a> | <a id="solve">Wie ben ik</a>
</figcaption>
</figure>
You call game on load, remove the shuffle click and just call shuffle() at the end of game() :
window.addEventListener("load",game);
function game() {
...
shuffle();
}
window.addEventListener("load",game);
function game() {
// Data structure to hold positions of tiles
var parentX = document.querySelector(".sliding-puzzle").clientHeight;
var baseDistance = 38;
var tileMap = {
1: {
tileNumber: 1,
position: 1,
top: 0,
left: 0
},
2: {
tileNumber: 2,
position: 2,
top: 0,
left: baseDistance * 1
},
3: {
tileNumber: 3,
position: 3,
top: 0,
left: baseDistance * 2
},
4: {
tileNumber: 4,
position: 4,
top: baseDistance,
left: 0
},
5: {
tileNumber: 5,
position: 5,
top: baseDistance,
left: baseDistance
},
6: {
tileNumber: 6,
position: 6,
top: baseDistance,
left: baseDistance * 2
},
7: {
tileNumber: 7,
position: 7,
top: baseDistance * 2,
left: 0
},
8: {
tileNumber: 8,
position: 8,
top: baseDistance * 2,
left: baseDistance
},
empty: {
position: 9,
top: baseDistance * 2,
left: baseDistance * 2
}
}
// Array of tileNumbers in order of last moved
var history = [];
// Movement map
function movementMap(position) {
if (position == 9) return [6, 8];
if (position == 8) return [5, 7, 9];
if (position == 7) return [4, 8];
if (position == 6) return [3, 5, 9];
if (position == 5) return [2, 4, 6, 8];
if (position == 4) return [1, 5, 7];
if (position == 3) return [2, 6];
if (position == 2) return [1, 3, 5];
if (position == 1) return [2, 4];
}
// Board setup according to the tileMap
document.querySelector('#solve').addEventListener('click', solve, true);
var tiles = document.querySelectorAll('.tile');
var delay = -50;
for (var i = 0; i < tiles.length; i++) {
tiles[i].addEventListener('click', tileClicked, true);
var tileId = tiles[i].innerHTML;
delay += 50;
setTimeout(setup, delay, tiles[i]);
}
function setup(tile) {
var tileId = tile.innerHTML;
// tile.style.left = tileMap[tileId].left + '%';
// tile.style.top = tileMap[tileId].top + '%';
var xMovement = parentX * (tileMap[tileId].left / 100);
var yMovement = parentX * (tileMap[tileId].top / 100);
var translateString = "translateX(" + xMovement + "px) " + "translateY(" + yMovement + "px)"
tile.style.webkitTransform = translateString;
recolorTile(tile, tileId);
}
function tileClicked(event) {
var tileNumber = event.target.innerHTML;
moveTile(event.target);
if (checkSolution()) {
console.log("You win!");
}
}
// Moves tile to empty spot
// Returns error message if tile cannot be moved
function moveTile(tile, recordHistory = true) {
// Check if Tile can be moved
// (must be touching empty tile)
// (must be directly perpendicular to empty tile)
var tileNumber = tile.innerHTML;
if (!tileMovable(tileNumber)) {
console.log("Tile " + tileNumber + " can't be moved.");
return;
}
// Push to history
if (recordHistory == true) {
if (history.length >= 3) {
if (history[history.length - 1] != history[history.length - 3]) history.push(tileNumber);
} else {
history.push(tileNumber);
}
}
// Swap tile with empty tile
var emptyTop = tileMap.empty.top;
var emptyLeft = tileMap.empty.left;
var emptyPosition = tileMap.empty.position;
tileMap.empty.top = tileMap[tileNumber].top;
tileMap.empty.left = tileMap[tileNumber].left;
tileMap.empty.position = tileMap[tileNumber].position;
// tile.style.top = emptyTop + '%';
// tile.style.left = emptyLeft + '%';
var xMovement = parentX * (emptyLeft / 100);
var yMovement = parentX * (emptyTop / 100);
var translateString = "translateX(" + xMovement + "px) " + "translateY(" + yMovement + "px)"
tile.style.webkitTransform = translateString;
tileMap[tileNumber].top = emptyTop;
tileMap[tileNumber].left = emptyLeft;
tileMap[tileNumber].position = emptyPosition;
recolorTile(tile, tileNumber);
}
// Determines whether a given tile can be moved
function tileMovable(tileNumber) {
var selectedTile = tileMap[tileNumber];
var emptyTile = tileMap.empty;
var movableTiles = movementMap(emptyTile.position);
if (movableTiles.includes(selectedTile.position)) {
return true;
} else {
return false;
}
}
// Returns true/false based on if the puzzle has been solved
function checkSolution() {
if (tileMap.empty.position !== 9) return false;
for (var key in tileMap) {
if ((key != 1) && (key != "empty")) {
if (tileMap[key].position < tileMap[key - 1].position) return false;
}
}
// Clear history if solved
history = [];
return true;
}
// Check if tile is in correct place!
function recolorTile(tile, tileId) {
if (tileId == tileMap[tileId].position) {
tile.classList.remove("error");
} else {
tile.classList.add("error");
}
}
// Shuffles the current tiles
shuffleTimeouts = [];
function shuffle() {
clearTimers(solveTimeouts);
var boardTiles = document.querySelectorAll('.tile');
var shuffleDelay = 200;
shuffleLoop();
var shuffleCounter = 0;
while (shuffleCounter < 20) {
shuffleDelay += 200;
shuffleTimeouts.push(setTimeout(shuffleLoop, shuffleDelay));
shuffleCounter++;
}
}
var lastShuffled;
function shuffleLoop() {
var emptyPosition = tileMap.empty.position;
var shuffleTiles = movementMap(emptyPosition);
var tilePosition = shuffleTiles[Math.floor(Math.floor(Math.random() * shuffleTiles.length))];
var locatedTile;
for (var i = 1; i <= 8; i++) {
if (tileMap[i].position == tilePosition) {
var locatedTileNumber = tileMap[i].tileNumber;
locatedTile = tiles[locatedTileNumber - 1];
}
}
if (lastShuffled != locatedTileNumber) {
moveTile(locatedTile);
lastShuffled = locatedTileNumber;
} else {
shuffleLoop();
}
}
function clearTimers(timeoutArray) {
for (var i = 0; i < timeoutArray.length; i++) {
clearTimeout(timeoutArray[i])
}
}
// Temporary function for solving puzzle.
// To be reimplemented with a more sophisticated algorithm
solveTimeouts = []
function solve() {
clearTimers(shuffleTimeouts);
repeater = history.length;
for (var i = 0; i < repeater; i++) {
solveTimeouts.push(setTimeout(moveTile, i * 100, tiles[history.pop() - 1], false));
}
}
shuffle()
}
body {
font-family: 'Roboto Condensed', sans-serif;
font-weight: 700;
font-size: 24px;
background-color: #ECF0F1;
-webkit-tap-highlight-color: transparent;
khtml-tap-highlight-color: transparent;
}
.sliding-puzzle-figure {
margin: auto;
height: 360px;
width: 360px;
padding-bottom: 50vh;
padding-top: 10vh;
}
.sliding-puzzle-figure a {
cursor: pointer;
}
.sliding-puzzle-figure a#shuffle {
color: #E74C3C;
}
.sliding-puzzle-figure a#solve {
color: #3498DB;
}
.sliding-puzzle-figure .sliding-puzzle {
list-style-type: none;
position: relative;
margin-left: 0;
margin-right: 00;
width: 360px;
height: 360px;
box-sizing: border-box;
background-clip: border-box;
/* Firefox 4, Safari 5, Opera 10, IE 9 */
border: 18px solid #2C3E50;
border-radius: 10px;
background-color: #2C3E50;
}
.sliding-puzzle-figure .sliding-puzzle .tile {
position: absolute;
background: url(https://simonwiddowson.typepad.com/files/countryside360x360.jpg);
border-radius: 2px;
cursor: pointer;
width: 120px;
height: 120px;
display: flex;
justify-content: center;
align-items: center;
font-size: 0px;
left: 0%;
top: 0%;
transition: all 0.5s linear;
transition-timing-function: ease;
box-sizing: border-box;
}
.sliding-puzzle-figure .sliding-puzzle .tile.error {
background-color: #F0867D;
}
#tile1 {
background-position: left top;
}
#tile2 {
background-position: center top;
}
#tile3 {
background-position: right top;
}
#tile4 {
background-position: left center;
}
#tile5 {
background-position: center center;
}
#tile6 {
background-position: right center;
}
#tile7 {
background-position: left bottom;
}
#tile8 {
background-position: center bottom;
}
#media only screen and (max-width: 650px) {
.sliding-puzzle-figure {
width: 90vw;
height: 90vw;
max-height: 100vh;
}
.sliding-puzzle-figure .sliding-puzzle {
border-width: 10px;
border-radius: 14px;
}
.sliding-puzzle-figure .tile {
font-size: 1em;
}
}
/*# sourceMappingURL=style.css.map */
<link href="https://fonts.googleapis.com/css?family=Roboto+Condensed:400,700" rel="stylesheet">
<figure class="sliding-puzzle-figure">
<div class="sliding-puzzle">
<div class="tile" id="tile1">1</div>
<div class="tile" id="tile2">2</div>
<div class="tile" id="tile3">3</div>
<div class="tile" id="tile4">4</div>
<div class="tile" id="tile5">5</div>
<div class="tile" id="tile6">6</div>
<div class="tile" id="tile7">7</div>
<div class="tile" id="tile8">8</div>
</div>
<figcaption><br><br> Barry Paling | <a id="solve">Wie ben ik</a>
</figcaption>
</figure>

i dont get why the baloons are not moving in the minigame i've built

I've built a small balloon game , trying to learn the foundations,
anyways I've successfully rendered balloons, i can see them both on the page however the move functions doesn't work,it should do so on page load that I've set in the index.html body(the startGame func) , code looks fine,however nothing happens.
var gNextId = 100
var gBaloons = createBalloons()
var gInterval = null
function startGame() {
renderBaloons();
gInterval = setInterval(() => {
moveBalloons();
}, 500);
}
function renderBaloons() {
var strHtml = ''
for (var i = 0; i < gBaloons.length; i++) {
var balloon = gBaloons[i]
strHtml += `
${balloon.txt}
`
}
document.querySelector('.balloon-container').innerHTML = strHtml
}
function moveballoons() {
var elballoons = document.querySelectorAll('.balloon')
for (var i = 0; i > gBaloons.length; i++) {
var balloon = gBaloons[i]
var elballoon = elballoons[i]
balloon.bottom += balloon.speed
elballoon.style.bottom = balloon.bottom + 'px'
}
if (balloon.bottom >= 800) clearInterval(gInterval)
}
function createBalloons() {
var ballons = [
createBalloon('A'),
createBalloon('B'),
createBalloon('C')
];
return ballons
}
function createBalloon(txt) {
return {
id: gNextId++,
bottom: 0,
speed: 45,
txt: txt
}
}
body {
background-color: lightblue;
}
.balloon {
position: absolute;
width: 170px;
height: 200px;
border-radius: 40%;
bottom: 0;
transition: 3s;
background-color: yellow;
text-align: center;
font-weight: bold;
}
.balloon1 {
left: 200px;
background-color: rgb(3, 61, 23);
}
.balloon2 {
left: 600px;
background-color: rgb(182, 24, 50);
}
.fade {
opacity: 0;
}
In the moveballoons() function the following line:
for (var i = 0; i > gBaloons.length; i++) {
Should be
for (var i = 0; i < gBaloons.length; i++) {
Note: I've swapped > with <
I couldn't the get example running, so there could well be other reasons as to why this is not working but that is definitely an issue.

Why does my code not work in Safari or Opera?

There is a function in js which displays messages to the table (messages are stored in json). In Google Chrome, it works, but Safari, Opera or Microsoft Edge - no!
There is a mistake in code which is associated with the call to setTimeout (callback, 5000)(nothing is sent to the callback).So, For (var i = 0; i <respond.length; i ++) will not work since respond === undefined.
But why is it so?
callback(
[{
"time": "1500303264",
"user": "qwe",
"message": "we",
"id": 1
},
{
"time": "1500303987",
"user": "Max",
"message": "q",
"id": 2
}
]);
function smile(mess) {
var smile = ":)";
var graficSmile = "<img src = './image/Smile.png' alt='Smile' align='middle'>";
var string_with_replaced_smile = mess.replace(smile, graficSmile);
var sad = ":("
var graficSad = "<img src = './image/Sad.png' alt='Smile' align='middle'>";
var string_with_replaced_smile_and_sad = string_with_replaced_smile.replace(sad, graficSad);
return string_with_replaced_smile_and_sad;
}
$.getJSON('data/messages.json', callback);
var exists = [];
function callback(respond) {
var timeNow = Date.now();
for (var i = 0; i < respond.length; i++) {
var data = respond[i];
if (exists.indexOf(data.id) != -1) continue;
var timeInMessage = data.time * 1000;
var diff_time = (timeNow - timeInMessage);
if (diff_time <= 3600000) {
var rowClone = $('.mess_hide').clone().removeClass('mess_hide');
var newDate = new Date(timeInMessage);
var dateArray = [newDate.getHours(), newDate.getMinutes(), newDate.getSeconds()]
var res = dateArray.map(function(x) {
return x < 10 ? "0" + x : x;
}).join(":");
$('#messages').append(rowClone);
$('.time', rowClone).html(res);
$('.name', rowClone).html(data.user);
$('.message', rowClone).html(smile(data.message));
$('.scroller').scrollTop($('#messages').height());
exists.push(data.id);
}
}
setTimeout(function(){callback(respond)}, 5000);
}
.scroller {
width: 490px;
height: 255px;
max-height: 255px;
overflow-y: auto;
overflow-x: hidden;
}
table#messages {
min-height: 260px;
width: 100%;
background: #fffecd;
border: none;
}
table#messages::-webkit-scrollbar {
width: 1em;
}
table#messages::-webkit-scrollbar-track {
-webkit-box-shadow: inset 0 0 6px rgba(0, 0, 0, 0.3);
}
table#messages::-webkit-scrollbar-thumb {
background-color: darkgrey;
outline: 1px solid slategrey;
}
tr {
height: 20%;
display: block;
}
td.time,
td.name {
width: 70px;
max-width: 75px;
text-align: center;
}
td.name {
font-weight: bold;
}
form#text_submit {
display: inline-flex;
align-items: flex-start;
}
input#text {
width: 370px;
height: 30px;
margin-top: 20px;
background: #fffecd;
font-family: 'Montserrat';
font-size: 16px;
border: none;
align-self: flex-start;
}
input#submit {
padding: 0;
margin-left: 21px;
margin-top: 21px;
height: 30px;
width: 95px;
background: #635960;
border: none;
color: white;
font-family: 'Montserrat';
font-size: 16px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="scroller">
<table id="messages">
<tr class="mess_hide">
<td class="time"></td>
<td class="name"></td>
<td class="message"></td>
</tr>
</table>
</div>
<form method="POST" id="easyForm">
<input type="text" name="text" id="text">
<input type="submit" value="Send" id="submit">
</form>
</div>
Chrome
Opera
Since it is assumed that the var exists - array, but the value of the array ([]) is assigned to it only later, after the call $.getJSON(...). So, when callback is called for the first time value [] is not set for exists.We just need to move var exists above the first call of callback.
When callback is called by the timer, nothing is passed to it. But timer needs to reread the messages from the file and display them on the screen.So, instead setTimeout(function(){callback(respond)}, 5000); we need setTimeout(function(){$.getJSON('data/messages.json', callback);}, 5000);.
var exists = [];
$.getJSON('data/messages.json', callback);
function callback(respond) {
var timeNow = Date.now();
for (var i = 0; i < respond.length; i++) {
var data = respond[i];
if (exists.indexOf(data.id) != -1) continue;
var timeInMessage = data.time * 1000;
var diff_time = (timeNow - timeInMessage);
if (diff_time <= 3600000) {
var rowClone = $('.mess_hide').clone().removeClass('mess_hide');
var newDate = new Date(timeInMessage);
var dateArray = [newDate.getHours(), newDate.getMinutes(), newDate.getSeconds()]
var res = dateArray.map(function(x) {
return x < 10 ? "0" + x : x;
}).join(":");
$('#messages').append(rowClone);
$('.time', rowClone).html(res);
$('.name', rowClone).html(data.user);
$('.message', rowClone).html(smile(data.message));
$('.scroller').scrollTop($('#messages').height());
exists.push(data.id);
}
}
setTimeout(function() {
$.getJSON('data/messages.json', callback);
}, 5000);
}
Since callback requires an array to be passed as an argument, setTimeout must ensure that when it calls callback, it passes the array.
Change
setTimeout(callback, 5000);
to
setTimeout(function(){callback(respond)}, 5000);
which allows callback to be called with an argument as the body of an anonymous function that will be called by setTimeout.
Also, as a side note, if you used respond.forEach() instead of a counting for loop, the code would be much cleaner:
respond.forEach(function(data) {
if (exists.indexOf(data.id) != -1) continue;
var timeInMessage = data.time * 1000;
var diff_time = (timeNow - timeInMessage);
if (diff_time <= 3600000) {
var rowClone = $('.mess_hide').clone().removeClass('mess_hide');
var newDate = new Date(timeInMessage);
var dateArray = [newDate.getHours(), newDate.getMinutes(), newDate.getSeconds()]
var res = dateArray.map(function(x) {
return x < 10 ? "0" + x : x;
}).join(":");
$('#messages').append(rowClone);
$('.time', rowClone).html(res);
$('.name', rowClone).html(data.user);
$('.message', rowClone).html(smile(data.message));
$('.scroller').scrollTop($('#messages').height());
exists.push(data.id);
}
});

Sound-Reactive css animation on chrome android/iOs

I'm working on a website for my Sound Design degree for which I need to visualize the music.
I managed to animate the background of my website according to the "volume" of the sound playing (variation of the opacity). It works like a charm on Chrome osx but I can't can't figure out how to make it work on android/iOS. Should I use a specific library for mobile css animation ?
Thanks a lot !!
Here is the messy my code in his entirety :
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>Choir_Test</title>
<link href="http://fonts.googleapis.com/css?family=Open+Sans:400,300" rel="stylesheet" type="text/css">
<style>
body {
font-family:'Open Sans', serif; font-size:40px;
background-color:#000000;
padding : 0;
margin: 0;
width: 100%;
height: 100%;
}
Header {
position: center 40px;
height: 100px;
width: 100%;
color: white;
}
.contentWrapper {
width:1000px; margin-left: 40px; font-size:22px; font-weight:200;
}
h1 {
font-size:60px; font-weight:300;
}
.area {
height: 150px;
width: 100%;
color: white;
z-index:10;
padding : 0;
margin: 0;
}
#circularCenter {
margin: auto;
position: absolute;
top: 0;
left: 0;
bottom: 0;
right: 0;
width:74px;
height:74px;
border-radius:100%;
background:rgb(255,0,0);
}
.circle {
background:rgba(255,0,0, 1);
position: absolute;
top: 0;
left: 0;
bottom: 0;
right: 0;
-webkit-transition:0.1s ease all;
z-index:-1;
}
.initiator {
position:absolute;
width:100%; height:100%;
background:rgba(255,255,255, 0);
-webkit-transition:0.3s ease all;
z-index:1;
cursor:pointer;
}
.experiment {
background:rgba(0,0,0, 1);
background:-webkit-linear-gradient(#000,#000);
background:-moz-linear-gradient(#000,#000);
background:-ms-linear-gradient(#000,#000);
width:100%;
height:100%;
position: center 40px;
background-image:url(Images/Choirs.png);
background-size:150px 75px;
background-attachment:fixed;
background-repeat:no-repeat;
background-position:center 40px;
z-index: 100;
height: 100%;
Width: 100%;
padding : 0;
margin: 0;
}
.header
{
height: 100px;
padding-right: auto;
padding-left:auto;
z-index: 1000;
}
.footer
{
position: absolute;
bottom: 0px;
height: 30px;
padding-left:40px;
margin-bottom: 40px;
z-index: 750;
-webkit-filter: invert(100%);
}
</style>
</head>
<body>
<div class="experiment" id="r3">
<div class="initiator"></div>
<div id="circles" class="area"></div>
<div id="circles" class="footer">
<img src="Images/Twitter.png" width="40px"></img>
<img src="Images/Facebook.png" width="40px"></img>
</div>
</div>
</div>
<audio id="r0audio" loop>
<source src="Musics/China1.mp3"></audio>
<script>
window.AudioContext = window.AudioContext || window.webkitAudioContext || window.mozAudioContext;
var renderers = {
'r0': (function() {
var barsArr = [],
initialized = false,
barsEl;
var height = 0;
var init = function(config) {
var count = config.count;
var width = config.width;
var barWidth = (width/count) >> 0;
height = config.height;
barsEl = document.getElementById('bars');
for(var i = 0; i < count; i++ ){
var nunode = document.createElement('div');
nunode.classList.add('bar');
nunode.style.width = barWidth + 'px';
nunode.style.left = (barWidth * i) + 'px';
barsArr.push(nunode);
barsEl.appendChild(nunode);
}
initialized = true;
};
var max = 256;
var renderFrame = function(frequencyData) {
for(var i = 0; i < barsArr.length; i++) {
var bar = barsArr[i];
bar.style.height = ((frequencyData[i]/max)*height + 'px');
}
};
return {
init: init,
isInitialized: function() {
return initialized;
},
renderFrame: renderFrame
}
})(),
'r3': (function() {
var circles = [];
var initialized = false;
var height = 0;
var width = 0;
var init = function(config) {
var count = config.count;
width = config.width;
height = config.height;
var circleMaxWidth = (width*0.99) >> 0;
circlesEl = document.getElementById('circles');
for(var i = 0; i < count; i++ ){
var node = document.createElement('div');
node.style.width = node.style.color = (i/count*circleMaxWidth) + 'px';
node.classList.add('circle');
circles.push(node);
circlesEl.appendChild(node);
}
initialized = true;
};
var max = 256;
var renderFrame = function(frequencyData) {
for(var i = 0; i < circles.length; i++) {
var circle = circles[i];
circle.style.cssText = '-webkit-transform:scale('+1+');';
circle.style.cssText += 'opacity:'+((frequencyData[i]/max))+';';
}
};
return {
init: init,
isInitialized: function() {
return initialized;
},
renderFrame: renderFrame
}
})(),
};
window.onload = function() {
function Visualization(config) {
var audio,
audioStream,
analyser,
source,
audioCtx,
canvasCtx,
frequencyData,
running = false,
renderer = config.renderer,
width = config.width || 360,
height = config.height || 360;
var init = function() {
audio = document.getElementById('r0audio');
audioCtx = new AudioContext();
analyser = audioCtx.createAnalyser();
source = audioCtx.createMediaElementSource(audio);
source.connect(analyser);
analyser.connect(audioCtx.destination);
analyser.fftSize = 64;
frequencyData = new Uint8Array(analyser.frequencyBinCount);
renderer.init({
count: analyser.frequencyBinCount,
width: width,
height: height
});
};
this.start = function() {
audio.play();
running = true;
renderFrame();
};
this.stop = function() {
running = false;
audio.pause();
};
this.setRenderer = function(r) {
if (!r.isInitialized()) {
r.init({
count: analyser.frequencyBinCount,
width: width,
height: height
});
}
renderer = r;
};
this.isPlaying = function() {
return running;
}
var renderFrame = function() {
analyser.getByteFrequencyData(frequencyData);
renderer.renderFrame(frequencyData);
if (running) {
requestAnimationFrame(renderFrame);
}
};
init();
};
var vis = document.querySelectorAll('.initiator');
var v = null;
var lastEl;
var lastElparentId;
for(var i=0; i<vis.length; i++) {
vis[i].onclick = (function() {
return function() {
var el = this;
var id = el.parentNode.id;
if (!v) {
v = new Visualization({renderer: renderers[id] });
}
v.setRenderer(renderers[id]);
if (v.isPlaying()) {
if (lastElparentId === id) {
v.stop();
el.style.backgroundColor = 'rgba(0,0,0,0.5)';
} else {
lastEl.style.backgroundColor = 'rgba(0,0,0,0.5)';
el.style.backgroundColor = 'rgba(0,0,0,0)';
}
}else {
v.start();
el.style.backgroundColor = 'rgba(0,0,0,0)';
}
lastElparentId = id;
lastEl = el;
};
})();
}
};
</script>
</body>
</html>

Categories

Resources