The problem here is that when you reach the last item by doing a touch move,
If you touch move with the previous item, it doesn't work.
function slideCustom () {
const listWrap = document.querySelector('.list-item-wrap');
const listItem = document.querySelector('.list-item-wrap .list-item');
const listItems = document.querySelectorAll('.list-item-wrap .list-item');
const listItemPrev = document.querySelector('.m-slide-list-wrap .list-prev-btn');
const listItemNext = document.querySelector('.m-slide-list-wrap .list-next-btn');
const listItemCount = listItems.length;
const listItemWidth = listItem.offsetWidth;
let currentIndex = 0;
let touchStartX = null;
listWrap.style.width = listItemWidth * listItemCount + 'px';
function moveSlide(num) {
listWrap.style.left = -(num * ( listItemWidth + 10 )) + 'px';
currentIndex = num;
}
listItems.forEach((item, index) => {
item.addEventListener('click', function() {
moveSlide(index);
listItems.forEach(i => i.classList.remove('active'));
this.classList.add('active');
});
});
moveSlide(currentIndex);
listItemPrev.addEventListener('click', () => {
if (currentIndex > 0) {
moveSlide(currentIndex - 1);
listItems[currentIndex + 1].classList.remove("active");
listItems[currentIndex].classList.add("active");
}
});
listItemNext.addEventListener('click', () => {
if (currentIndex < listItemCount - 1) {
moveSlide(currentIndex + 1);
listItems[currentIndex - 1].classList.remove("active");
listItems[currentIndex].classList.add("active");
}
});
if (listItemCount < 2) {
listItemPrev.remove();
listItemNext.remove();
}
listWrap.addEventListener('touchstart', (event) => {
touchStartX = event.touches[0].clientX;
});
listWrap.addEventListener('touchmove', (event) => {
let touchMoveX = event.touches[0].clientX;
let touchDiffX = touchMoveX - touchStartX;
if (touchStartX !== null) {
if (touchDiffX > 0 && currentIndex > 0) {
moveSlide(currentIndex - 1);
listItems[currentIndex + 1].classList.remove("active");
listItems[currentIndex].classList.add("active");
} else if (touchDiffX < 0 && currentIndex < listItemCount - 1) {
moveSlide(currentIndex + 1);
listItems[currentIndex - 1].classList.remove("active");
listItems[currentIndex].classList.add("active");
} else if (touchDiffX < 0 && currentIndex === listItemCount - 1) {
moveSlide(currentIndex);
} else if (touchDiffX > 0 && currentIndex === 0) {
moveSlide(currentIndex);
}
touchStartX = null;
}
});
}
For example, assuming that there are 7 items,
When you touch move from right to left and reach the last 7th item,
I want to touch move the 7th item from left to right and move to the previous 6th item.
Related
I am looking to have my grid style game start once I click the start button on my page. Currently the game starts as soon as I click the grid, but I want this function to be invoked only when the you click the Start Button.
I already created my game Board. Which can be called using this function: createBoard(). Styling for this board is full of my divs and working.
I tried the solutions previously given in my other thread and still had an issue with the function not invoking only at the click of a start button.
Here is my replit: Any feedback on what I'm doing wrong? Thanks! :)
https://replit.com/#batb/WholeFrostyLocus
document.addEventListener('DOMContentLoaded', () => {
const grid = document.querySelector('.grid')
const startBtn = document.querySelector('.button-one')
const pauseBtn = document.querySelector('.button-two')
const scoreDisplay = document.querySelector('.score')
const countdown = document.querySelector('.countdown')
let paused = true
let score = 100
const width = 8
const squares = []
let isGameOver = false
let buzzyAmount = 12
let result = 0
const fiBuzz = [
'url(images/purple-fizzy.png)',
'url(images/buzzy-green.png)',
'url(images/new-moo-buzzy.png)',
'url(images/new-shiny-fizzy.png)'
]
//shuffled Arrays
function createBoard() {
const buzzArray = Array(buzzyAmount).fill('buzzy')
const emptyArray = Array(width * width - buzzyAmount).fill('valid')
const gameArray = emptyArray.concat(buzzArray)
const shuffledArray = gameArray.sort(() => Math.random() - 0.5)
for (let i = 0; i < width * width; i++) {
let randomNumber = Math.floor(Math.random() * fiBuzz.length)
let square = document.createElement('div')
square.setAttribute('id', i)
square.setAttribute('draggable', 'true')
square.classList.add(shuffledArray[i])
grid.appendChild(square)
squares.push(square)
square.style.backgroundImage = fiBuzz[randomNumber]
//normal click
square.addEventListener('click', function(e) {
click(square)
})
}
}
createBoard()
//check neighboring squares once square is clicked
function checkSquare(square, currentId) {
const isLeftEdge = (currentId % width === 0)
const isRightEdge = (currentId % width === width -1)
setTimeout(() => {
if (currentId > 0 && !isLeftEdge) {
const newId = squares[parseInt(currentId) -1].id
//const newId = parseInt(currentId) - 1 ....refactor
const newSquare = document.getElementById(newId)
click(newSquare)
}
if (currentId > 7 && !isRightEdge) {
const newId = squares[parseInt(currentId) +1 -width].id
//const newId = parseInt(currentId) +1 -width ....refactor
const newSquare = document.getElementById(newId)
click(newSquare)
}
if (currentId > 10) {
const newId = squares[parseInt(currentId -width)].id
//const newId = parseInt(currentId) -width ....refactor
const newSquare = document.getElementById(newId)
click(newSquare)
}
if (currentId > 11 && !isLeftEdge) {
const newId = squares[parseInt(currentId) -1 -width].id
//const newId = parseInt(currentId) -1 -width ....refactor
const newSquare = document.getElementById(newId)
click(newSquare)
}
if (currentId < 38 && !isRightEdge) {
const newId = squares[parseInt(currentId) +1].id
//const newId = parseInt(currentId) +1 ....refactor
const newSquare = document.getElementById(newId)
click(newSquare)
}
if (currentId < 40 && !isLeftEdge) {
const newId = squares[parseInt(currentId) -1 +width].id
//const newId = parseInt(currentId) -1 +width ....refactor
const newSquare = document.getElementById(newId)
click(newSquare)
}
if (currentId < 45 && !isRightEdge) {
const newId = squares[parseInt(currentId) +1 +width].id
//const newId = parseInt(currentId) +1 +width ....refactor
const newSquare = document.getElementById(newId)
click(newSquare)
}
if (currentId < 48) {
const newId = squares[parseInt(currentId) +width].id
//const newId = parseInt(currentId) +width ....refactor
const newSquare = document.getElementById(newId)
click(newSquare)
}
}, 10)
}
// game over
function gameOver(square) {
scoreDisplay.innerHTML = score + '<br>'+ ' You Lose :('
isGameOver = true
clearInterval(timerId)
// show ALL the badStars in gameOver
squares.forEach(square => {
if (square.classList.contains('buzzy')) {
square.appendChild(document.createElement('img')).src = 'images/fizz-buzz-mix.png'
square.classList.remove('buzzy')
square.classList.add('checked')
clearInterval(timerId)
}
})
}
function checkForWin() {
let matches = 0
for (let i = 0; i < squares.length; i++) {
if (score >= 100) {
scoreDisplay.innerHTML = score + ': ' + ' You Win!'
} else {
scoreDisplay.innerHTML = score + ': ' + ' You Lose!'
}
clearInterval(timerId)
}
}
// TIMER LOGIC
const startingMinutes = .25
let time = startingMinutes * 60
let timerId
let square
function countDown() {
let minutes = Math.floor(time / 60)
let seconds = time % 60
time--
console.log(minutes, 'minutes:', seconds, 'seconds')
if (time <= 0) {
checkForWin()
gameOver()
}
countdown.innerHTML = minutes + ' minutes ' + ': ' + seconds + ' seconds '
}
// add to right click
function click(square) {
let currentId = square.id
if (isGameOver) return
if (square.classList.contains('checked')) return score++
if (square.classList.contains('buzzy')) {
gameOver(square)
} else {
let total = square.getAttribute('data')
if (total !=0) {
square.classList.add('checked')
if (total == 1) square.classList.add('one')
if (total == 2) square.classList.add('two')
if (total == 3) square.classList.add('three')
if (total == 4) square.classList.add('four')
square.innerHTML = total
return
}
checkSquare(square, currentId)
}
square.classList.add('checked')
}
// START AND PAUSE LOGIC
function scoreFunction() {
if(square.classList.contains('valid')) {
score+=3
}
}
startBtn.addEventListener('click', () => {
if (paused === false) {
score++
return
}
scoreDisplay.innerHTML = 'Score' + ': ' + score++
paused = false
timerId = setInterval(countDown, 1000)
})
function pauseGame() {
paused = true
clearInterval(timerId)
}
pauseBtn.addEventListener('click', () => {
pauseGame()
})
})
Try changing up your html button so it calls the function you want once you click the button:
<button class="button-one" onclick="function_name"> Start </button>
instead of fucntion_name put the name of the function you want to call on the button click.
I have a js pagination system that find .classname elems and paginate them on-the-fly. Clicking on navigation pages the script shows only .classname elements in that interval.
When too much items have to be paginated I would like to add an arrow system to let navigate pages links. The main script is here: https://jsfiddle.net/gyzo2u9c/
(function($) {
var pagify = {
items: {},
container: null,
totalPages: 1,
perPage: 3,
currentPage: 0,
createNavigation: function() {
this.totalPages = Math.ceil(this.items.length / this.perPage);
$('.pagination', this.container.parent()).remove();
var pagination = $('<div class="pagination"></div>').append('<a class="nav prev disabled" data-next="false"><i class="fas fa-caret-left"></i></a>');
for (var i = 0; i < this.totalPages; i++) {
var pageElClass = "page";
if (!i)
pageElClass = "page current";
var pageEl = '<a class="' + pageElClass + '" data-page="' + (
i + 1) + '">' + (
i + 1) + "</a>";
pagination.append(pageEl);
}
pagination.append('<a class="nav next" data-next="true"><i class="fas fa-caret-right"></i></a>');
/*aggiungiamo la paginazione sopra nel calendario*/
if ($(this.container).selector == '#calendario .archivio') {
this.container.before(pagination);
} else {
/*sotto, in tutti gli altri casi*/
this.container.after(pagination);
}
var that = this;
$("body").off("click", ".nav");
this.navigator = $("body").on("click", ".nav", function() {
var el = $(this);
that.navigate(el.data("next"));
});
$("body").off("click", ".page");
this.pageNavigator = $("body").on("click", ".page", function() {
var el = $(this);
that.goToPage(el.data("page"));
$([document.documentElement, document.body]).animate({
scrollTop: ($(".archivio").offset().top - 120)
}, 1);
});
},
navigate: function(next) {
// default perPage to 5
if (isNaN(next) || next === undefined) {
next = true;
}
$(".pagination .nav").removeClass("disabled");
if (next) {
this.currentPage++;
if (this.currentPage > (this.totalPages - 1))
this.currentPage = (this.totalPages - 1);
if (this.currentPage == (this.totalPages - 1))
$(".pagination .nav.next").addClass("disabled");
} else {
this.currentPage--;
if (this.currentPage < 0)
this.currentPage = 0;
if (this.currentPage == 0)
$(".pagination .nav.prev").addClass("disabled");
}
this.showItems();
},
updateNavigation: function() {
var pages = $(".pagination .page");
pages.removeClass("current");
$('.pagination .page[data-page="' + (
this.currentPage + 1) + '"]').addClass("current");
},
goToPage: function(page) {
this.currentPage = page - 1;
$(".pagination .nav").removeClass("disabled");
if (this.currentPage == (this.totalPages - 1))
$(".pagination .nav.next").addClass("disabled");
if (this.currentPage == 0)
$(".pagination .nav.prev").addClass("disabled");
this.showItems();
},
showItems: function() {
this.items.hide().removeClass('item_visibile');
var base = this.perPage * this.currentPage;
this.items.slice(base, base + this.perPage).show().addClass('item_visibile');
this.updateNavigation();
},
init: function(container, items, perPage, currentPage) {
// default perPage to 5
if (isNaN(currentPage) || currentPage === undefined) {
currentPage = 0;
}
this.container = container;
this.currentPage = currentPage;
this.totalPages = 1;
this.perPage = perPage;
this.items = items;
this.createNavigation();
this.showItems();
}
};
// stuff it all into a jQuery method!
$.fn.pagify = function(perPage, itemSelector, currentPage) {
var el = $(this);
var items = $(itemSelector, el);
// default perPage to 5
if (isNaN(perPage) || perPage === undefined) {
perPage = 3;
}
// don't fire if fewer items than perPage
if (items.length <= perPage) {
return true;
}
pagify.init(el, items, perPage, currentPage);
};
})(jQuery);
jQuery(".archive").pagify(2, ".item");
How/Where I have to add the arrow alghoritm?
Thank you in advanced
Solution:
(function($) {
var pagify = {
items: {},
container: null,
totalPages: 1,
perPage: 3,
currentPage: 0,
nextpageInterval: 20,
createNavigation: function() {
this.generateUI();
var that = this;
$("body").off("click", ".nav");
this.navigator = $("body").on("click", ".nav", function() {
var el = $(this);
that.navigate(el.data("next"));
});
$("body").off("click", ".page");
this.pageNavigator = $("body").on("click", ".page", function() {
var el = $(this);
that.goToPage(el.data("page"));
$([document.documentElement, document.body]).animate({
scrollTop: ($(".archivio").offset().top-120)
}, 1);
});
},
getPageList: function(totalPages, page, maxLength) {
if (maxLength < 5) throw "maxLength must be at least 5";
function range(start, end) {
return Array.from(Array(end - start + 1), (_, i) => i + start);
}
var sideWidth = 1;
var leftWidth = (maxLength - sideWidth*2 - 3) >> 1;
var rightWidth = (maxLength - sideWidth*2 - 2) >> 1;
if (totalPages <= maxLength) {
// no breaks in list
return range(1, totalPages);
}
if (page <= maxLength - sideWidth - 1 - rightWidth) {
// no break on left of page
return range(1, maxLength - sideWidth - 1)
.concat(0, range(totalPages - sideWidth + 1, totalPages));
}
if (page >= totalPages - sideWidth - 1 - rightWidth) {
// no break on right of page
return range(1, sideWidth)
.concat(0, range(totalPages - sideWidth - 1 - rightWidth - leftWidth, totalPages));
}
// Breaks on both sides
return range(1, sideWidth)
.concat(0, range(page - leftWidth, page + rightWidth),
0, range(totalPages - sideWidth + 1, totalPages));
},
generateUI: function(){
this.totalPages = Math.ceil(this.items.length / this.perPage);
var pages = this.getPageList(this.totalPages, this.currentPage, this.nextpageInterval);
$('.pagination', this.container.parent()).remove();
var pagination = $('<div class="pagination"></div>');
for (var i = 0; i < pages.length; i++) {
var pageElClass = "page";
if (pages[i] == (this.currentPage + 1)){
pageElClass = "page current";
}
if(pages[i] != 0){
var lbl = pages[i];
if(i == 0 && pages[i + 1] == 0){
lbl = '<i class="fas fa-step-backward"></i>';
}else if(i == (pages.length-1) && pages[i - 1] == 0){
lbl = '<i class="fas fa-step-forward"></i>';
}
var pageEl = '<a class="' + pageElClass + '" data-page="' + (
pages[i]) + '">' + (
lbl) + "</a>";
pagination.append(pageEl);
}else{
if(i == 1){
var prevEl = '<a class="nav prev disabled" data-next="false"><i class="fas fa-caret-left"></i></a>';
pagination.append(prevEl);
}else{
var nextEl = '<a class="nav next" data-next="true"><i class="fas fa-caret-right"></i></a>';
pagination.append(nextEl);
}
}
}
/*aggiungiamo la paginazione sopra nel calendario*/
if ($(this.container).selector == '#calendario .archivio'){
this.container.before(pagination);
} else {
/*sotto, in tutti gli altri casi*/
this.container.after(pagination);
}
},
navigate: function(next) {
// default perPage to 5
if (isNaN(next) || next === undefined) {
next = true;
}
$(".pagination .nav").removeClass("disabled");
if (next) {
this.currentPage++;
if (this.currentPage > (this.totalPages - 1))
this.currentPage = (this.totalPages - 1);
if (this.currentPage == (this.totalPages - 1))
$(".pagination .nav.next").addClass("disabled");
}
else {
this.currentPage--;
if (this.currentPage < 0)
this.currentPage = 0;
if (this.currentPage == 0)
$(".pagination .nav.prev").addClass("disabled");
}
this.showItems();
},
updateNavigation: function() {
var pages = $(".pagination .page");
pages.removeClass("current");
$('.pagination .page[data-page="' + (
this.currentPage + 1) + '"]').addClass("current");
this.generateUI();
},
goToPage: function(page) {
this.currentPage = page - 1;
$(".pagination .nav").removeClass("disabled");
if (this.currentPage == (this.totalPages - 1))
$(".pagination .nav.next").addClass("disabled");
if (this.currentPage == 0)
$(".pagination .nav.prev").addClass("disabled");
this.showItems();
},
showItems: function() {
this.items.hide().removeClass('item_visibile');
var base = this.perPage * this.currentPage;
this.items.slice(base, base + this.perPage).show().addClass('item_visibile');
this.updateNavigation();
},
init: function(container, items, perPage, currentPage) {
// default perPage to 5
if (isNaN(currentPage) || currentPage === undefined) {
currentPage = 0;
}
this.container = container;
this.currentPage = currentPage;
this.totalPages = 1;
this.perPage = perPage;
this.items = items;
this.createNavigation();
this.showItems();
}
};
// stuff it all into a jQuery method!
$.fn.pagify = function(perPage, itemSelector, currentPage) {
var el = $(this);
var items = $(itemSelector, el);
// default perPage to 5
if (isNaN(perPage) || perPage === undefined) {
perPage = 3;
}
// don't fire if fewer items than perPage
if (items.length <= perPage) {
return true;
}
pagify.init(el, items, perPage, currentPage);
};
})(jQuery);
I'm trying to code an Othello game, and now I'm trying to code the algorithm that does return the valid positions. I started by retrieving the directions of the empty squares where there's a black or white stone right next to it, but my code doesn't run. I don't know if I did something wrong but it seems that when I launch the program, the code runs slow because the algorithm is overkill.
What can I do for that?
Here's my Code(By the way, I use React.js):
Here's the data structure of the square array:
history: [{
squares: [
Array(8).fill(null),
Array(8).fill(null),
Array(8).fill(null),
[null,null,null,'black','white',null,null,null],
[null,null,null,'white','black',null,null,null],
Array(8).fill(null),
Array(8).fill(null),
Array(8).fill(null)
]
}],
The Algorithm(for now, just returns the squares that have a stone right next to it(up, up & right , down, left, etc.)):
checkMoveValidity(isBlack) {
const history = this.state.history.slice(0, this.state.stepNumber + 1);
const current = history[history.length - 1];
const squares = current.squares.slice()
// Get all the empty spaces
const emptySpaces = []
for (var row=1;row<squares.length-1;row++) {
for (var col=1;col<squares[row].length-1;col++) {
if (!squares[row][col]) {
emptySpaces.push([row,col])
}
}
}
const cordAndDirs = []
for (var sp=0;sp<emptySpaces.length;sp++) {
const element = emptySpaces[sp]
const elObject = {
coordinates: element,
directions: []
}
if (element === [0,0])
{
// Check down
if (squares[1][0]) {
const downEls = []
for (var i=1;i<squares.length;i++) {
downEls.push([i,0])
}
elObject.directions.push(downEls)
}
// Check down right (diagonal)
if (squares[1][1]) {
const drEls = []
for (var i=1;i<squares.length;i++) {
drEls.push([i,i])
}
elObject.directions.push(drEls)
}
// Check right
if (squares[0][1]) {
const rightEls = []
for (var i=1;i<squares.length;i++) {
rightEls.push([0,i])
}
elObject.directions.push(rightEls)
}
}
else if (emptySpaces[sp] === [0,7])
{
// Check down
if (squares[1][7]) {
const downEls = []
for (var i=1;i<squares.length;i++) {
downEls.push([i,7])
}
elObject.directions.push(downEls)
}
// Check down left (diagonal)
if (squares[1][6]) {
const drEls = []
for (var i=1;i<squares.length;i++) {
drEls.push([i,7 - i])
}
elObject.directions.push(drEls)
}
// Check left
if (squares[0][6]) {
const leftEls = []
for (var i=1;i<squares.length;i++) {
leftEls.push([0,7 - i])
}
elObject.directions.push(leftEls)
}
}
else if (emptySpaces[sp] === [7,0])
{
// Check up
if (squares[6][0]) {
const upEls = []
for (var i=1;i<squares.length;i++) {
upEls.push([7 - i,0])
}
elObject.directions.push(upEls)
}
// Check up right
if (squares[6][1]) {
const urEls = []
for (var i=1;i<squares.length;i++) {
urEls.push([7 - i,i])
}
elObject.directions.push(urEls)
}
// Check right
if (squares[7][1]) {
const rightEls = []
for (var i=1;i<squares.length;i++) {
rightEls.push([7,i - 1])
}
elObject.directions.push(rightEls)
}
}
else if (emptySpaces[sp] === [7,7])
{
//Check up
if (squares[6][7]) {
const upEls = []
for (var i=1;i<squares.length;i++) {
upEls.push([7 - i,7])
}
elObject.directions.push(upEls)
}
// Check up left
if (squares[6][6]) {
const ulEls = []
for (var i=1;i<squares.length;i++) {
ulEls.push([7 - i,7 - i])
}
elObject.directions.push(ulEls)
}
// Check left
if (squares[7][6]) {
const leftEls = []
for (var i=1;i<squares.length;i++) {
leftEls.push([7,7 - i])
}
elObject.directions.push(leftEls)
}
}
else
{
const crdsY = emptySpaces[sp][0]
const crdsX = emptySpaces[sp][1]
//Check up
if (squares[crdsY - 1][crdsX]) {
const upEls = []
var i = 1
while (crdsY - i >= 0) {
upEls.push([crdsY - i,crdsX])
i++;
}
elObject.directions.push(upEls)
}
// Check up right
if (squares[crdsY - 1][crdsX + 1]) {
const urEls = []
var i = 1
while (crdsY - i >= 0 && crdsX + i <= 7) {
urEls.push([crdsY - i,crdsX + i])
i++;
}
elObject.directions.push(urEls)
}
// Check right
if (squares[crdsY][crdsX + 1]) {
const rightEls = []
var i = 1
while (crdsX + i <= 7) {
rightEls.push([crdsY,crdsX + i])
i++;
}
elObject.directions.push(rightEls)
}
// Check down right
if (squares[crdsY + 1][crdsX + 1]) {
const rightEls = []
var i = 1
while (crdsY + i <= 7 && crdsX + i <= 7) {
rightEls.push([crdsY + i,crdsX + i])
i++;
}
elObject.directions.push(rightEls)
}
// Check down
if (squares[crdsY + 1][crdsX]) {
const rightEls = []
var i = 1
while (crdsY + i <= 7) {
rightEls.push([crdsY + i,crdsX])
i++;
}
elObject.directions.push(rightEls)
}
// Check down left
if (squares[crdsY + 1][crdsX - 1]) {
const rightEls = []
var i = 1
while (crdsY + i <= 7 && crdsX - i >= 0) {
rightEls.push([crdsY + i,crdsX - i])
i++;
}
elObject.directions.push(rightEls)
}
// Check left
if (squares[crdsY][crdsX - 1]) {
const rightEls = []
var i = 1
while (crdsX - i >= 0) {
rightEls.push([crdsY,crdsX - i])
i++;
}
elObject.directions.push(rightEls)
}
// Check up left
if (squares[crdsY - 1][crdsX - 1]) {
const rightEls = []
var i = 1
while (crdsY - i >= 0 && crdsX - i >= 0) {
rightEls.push([crdsY - i,crdsX - i])
}
elObject.directions.push(rightEls)
}
}
if (elObject.directions.length === 0) {
continue
} else {
cordAndDirs.push(elObject)
}
}
return cordAndDirs
}
And this is where I'm trying to implement it:
render() {
const history = this.state.history
const current = history[this.state.stepNumber]
// Return the game scene here
return (
<div className="master-container">
<GameBoard squares={current.squares} onClick={(row,col) => {
const elems = this.checkMoveValidity(this.state.blackIsNext)
console.log(elems)
}}/>
</div>
)
}
By the way, I checked whether the command has reached to the elements inside the GameBoard component. It does not have any problem, the problem occurred when I implemented the algorithm.
I did it. It was quite simple though, I even simplified the code a bit. I forgot to add i++; to the last while loop, I was stuck forever, and then I had to handle the borders so that I don't get an error. For example, I can't //Check up when the upper border squares have no squares beneath them.
This is how I changed the conditional statements:
for (var sp=0;sp<emptySpaces.length;sp++) {
const element = emptySpaces[sp]
const elObject = {
coordinates: element,
directions: []
}
// You apply the same methods for all the other squares here (can't use constant numbers in 'squares' now...)
const crdsY = emptySpaces[sp][0]
const crdsX = emptySpaces[sp][1]
var i;
//Check up
if (crdsY !== 0 && squares[crdsY - 1][crdsX]) {
const upEls = []
i = 1
while (crdsY - i >= 0) {
upEls.push([crdsY - i,crdsX])
i++;
}
elObject.directions.push(upEls)
}
// Check up right
if (crdsX !== 7 && crdsY !== 0 && squares[crdsY - 1][crdsX + 1]) {
const urEls = []
i = 1
while (crdsY - i >= 0 && crdsX + i <= 7) {
urEls.push([crdsY - i,crdsX + i])
i++;
}
elObject.directions.push(urEls)
}
// Check right
if (crdsX !== 7 && squares[crdsY][crdsX + 1]) {
const rightEls = []
i = 1
while (crdsX + i <= 7) {
rightEls.push([crdsY,crdsX + i])
i++;
}
elObject.directions.push(rightEls)
}
// Check down right
if (crdsX !== 7 && crdsY !== 7 && squares[crdsY + 1][crdsX + 1]) {
const rightEls = []
i = 1
while (crdsY + i <= 7 && crdsX + i <= 7) {
rightEls.push([crdsY + i,crdsX + i])
i++;
}
elObject.directions.push(rightEls)
}
// Check down
if (crdsY !== 7 && squares[crdsY + 1][crdsX]) {
const rightEls = []
i = 1
while (crdsY + i <= 7) {
rightEls.push([crdsY + i,crdsX])
i++;
}
elObject.directions.push(rightEls)
}
// Check down left
if (crdsY !== 7 && crdsX !== 0 && squares[crdsY + 1][crdsX - 1]) {
const rightEls = []
i = 1
while (crdsY + i <= 7 && crdsX - i >= 0) {
rightEls.push([crdsY + i,crdsX - i])
i++;
}
elObject.directions.push(rightEls)
}
// Check left
if (crdsX !== 0 && squares[crdsY][crdsX - 1]) {
const rightEls = []
i = 1
while (crdsX - i >= 0) {
rightEls.push([crdsY,crdsX - i])
i++;
}
elObject.directions.push(rightEls)
}
// Check up left
if (crdsX !== 0 && crdsY !== 0 && squares[crdsY - 1][crdsX - 1]) {
const rightEls = []
i = 1
while (crdsY - i >= 0 && crdsX - i >= 0) {
rightEls.push([crdsY - i,crdsX - i])
i++;
}
elObject.directions.push(rightEls)
}
if (elObject.directions.length !== 0) {
cordAndDirs.push(elObject)
}
And also I changed the the game board onClick property a bit like this:
return (
<div className="master-container">
<GameBoard squares={current.squares} onClick={(row,col) => {
const elems = this.checkElementsAround(this.checkMoveValidity(this.state.blackIsNext))
console.log(elems)
for (let el=0;el<elems.length;el++) {
if (row === elems[el].coordinates[0] && col === elems[el].coordinates[1]) {
this.handleMove(row,col);
break
}
}
}}/>
</div>
)
i have this 2 codes and want change the JS file.
Currently that's how it works:
--> the animation starts only when you click in the navigation.
I want play the animation if my site is loaded but i don't finde the function to change the code.
you can find the animation here: https://tympanus.net/Development/ShapeOverlays/index3.html
Thank you so much.
html:
<div class="animation">
<svg class="shape-overlays" viewBox="0 0 100 100" preserveAspectRatio="none">
<path class="shape-overlays__path"></path>
<path class="shape-overlays__path"></path>
<path class="shape-overlays__path"></path>
</svg>
</div>
JS-File:
setTimeout(() => document.body.classList.add('render'), 60);
class ShapeOverlays {
constructor(elm) {
this.elm = elm;
this.path = elm.querySelectorAll('path');
this.numPoints = 2;
this.duration = 600;
this.delayPointsArray = [];
this.delayPointsMax = 0;
this.delayPerPath = 200;
this.timeStart = Date.now();
this.isOpened = false;
this.isAnimating = false;
}
toggle() {
this.isAnimating = true;
for (var i = 0; i < this.numPoints; i++) {
this.delayPointsArray[i] = 0;
}
if (this.isOpened === false) {
this.open();
} else {
this.close();
}
}
open() {
this.isOpened = true;
this.elm.classList.add('is-opened');
this.timeStart = Date.now();
this.renderLoop();
}
close() {
this.isOpened = false;
this.elm.classList.remove('is-opened');
this.timeStart = Date.now();
this.renderLoop();
}
*/
updatePath(time) {
const points = [];
for (var i = 0; i < this.numPoints; i++) {
const thisEase = this.isOpened ?
(i == 1) ? ease.cubicOut : ease.cubicInOut:
(i == 1) ? ease.cubicInOut : ease.cubicOut;
points[i] = thisEase(Math.min(Math.max(time - this.delayPointsArray[i], 0) / this.duration, 1)) * 100
}
let str = '';
str += (this.isOpened) ? `M 0 0 V ${points[0]} ` : `M 0 ${points[0]} `;
for (var i = 0; i < this.numPoints - 1; i++) {
const p = (i + 1) / (this.numPoints - 1) * 100;
const cp = p - (1 / (this.numPoints - 1) * 100) / 2;
str += `C ${cp} ${points[i]} ${cp} ${points[i + 1]} ${p} ${points[i + 1]} `;
}
str += (this.isOpened) ? `V 0 H 0` : `V 100 H 0`;
return str;
}
render() {
if (this.isOpened) {
for (var i = 0; i < this.path.length; i++) {
this.path[i].setAttribute('d', this.updatePath(Date.now() - (this.timeStart + this.delayPerPath * i)));
}
} else {
for (var i = 0; i < this.path.length; i++) {
this.path[i].setAttribute('d', this.updatePath(Date.now() - (this.timeStart + this.delayPerPath * (this.path.length - i - 1))));
}
}
}
renderLoop() {
this.render();
if (Date.now() - this.timeStart < this.duration + this.delayPerPath * (this.path.length - 1) + this.delayPointsMax) {
requestAnimationFrame(() => {
this.renderLoop();
});
}
else {
this.isAnimating = false;
}
}
}
Well, you missed last part
(function() {
const elmHamburger = document.querySelector('.hamburger');
const gNavItems = document.querySelectorAll('.global-menu__item');
const elmOverlay = document.querySelector('.shape-overlays');
const overlay = new ShapeOverlays(elmOverlay);
elmHamburger.addEventListener('click', () => {
if (overlay.isAnimating) {
return false;
}
overlay.toggle();
if (overlay.isOpened === true) {
elmHamburger.classList.add('is-opened-navi');
for (var i = 0; i < gNavItems.length; i++) {
gNavItems[i].classList.add('is-opened');
}
} else {
elmHamburger.classList.remove('is-opened-navi');
for (var i = 0; i < gNavItems.length; i++) {
gNavItems[i].classList.remove('is-opened');
}
}
});
}());
There is event listener click attached to button elmHamburger, That is executing anonymous arrow function. If you want to run that animation on load, you need to replace click event with load.
That is:
elmHamburger.addEventListener('click', () => {...};
with
window.document.addEventListener('load', () => {...};
If you want to start animation on load and keep button event, then
(function() {
const elmHamburger = document.querySelector('.hamburger');
const gNavItems = document.querySelectorAll('.global-menu__item');
const elmOverlay = document.querySelector('.shape-overlays');
const overlay = new ShapeOverlays(elmOverlay);
const func = () => {
if (overlay.isAnimating) {
return false;
}
overlay.toggle();
if (overlay.isOpened === true) {
elmHamburger.classList.add('is-opened-navi');
for (var i = 0; i < gNavItems.length; i++) {
gNavItems[i].classList.add('is-opened');
}
} else {
elmHamburger.classList.remove('is-opened-navi');
for (var i = 0; i < gNavItems.length; i++) {
gNavItems[i].classList.remove('is-opened');
}
}
}
elmHamburger.addEventListener('click', func);
window.addEventListener('load', func);
}());
I've got a image slider on my website, it seems to work fine on IE, Firefox and Opera. But it doesn't work on Chrome and Safari. (Example: http://tommy-design.nl/ari/index.php)
<script type="text/javascript">
var data = [
["fotos/DSC_0055 (Large).JPG","Duitse herder","fotos/DSC_0055 (Large).JPG"],
["fotos/DSC_0154 (Large).JPG","Duitse herder","fotos/DSC_0154 (Large).JPG"],
["fotos/DSC_0194 (Large).JPG","Duitse herder","fotos/DSC_0194 (Large).JPG"],
["fotos/SSA41896 (Large).jpg","Duitse herder","fotos/SSA41896 (Large).jpg"],
["fotos/DSC_0143 (Large).JPG","Duitse herder","fotos/DSC_0143 (Large).JPG"]
]
imgPlaces = 4
imgWidth = 230
imgHeight = 122
imgSpacer = 0
dir = 0
newWindow = 1
moz = document.getElementById &&! document.all
step = 1
timer = ""
speed = 10
nextPic = 0
initPos = new Array()
nowDivPos = new Array()
function initHIS3()
{
for (var i = 0;i < imgPlaces+1;i++)
{
newImg=document.createElement("IMG")
newImg.setAttribute("id","pic_"+i)
newImg.setAttribute("src","")
newImg.style.position = "absolute"
newImg.style.width=imgWidth + "px"
newImg.style.height=imgHeight + "px"
newImg.style.border = 0
newImg.alt =""
newImg.i = i
newImg.onclick = function()
{
his3Win(data[this.i][2])
}
document.getElementById("display").appendChild(newImg)
}
containerEL = document.getElementById("container1")
displayArea = document.getElementById("display")
pic0 = document.getElementById("pic_0")
containerBorder = (document.compatMode == "CSS1Compat"?0:parseInt(containerEL.style.borderWidth) * 2)
containerWidth = (imgPlaces * imgWidth) + ((imgPlaces - 1) * imgSpacer)
containerEL.style.width=containerWidth + (!moz?containerBorder:"") + "px"
containerEL.style.height=imgHeight + (!moz?containerBorder:"") + "px"
displayArea.style.width = containerWidth+"px"
displayArea.style.clip = "rect(0," + (containerWidth+"px") + "," + (imgHeight+"px") + ",0)"
displayArea.onmouseover = function()
{
stopHIS3()
}
displayArea.onmouseout = function()
{
scrollHIS3()
}
imgPos = - pic0.width
for (var i = 0;i < imgPlaces+1;i++)
{
currentImage = document.getElementById("pic_"+i)
if (dir === 0)
{
imgPos += pic0.width + imgSpacer
}
initPos[i] = imgPos
if (dir === 0)
{
currentImage.style.left = initPos[i]+"px"
}
if (dir === 1)
{
document.getElementById("pic_"+[(imgPlaces-i)]).style.left = initPos[i]+"px"
imgPos += pic0.width + imgSpacer
}
if (nextPic == data.length)
{
nextPic = 0
}
currentImage.src = data[nextPic][0]
currentImage.alt = data[nextPic][1]
currentImage.i = nextPic
currentImage.onclick = function()
{
his3Win(data[this.i][2])
}
nextPic++
}
scrollHIS3()
}
timer = ""
function scrollHIS3()
{
clearTimeout(timer)
for (var i = 0;i < imgPlaces+1;i++)
{
currentImage = document.getElementById("pic_"+i)
nowDivPos[i] = parseInt(currentImage.style.left)
if (dir === 0)
{
nowDivPos[i] -= step
}
if (dir === 1)
{
nowDivPos[i] += step
}
if (dir === 0 && nowDivPos[i] <= -(pic0.width + imgSpacer) || dir == 1 && nowDivPos[i] > containerWidth)
{
if (dir === 0)
{
currentImage.style.left = containerWidth + imgSpacer + "px"
}
if (dir === 1)
{
currentImage.style.left = - pic0.width - (imgSpacer * 2) + "px"
}
if (nextPic > data.length-1)
{
nextPic = 0
}
currentImage.src=data[nextPic][0]
currentImage.alt=data[nextPic][1]
currentImage.i = nextPic
currentImage.onclick = function()
{
his3Win(data[this.i][2])
}
nextPic++
}
else
{
currentImage.style.left=nowDivPos[i] + "px"
}
}
timer = setTimeout("scrollHIS3()",speed)
}
function stopHIS3()
{
clearTimeout(timer)
}
function his3Win(loc)
{
if(loc === "")
{
return
}
if(newWindow === 0)
{
location = loc
}
else
{
newin = window.open(loc,'win1','left = 430,top = 340,width = 300 ,height = 300')
newin.focus()
}
}
</script>
I'm almost 100% sure that the problem lies in the array, but I can't seem to figure out what exactly the problem is..
Thanks in advance. :)
Try to use
position:relative;
and moving the first one from left to right / right to left(the others will follow accordingly as relative will tell em to follow the first image )
. i am pretty sure that that will start working on chrome then. as relative position tells it to use different positions. while opening your slider i found some bugs in chrome console : they all have the same left: thats getting changed together.