I have this slider that works on touch devices and it also detects mouse movement but the problem is that it detects all the movements that one makes, I would like you to help me by making it only detect when the finger or the mouse slides to the left or to the left. Right and right there you should let scroll down since wanting to see some other different information that is below the slider does not allow scrolling because the slider detects it and when dragging down what it does is move the images, only if you touch a space outside the slider if it drops. I would appreciate a lot if you could help me.
Here I share the complete code
var slidenumber = document.getElementsByClassName('content_inner').length;//how much slide
for(b=0; b<slidenumber; b++){
document.getElementById('buttons').innerHTML += '<span class="button"></span>';//adding buttons by slide number
}
var button = document.querySelectorAll(".button");//get array from buttons
var content = document.getElementsByClassName("content")[0];
button[0].classList.add('active');//adding active class to first button for default view
var a = 0;
for(let i=0; i<button.length; i++){
button[i].addEventListener('click', function (e) {
for(let z=0; z<button.length; z++){
button[z].classList.remove('active')// when click any button delete active class from others
}
button[i].classList.add('active');//adding active class clicking button
a = i;
content.style.transform = "translateX(calc(-100% * ("+ i +"-1))";
});
}
button2 = document.querySelectorAll(".slide_buttons_button");//getting next and prew buttons
for(t=0;t<button2.length;t++){
button2[t].addEventListener('click', function (e) {
if(e.target.id == "before_button"){//if button for prew it make variable x-1
a = a - 1;
if( a == -1){
a = slidenumber - 1
}
}
if(e.target.id == "after_button"){//if button for next it make variable x+1
a = a + 1;
if( a == slidenumber){
a = 0
}
}
for(let a=0; a < slidenumber; a++){
button[a].classList.remove('active')
}
button[a].classList.add('active');
content.style.transform = "translateX(calc(-100% * ("+ a +"))";//using variable for change slide
});
};
//touch sliding
var posN = 0,
posZ1 = 0,
posZ = 0,
yeni = 0,
dem = 0,
mytrans = window.getComputedStyle(content).getPropertyValue('transform'),
slides = content.getElementsByClassName('content_inner'),
slidesLength = slides.length,
slideSize = content.getElementsByClassName('content_inner')[0].offsetWidth;
// mouse events
content.onmousedown = dragStart;
// touch events
content.addEventListener('touchstart', dragStart);
content.addEventListener('touchend', dragEnd);
content.addEventListener('touchmove', dragAction);
function dragStart (e) {
e = e || window.event;
e.preventDefault();
//posInitial = content.offsetLeft;
posN = 0;
posZ = 0;
if (e.type == 'touchstart') {
posX1 = e.touches[0].clientX;
} else {
posX1 = e.clientX;
}
if (e.type == 'touchstart') {
posX2 = e.touches[0].clientX;
} else {
posX2 = e.clientX;
document.onmouseup = dragEnd;
document.onmousemove = dragAction;
}
if (e.type == 'touchstart') {
posX3 = e.touches[0].clientX;
}
else {
posX3 = e.clientX;
}
}
function dragAction (e) {
e = e || window.event;
if (e.type == 'touchmove') {
posN = e.touches[0].clientX - posX1;
posX1 = e.touches[0].clientX;
} else {
posN = e.clientX - posX1;
posX1 = e.clientX;
}
if (e.type == 'touchmove') {
posZ = posX2 - e.touches[0].clientX;
posX2 = e.touches[0].clientX;
} else {
posZ = posX2 - e.clientX;
posX2 = e.clientX;
}
var myff = posX2 - posX3;
content.style.transform = "translateX(calc((-100% * ("+ a +")) + ("+ myff +"px)))";
console.log("calc((-100% * ("+ a +")) + ("+ myff +"px))");
if(mytrans !== "none"){
dem = parseInt((mytrans.replace (/,/g, "")).split(" ")[4]);
}
else{
mytrans = window.getComputedStyle(content).getPropertyValue('transform');
}
console.log(myff)
}
function dragEnd (e) {
if(mytrans !== "none"){
posFinal = parseInt((mytrans.replace (/,/g, "")).split(" ")[4]);
};
//console.log(posN)
if (posN < 0) {
//console.log("burda knk1");
content.style.transform = "translateX(calc(-100% * ("+ a +" + 1))";
a = a + 1;
if( a == slidenumber){
a = 0
}
} else if (posN > 0) {
//console.log("burda knk2");
content.style.transform = "translateX(calc(-100% * ("+ a +" - 1))";
a = a - 1;
if( a == -1){
a = slidenumber - 1
}
}
for(let z=0; z<button.length; z++){
button[z].classList.remove('active')
}
button[a].classList.add('active');
content.style.transform = "translateX(calc(-100% * ("+ a +")";
document.onmouseup = null;
document.onmousemove = null;
}
function timeout() {
setTimeout(function () {
a = a + 1;
if( a == slidenumber){
a = 0
}
content.style.transform = "translateX(calc(-100% * ("+ a +"))";
for(let z=0; z<button.length; z++){
button[z].classList.remove('active')
}
button[a].classList.add('active');
timeout();
}, 5000)
}
timeout();
* {
width:100%;
box-sizing: border-box;
}
body {
margin: 0;
width: 100%;
height: 100vh;
}
.wrapper {
width: 100%;
max-width: 100%;
margin: auto;
}
.container {
overflow-x: hidden;
width: 100%;
position: absolute;
}
#buttons {
display: flex;
justify-content: center;
top: -1rem;
position: relative;
}
#buttons .button {
width: 0.75rem;
height: 0.75rem;
border: 1px solid grey;
border-radius: 50%;
margin-right: 0.25rem;
cursor: pointer;
}
#buttons .button.active {
background: green;
}
.content {
display: flex;
position: relative;
width: 100%;
transition: 350ms ease;
}
.content_inner {
background: grey;
flex-shrink: 0;
display: flex;
align-items: center;
justify-content: center;
width: 100%;
}
.slide_buttons_button.active {
background: green;
}
.content.toggle1 {
transform: translateX(-100%);
}
#media (orientation:landscape){
.content_inner img{
height: 95vh;
}
}
<div class="wrapper">
<div class="container">
<div class="content">
<div class="content_inner"> <img src="https://www.themoviedb.org/t/p/original/jqwM0nhOLEFI1HHBabwr80Od3TC.jpg"></div>
<div class="content_inner"><img src="https://www.themoviedb.org/t/p/original/7d6EY00g1c39SGZOoCJ5Py9nNth.jpg"></div>
<div class="content_inner"><img src="https://www.themoviedb.org/t/p/original/6qVF0gnLnbKCgcMfCpCB8GH7B5I.jpg"></div>
<div class="content_inner"><img src="https://www.themoviedb.org/t/p/original/jqwM0nhOLEFI1HHBabwr80Od3TC.jpg"></div>
<div class="content_inner"><img src="https://www.themoviedb.org/t/p/original/7d6EY00g1c39SGZOoCJ5Py9nNth.jpg"></div>
<div class="content_inner"><img src="https://www.themoviedb.org/t/p/original/jqwM0nhOLEFI1HHBabwr80Od3TC.jpg"></div>
<div class="content_inner"><img src="https://www.themoviedb.org/t/p/original/7d6EY00g1c39SGZOoCJ5Py9nNth.jpg"></div>
</div>
<div id="buttons"></div>
<div class="slide_buttons">
<div class="slide_buttons_button" id="before_button"></div>
<div class="slide_buttons_button" id="after_button"></div>
</div>
</div>
</div>
Related
When I change the width of the page it does not stretch in width. Sorry for my English. #How to make the slider width change when Resize.# For some reason, it remembers the first width.
Resize width and transform Please help me. I want to change the width of the screen and have the slider adjust to the width. This code is in pure Javascript. Who can help. I've been racking my head for 3 days, I'm just a beginner.
(function() {
let curTranslateX = 0;
let curPageNum = 0;
let dots = null;
let slideWidth = 0;
let duration = 300;
let pointStart, pointMove, pointEnd;
let slidePositions = [];
let isAutoLoop = false;
let hasArrow = true;
let scrollbar = {
el: '.slide-navbar',
isHide: true,
canClick: true
};
let slideContainer = document.querySelector('.container_slider');
let slideWrapper = slideContainer.querySelector('.slide_wrapper');
let slideItems = [...slideWrapper.querySelectorAll('.slide-item')];
const utils = {
hasClass: function(elem, className) {
return(new RegExp('(\\s|^)' + className + '(\\s|$)')).test(elem.className);
},
addClass: function(elem, className) {
if(!arguments.length) {
return;
}
if(typeof className === 'undefined' || this.hasClass(elem, className)) {
return;
}
let newClasses = elem.className.split(' ');
newClasses.push(className);
elem.className = newClasses.join(' ');
},
removeClass: function(elem, className) {
if(!arguments.length) {
return;
}
if(typeof className === 'undefined' || !this.hasClass(elem, className)) {
return;
}
let classes = elem.className.split(' ');
classes = classes.filter(cls => cls !== className);
elem.className = classes.join(' ');
},
isMobile: function() {
return(/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i).test(navigator.userAgent);
}
}
var slide = {
init: (function() {
document.addEventListener('DOMContentLoaded', function() {
dots = [...document.querySelectorAll('.slide-navbar span')];
dots.forEach(dot => {
utils.addClass(dot, 'dot');
});
if(utils.isMobile()) {
pointStart = 'touchstart';
pointMove = 'touchmove';
pointEnd = 'touchend';
} else {
pointStart = 'pointerdown';
pointMove = 'pointermove';
pointEnd = 'pointerup';
}
slide.bindTouchEvent();
slide.setCurrentPage();
}.bind(slide), false);
})(),
setTranslate: function(duration, offsetX, ...yz) {
this.style = `transition-duration: ${duration}ms; transform: translate3d(${offsetX}px, 0px, 0px);`;
curTranslateX = offsetX;
},
setCurrentPage: function(num) {
if(curPageNum !== -1) {
utils.removeClass(dots[curPageNum], 'dot-active');
utils.removeClass(slideItems[curPageNum], 'slide-active');
}
num = (typeof num === 'undefined') ? 0 : num;
curPageNum = num;
utils.addClass(dots[curPageNum], 'dot-active');
utils.addClass(slideItems[curPageNum], 'slide-active');
},
gotoPage: function(num) {
if(num < 0 || num > dots.length - 1) {
return;
}
slide.setTranslate.call(slideWrapper, duration, slidePositions[num]);
setTimeout(() => {
slide.setCurrentPage(num);
}, duration / 2);
},
bindTouchEvent: function() {
slideWidth = slideItems[0].scrollWidth;
slideContainer.style.width = `${slideWidth}px`;
let negMaxWidth = -slideWidth * (slideItems.length - 1);
for(let i = 0, wtd = 0; i < slideItems.length; i++, wtd -= slideWidth) {
slidePositions.push(wtd);
}
let startX,
startY,
initialPos = 0,
moveDist = 0,
direction = 0,
isMove = false,
startT = 0,
isPointOut = true;
slideContainer.addEventListener(pointStart, function(e) {
e.preventDefault();
if(!isPointOut && e.touches.length !== 1) {
return;
}
let startPoint = e.touches[0];
startX = startPoint.pageX;
startY = startPoint.pageY;
initialPos = curTranslateX;
startT = +new Date();
isMove = false;
isPointOut = false;
}.bind(this), false);
slideContainer.addEventListener(pointMove, function(e) {
if(isPointOut) {
return
}
let movePoint = e.touches[0];
let deltaX = movePoint.pageX - startX;
let deltaY = movePoint.pageY - startY;
let offsetX = initialPos + deltaX;
if(offsetX > 0 || offsetX < negMaxWidth) {
offsetX -= (deltaX / 2);
}
this.setTranslate.call(slideWrapper, 0, offsetX);
isMove = true;
deltaX = offsetX - initialPos;
moveDist = deltaX;
direction = deltaX > 0 ? 0 : 1;
}.bind(this), false);
slideContainer.addEventListener(pointEnd, function(e) {
e.preventDefault();
let deltaT = +new Date() - startT;
if(!isMove) {
if(utils.hasClass(e.target, 'slide-button-prev')) {
if(curPageNum === 0) {
return;
}
slide.gotoPage.call(e.target, curPageNum - 1);
} else if(utils.hasClass(e.target, 'slide-button-next')) {
if(curPageNum === dots.length - 1) {
return;
}
slide.gotoPage.call(e.target, curPageNum + 1);
}
return;
}
if(isPointOut) {
return;
}
isPointOut = true;
if(deltaT < 300 || Math.abs(moveDist) > slideWidth / 2) {
offsetX = direction === 0 ? curTranslateX + slideWidth - moveDist : curTranslateX - slideWidth - moveDist;
offsetX = offsetX > 0 ? 0 : offsetX;
offsetX = offsetX < negMaxWidth ? negMaxWidth : offsetX;
} else {
offsetX = curTranslateX - moveDist;
}
slide.setTranslate.call(slideWrapper, duration, offsetX);
let newPageNum = Math.round(Math.abs(offsetX) / slideWidth);
setTimeout(() => {
this.setCurrentPage(newPageNum);
}, duration / 2);
}.bind(this), false);
},
};
})();
.container_box {
max-width: 1400px;
margin: 0 auto;
}
.container_slider {
position: relative;
overflow: hidden;
}
.slide_wrapper {
position: relative;
z-index: 1;
display: flex;
transition-property: transform;
}
.container_slider .slide-item {
z-index: 1;
display: flex;
flex-shrink: 0;
width: 100%;
height: 300px;
user-select: none;
background-size: cover;
background-position: 50%;
background-repeat: no-repeat;
}
.slide-navbar {
position: absolute;
right: 0;
left: 0;
bottom: 0;
text-align: center;
font-size: 0;
z-index: 2;
}
.dot {
display: inline-block;
margin: 0 4px;
width: 8px;
height: 8px;
border-radius: 50%;
background-color: rgba(255, 255, 255, 0.5);
}
.dot-active {
width: 20px;
border-radius: 6px;
background-color: rgba(233, 233, 233, .9);
}
.slide-button-prev,
.slide-button-next {
display: inline-block;
position: absolute;
top: 50%;
width: 40px;
height: 60px;
z-index: 2;
color: rgba(233, 233, 233, .9);
text-align: center;
font-weight: 500;
}
.slide-button-prev {
left: 0;
transform: translateY(-50%);
}
.slide-button-next {
right: 0;
transform: translateY(-50%);
}
<div class="container_box">
<div class="container_slider">
<div class="slide_wrapper">
<div class="slide-item slide-active" style="background-color:green;"></div>
<div class="slide-item" style="background-color:blue;"></div>
<div class="slide-item" style="background-color:black;"></div>
</div>
<div class="control_slider slide-button-prev"><</div>
<div class="control_slider slide-button-next">></div>
<div class="slide-navbar">
<span class="dot dot-active">1</span>
<span class="dot">2</span>
<span class="dot">3</span>
</div>
</div>
</div>
First: I replaced the < and > by > and <:
<div class="control_slider slide-button-prev"><</div>
<div class="control_slider slide-button-next">></div>
To your question:
I found out that in bindTouchEvent: function() {}
exists the line
slideContainer.style.width = ${slideWidth}px;
This line is in charge to set a fix width. If you comment out this line all single slide-items reacts on resize.
I have a large background image and some much smaller images for the user to drag around on the background. I need this to be efficient in terms of performance, so i'm trying to avoid libraries. I'm fine with drag 'n' drop if it work's well, but im trying to get drag.
Im pretty much trying to do this. But after 8 years there must be a cleaner way to do this right?
I currently have a drag 'n' drop system that almost works, but when i drop the smaller images, they are just a little off and it's very annoying. Is there a way to fix my code, or do i need to take a whole different approach?
This is my code so far:
var draggedPoint;
function dragStart(event) {
draggedPoint = event.target; // my global var
}
function drop(event) {
event.preventDefault();
let xDiff = draggedPoint.x - event.pageX;
let yDiff = draggedPoint.y - event.pageY;
let left = draggedPoint.style.marginLeft; // get margins
let top = draggedPoint.style.marginTop;
let leftNum = Number(left.substring(0, left.length - 2)); // cut off px from the end
let topNum = Number(top.substring(0, top.length - 2));
let newLeft = leftNum - xDiff + "px" // count new margins and put px back to the end
let newTop = topNum - yDiff + "px"
draggedPoint.style.marginLeft = newLeft;
draggedPoint.style.marginTop = newTop;
}
function allowDrop(event) {
event.preventDefault();
}
let imgs = [
"https://upload.wikimedia.org/wikipedia/commons/6/67/Orange_juice_1_edit1.jpg",
"https://upload.wikimedia.org/wikipedia/commons/f/ff/Solid_blue.svg",
"https://upload.wikimedia.org/wikipedia/commons/b/b4/Litoria_infrafrenata_-_Julatten.jpg"
]
/* my smaller images: */
for (let i = 0; i < 6; i++) {
let sensor = document.createElement("img");
sensor.src = imgs[i % imgs.length];
sensor.alt = i;
sensor.draggable = true;
sensor.classList.add("sensor");
sensor.style.marginLeft = `${Math.floor(Math.random() * 900)}px`
sensor.style.marginTop = `${Math.floor(Math.random() * 500)}px`
sensor.onclick = function() {
sensorClick(logs[i].id)
};
sensor.addEventListener("dragstart", dragStart, null);
let parent = document.getElementsByClassName("map")[0];
parent.appendChild(sensor);
}
<!-- my html: -->
<style>
.map {
width: 900px;
height: 500px;
align-content: center;
margin: 150px auto 150px auto;
}
.map .base {
position: absolute;
width: inherit;
height: inherit;
}
.map .sensor {
position: absolute;
width: 50px;
height: 50px;
}
</style>
<div class="map" onDrop="drop(event)" ondragover="allowDrop(event)">
<img src='https://upload.wikimedia.org/wikipedia/commons/f/f7/Plan-Oum-el-Awamid.jpg' alt="pohja" class="base" draggable="false">
<div>
With the answers from here and some time i was able to get a smooth drag and click with pure js.
Here is a JSFiddle to see it in action.
let maxLeft;
let maxTop;
const minLeft = 0;
const minTop = 0;
let timeDelta;
let imgs = [
"https://upload.wikimedia.org/wikipedia/commons/6/67/Orange_juice_1_edit1.jpg",
"https://upload.wikimedia.org/wikipedia/commons/f/ff/Solid_blue.svg",
"https://upload.wikimedia.org/wikipedia/commons/b/b4/Litoria_infrafrenata_-_Julatten.jpg"
]
var originalX;
var originalY;
window.onload = function() {
document.onmousedown = startDrag;
document.onmouseup = stopDrag;
}
function sensorClick () {
if (Date.now() - timeDelta < 150) { // check that we didn't drag
createPopup(this);
}
}
// create a popup when we click
function createPopup(parent) {
let p = document.getElementById("popup");
if (p) {
p.parentNode.removeChild(p);
}
let popup = document.createElement("div");
popup.id = "popup";
popup.className = "popup";
popup.style.top = parent.y - 110 + "px";
popup.style.left = parent.x - 75 + "px";
let text = document.createElement("span");
text.textContent = parent.id;
popup.appendChild(text);
var map = document.getElementsByClassName("map")[0];
map.appendChild(popup);
}
// when our base is loaded
function baseOnLoad() {
var map = document.getElementsByClassName("map")[0];
let base = document.getElementsByClassName("base")[0];
maxLeft = base.width - 50;
maxTop = base.height - 50;
/* my smaller images: */
for (let i = 0; i < 6; i++) {
let sensor = document.createElement("img");
sensor.src = imgs[i % imgs.length];
sensor.alt = i;
sensor.id = i;
sensor.draggable = true;
sensor.classList.add("sensor");
sensor.classList.add("dragme");
sensor.style.left = `${Math.floor(Math.random() * 900)}px`
sensor.style.top = `${Math.floor(Math.random() * 500)}px`
sensor.onclick = sensorClick;
let parent = document.getElementsByClassName("map")[0];
parent.appendChild(sensor);
}
}
function startDrag(e) {
timeDelta = Date.now(); // get current millis
// determine event object
if (!e) var e = window.event;
// prevent default event
if(e.preventDefault) e.preventDefault();
// IE uses srcElement, others use target
targ = e.target ? e.target : e.srcElement;
originalX = targ.style.left;
originalY = targ.style.top;
// check that this is a draggable element
if (!targ.classList.contains('dragme')) return;
// calculate event X, Y coordinates
offsetX = e.clientX;
offsetY = e.clientY;
// calculate integer values for top and left properties
coordX = parseInt(targ.style.left);
coordY = parseInt(targ.style.top);
drag = true;
document.onmousemove = dragDiv; // move div element
return false; // prevent default event
}
function dragDiv(e) {
if (!drag) return;
if (!e) var e = window.event;
// move div element and check for borders
let newLeft = coordX + e.clientX - offsetX;
if (newLeft < maxLeft && newLeft > minLeft) targ.style.left = newLeft + 'px'
let newTop = coordY + e.clientY - offsetY;
if (newTop < maxTop && newTop > minTop) targ.style.top = newTop + 'px'
return false; // prevent default event
}
function stopDrag() {
if (typeof drag == "undefined") return;
if (drag) {
if (Date.now() - timeDelta > 150) { // we dragged
let p = document.getElementById("popup");
if (p) {
p.parentNode.removeChild(p);
}
} else {
targ.style.left = originalX;
targ.style.top = originalY;
}
}
drag = false;
}
.map {
width: 900px;
height: 500px;
margin: 50px
position: relative;
}
.map .base {
position: absolute;
width: inherit;
height: inherit;
}
.map .sensor {
display: inline-block;
position: absolute;
width: 50px;
height: 50px;
}
.dragme {
cursor: move;
left: 0px;
top: 0px;
}
.popup {
position: absolute;
display: inline-block;
width: 200px;
height: 100px;
background-color: #9FC990;
border-radius: 10%;
}
.popup::after {
content: "";
position: absolute;
top: 100%;
left: 50%;
margin-left: -10px;
border-width: 10px;
border-style: solid;
border-color: #9FC990 transparent transparent transparent;
}
.popup span {
width: 90%;
margin: 10px;
display: inline-block;
text-align: center;
}
<div class="map" width="950px" height="500px">
<img src='https://upload.wikimedia.org/wikipedia/commons/f/f7/Plan-Oum-el-Awamid.jpg' alt="pohja" class="base" draggable="false" onload="baseOnLoad()">
<div>
I noticed these resize pointers in the css spec...
https://drafts.csswg.org/css-ui-3/#valdef-cursor-se-resize
Is there a CSS shortcut for 4 corner resizability similar to the one corner ('resize: both') method?
If not, are there known conflicts when combining resizability with a draggable div?
My starting point was here...
https://www.w3schools.com/howto/howto_js_draggable.asp
Any help navigating the posX, posY is appreciated.
notes for getBoundingClient()
———---
| |
|____ | div.getBoundingClientRect()
SE (bottom right):
Height and width / top and left are stationary
SW (bottom left):
Height and width and left / top is stationary
NW (top left):
Height and width top and left
NE (top right):
Height and width and Top / Left is stationary
edit: removed padding and borders.
const myDiv = document.getElementById('mydiv')
let isResizing = false;
//Make the DIV element draggable:
dragElement(myDiv);
function dragElement(elmnt) {
if (!isResizing) {
let pos1 = 0,
pos2 = 0,
pos3 = 0,
pos4 = 0;
if (document.getElementById(elmnt.id + "header")) {
//if present, the header is where you move the DIV from:
document.getElementById(elmnt.id + "header").onmousedown = dragMouseDown;
} else {
//otherwise, move the DIV from anywhere inside the DIV:
elmnt.onmousedown = dragMouseDown;
}
function dragMouseDown(e) {
e = e || window.event;
e.preventDefault();
// get the mouse cursor position at startup:
pos3 = e.clientX;
pos4 = e.clientY;
document.onmouseup = closeDragElement;
// call a function whenever the cursor moves:
document.onmousemove = elementDrag;
}
function elementDrag(e) {
e = e || window.event;
e.preventDefault();
// calculate the new cursor position:
pos1 = pos3 - e.clientX;
pos2 = pos4 - e.clientY;
pos3 = e.clientX;
pos4 = e.clientY;
// set the element's new position:
elmnt.style.top = (elmnt.offsetTop - pos2) + "px";
elmnt.style.left = (elmnt.offsetLeft - pos1) + "px";
}
function closeDragElement() {
//stop moving when mouse button is released:
document.onmouseup = null;
document.onmousemove = null;
}
}
}
// Resize
(function fourCorners() {
const resizers = document.querySelectorAll('.resizer')
let currentResizer
for (let resizer of resizers) {
resizer.addEventListener('mousedown', mouseDown)
function mouseDown(e) {
currentResizer = e.target
e.preventDefault()
isResizing = true;
let posX = e.clientX;
let posY = e.clientY;
myDiv.addEventListener('mousemove', mouseMove)
myDiv.addEventListener('mouseup', mouseUp)
function mouseMove(e) {
e.preventDefault()
const rect = myDiv.getBoundingClientRect()
if (currentResizer.classList.contains('se')) {
//console.log(currentResizer.classList.value)
myDiv.style.width = rect.width - (posX - e.clientX) + 'px';
myDiv.style.height = rect.height - (posY - e.clientY) + 'px';
} else if (currentResizer.classList.contains('sw')) {
//console.log(currentResizer.classList.value)
myDiv.style.width = rect.width + (posX - e.clientX) + 'px';
myDiv.style.height = rect.height - (posY - e.clientY) + 'px';
myDiv.style.left = rect.left - (posX - e.clientX) + 'px';
} else if (currentResizer.classList.contains('ne')) {
//console.log(currentResizer.classList.value)
myDiv.style.width = rect.width - (posX - e.clientX) + 'px';
myDiv.style.height = rect.height + (posY - e.clientY) + 'px';
myDiv.style.top = rect.top - (posY - e.clientY) + 'px';
} else {
//console.log(currentResizer.classList.value)
myDiv.style.width = rect.width + (posX - e.clientX) + 'px';
myDiv.style.height = rect.height + (posY - e.clientY) + 'px';
myDiv.style.top = rect.top - (posY - e.clientY) + 'px';
myDiv.style.left = rect.left - (posX - e.clientX) + 'px';
}
posX = e.clientX;
posY = e.clientY;
}
function mouseUp(e) {
myDiv.removeEventListener('mousemove', mouseMove)
myDiv.removeEventListener('mouseup', mouseUp)
isResizing = false
}
}
}
})()
* {
margin: 0;
padding : 0;
}
#mydiv {
position: absolute; /* NECESSARY */
background-color: whitesmoke;
box-sizing: border-box;
text-align: center;
/* border: 1px solid #222; */
height: 200px;
width: 200px;
/* resize: both; /* CSS RESIZE */
overflow: hidden; /* CSS RESIZE */
}
#mydivheader {
/* padding: 10px; */
cursor: move;
background-color: dodgerblue;
color: #fff;
}
#content {
color: #000;
margin: 0px;
background-color: whitesmoke;
}
/* ::-webkit-resizer {
position: absolute;
height: 20px;
width: 20px;
border-top-left-radius: 25px;
background-color: #dd0;
z-index: 2;
} */
.resizer {
position: absolute;
height: 20px;
width: 20px;
background-color: #dd0;
z-index: 2;
}
.resizer.nw {
top: -1px;
left: -1px;
cursor: nw-resize;
border-bottom-right-radius: 25px;
}
.resizer.ne {
top: -1px;
right: -1px;
cursor: ne-resize;
border-bottom-left-radius: 25px;
}
.resizer.sw {
bottom: -1px;
left: -1px;
cursor: sw-resize;
border-top-right-radius: 25px;
}
.resizer.se {
bottom: -1px;
right: -1px;
cursor: se-resize;
border-top-left-radius: 25px;
}
<div id="mydiv">
<div class='resizer nw'></div>
<div class='resizer ne'></div>
<div class='resizer sw'></div>
<div class='resizer se'></div>
<div id="mydivheader">Click here to move
<div id='content'>
<div id='image-container'><img height='auto' width='100%' src='https://picsum.photos/600' /></div>
</div>
</div>
</div>
Well if you want to make it nice and easy you could use jQuery to help it resize would probably be the easiest way. Then after you learn how to do it with jQuery you could do it with pure js.
So, you want the resize handle to appear on all four corners? That'll require some bounds checking.
You can modify the offset check in drag to account for any corner and handle the drag as a resize event instead. The code somewhat works for top-left and bottom-right resizing, but doe not work too well with the opposite corners. This is a start.
This is a start:
const cursor = document.querySelector('#cursor');
const cornerThreshold = 4;
const dragStart = e => {
const [ horz, vert ] = getDirection(e, cornerThreshold);
const bounds = e.target.getBoundingClientRect();
const cursor = getCursorType(e);
if (cursor === 'grab') {
e.target.dataset.isDragging = true;
} else {
e.target.dataset.isResizing = true;
}
e.target.dataset.startWidth = bounds.width;
e.target.dataset.startHeight = bounds.height;
e.target.dataset.originX = e.clientX;
e.target.dataset.originY = e.clientY;
e.target.dataset.offsetX = e.clientX - e.target.offsetLeft;
e.target.dataset.offsetY = e.clientY - e.target.offsetTop;
e.target.dataset.dirHorz = horz;
e.target.dataset.dirVert = vert;
e.target.style.zIndex = 999;
};
const dragEnd = e => {
delete e.target.dataset.isDragging;
delete e.target.dataset.offsetX;
delete e.target.dataset.offsetY;
delete e.target.dataset.originX;
delete e.target.dataset.originY;
delete e.target.dataset.startWidth;
delete e.target.dataset.startHeight;
delete e.target.dataset.dirHorz;
delete e.target.dataset.dirVert;
delete e.target.dataset.resizeDirection;
e.target.style.removeProperty('z-index');
e.target.style.removeProperty('cursor');
};
const drag = e => {
e.target.style.cursor = getCursorType(e);
cursor.textContent = `(${e.clientX}, ${e.clientY})`;
if (e.target.dataset.isDragging) {
e.target.style.left = `${e.clientX - parseInt(e.target.dataset.offsetX, 10)}px`;
e.target.style.top = `${e.clientY - parseInt(e.target.dataset.offsetY, 10)}px`;
} else if (e.target.dataset.isResizing) {
const bounds = e.target.getBoundingClientRect();
const startWidth = parseInt(e.target.dataset.startWidth, 10);
const startHeight = parseInt(e.target.dataset.startWidth, 10);
const deltaX = e.clientX - parseInt(e.target.dataset.originX, 10);
const deltaY = e.clientY - parseInt(e.target.dataset.originY, 10);
const originX = parseInt(e.target.dataset.originX, 10);
const originY = parseInt(e.target.dataset.originY, 10);
const dirHorz = parseInt(e.target.dataset.dirHorz, 10);
const dirVert = parseInt(e.target.dataset.dirVert, 10);
if (dirHorz < 0) {
e.target.style.left = `${originX + deltaX}px`;
e.target.style.width = `${startWidth - deltaX}px`
} else if (dirHorz > 0) {
e.target.style.width = `${startWidth + deltaX}px`;
}
if (dirVert < 0) {
e.target.style.top = `${originY + deltaY}px`;
e.target.style.height = `${startHeight - deltaY}px`;
} else if (dirVert > 0) {
e.target.style.height = `${startHeight + deltaY}px`;
}
}
};
const focus = e => { };
const unfocus = e => { e.target.style.removeProperty('cursor'); };
const getDirection = (e, threshold) => {
const bounds = e.target.getBoundingClientRect();
const offsetX = e.clientX - e.target.offsetLeft;
const offsetY = e.clientY - e.target.offsetTop;
const isTop = offsetY <= threshold;
const isLeft = offsetX <= threshold;
const isBottom = offsetY > (bounds.height - threshold);
const isRight = offsetX > (bounds.width - threshold);
if (isTop && isLeft) return [ -1, -1 ];
else if (isTop && isRight) return [ -1, 1 ];
else if (isBottom && isLeft) return [ 1, -1 ];
else if (isBottom && isRight) return [ 1, 1 ];
else return [ 0, 0 ];
};
const getCursorType = (e) => {
if (e.target.dataset.isDragging) {
return 'grabbing';
} else {
const [ horz, vert ] = getDirection(e, cornerThreshold);
const isTop = vert === -1;
const isLeft = horz === -1;
const isBottom = vert === 1;
const isRight = horz === 1;
if ((isTop && isLeft) || (isBottom && isRight)) return 'nwse-resize';
if ((isTop && isRight) || (isBottom && isLeft)) return 'nesw-resize';
}
return 'grab';
};
document.querySelectorAll('.draggable').forEach(draggable => {
draggable.addEventListener('mousedown', dragStart);
draggable.addEventListener('mouseup', dragEnd);
draggable.addEventListener('mousemove', drag);
draggable.addEventListener('mouseenter', focus);
draggable.addEventListener('mouseleave', unfocus);
});
html, body {
margin: 0;
padding: 0;
width: 100%;
height: 100%;
}
.container {
position: relative;
width: 60%;
height: 60%;
border: thin solid grey;
}
.square {
position: absolute;
height: 2em;
width: 2em;
}
.color-red { background: red; }
.color-blue { background: blue; }
.color-green { background: green; }
#square-1 { top: 10px; left: 10px; }
#square-2 { top: 50px; left: 50px; }
#square-3 { top: 100px; left: 100px; }
<div class="container">
<div id="square-1" class="square color-red draggable resizable"></div>
<div id="square-2" class="square color-blue draggable resizable"></div>
<div id="square-3" class="square color-green draggable resizable"></div>
</div>
<br />
<div>Cursor: <span id="cursor">(0, 0)</span></div>
I am trying to add a generic game menu with "start" to initiate the game. How do I go about doing this? Here is the code:
var LEFT_KEY = 37;
var UP_KEY = 38;
var RIGHT_KEY = 39;
var DOWN_KEY = 40;
var SPACE_KEY = 32;
var HERO_MOVEMENT = 3;
var lastLoopRun = 0;
var score = 0;
var iterations = 0;
var controller = new Object();
var enemies = new Array();
function createSprite(element, x, y, w, h) {
var result = new Object();
result.element = element;
result.x = x;
result.y = y;
result.w = w;
result.h = h;
return result;
}
function toggleKey(keyCode, isPressed) {
if (keyCode == LEFT_KEY) {
controller.left = isPressed;
}
if (keyCode == RIGHT_KEY) {
controller.right = isPressed;
}
if (keyCode == UP_KEY) {
controller.up = isPressed;
}
if (keyCode == DOWN_KEY) {
controller.down = isPressed;
}
if (keyCode == SPACE_KEY) {
controller.space = isPressed;
}
}
function intersects(a, b) {
return a.x < b.x + b.w && a.x + a.w > b.x && a.y < b.y + b.h && a.y + a.h > b.y;
}
function ensureBounds(sprite, ignoreY) {
if (sprite.x < 20) {
sprite.x = 20;
}
if (!ignoreY && sprite.y < 20) {
sprite.y = 20;
}
if (sprite.x + sprite.w > 480) {
sprite.x = 480 - sprite.w;
}
if (!ignoreY && sprite.y + sprite.h > 480) {
sprite.y = 480 - sprite.h;
}
}
function setPosition(sprite) {
var e = document.getElementById(sprite.element);
e.style.left = sprite.x + 'px';
e.style.top = sprite.y + 'px';
}
function handleControls() {
if (controller.up) {
hero.y -= HERO_MOVEMENT;
}
if (controller.down) {
hero.y += HERO_MOVEMENT;
}
if (controller.left) {
hero.x -= HERO_MOVEMENT;
}
if (controller.right) {
hero.x += HERO_MOVEMENT;
}
if (controller.space) {
var laser = getFireableLaser();
if (laser) {
laser.x = hero.x + 9;
laser.y = hero.y - laser.h;
}
}
ensureBounds(hero);
}
function getFireableLaser() {
var result = null;
for (var i = 0; i < lasers.length; i++) {
if (lasers[i].y <= -120) {
result = lasers[i];
}
}
return result;
}
function getIntersectingLaser(enemy) {
var result = null;
for (var i = 0; i < lasers.length; i++) {
if (intersects(lasers[i], enemy)) {
result = lasers[i];
break;
}
}
return result;
}
function checkCollisions() {
for (var i = 0; i < enemies.length; i++) {
var laser = getIntersectingLaser(enemies[i]);
if (laser) {
var element = document.getElementById(enemies[i].element);
element.style.visibility = 'hidden';
element.parentNode.removeChild(element);
enemies.splice(i, 1);
i--;
laser.y = -laser.h;
score += 100;
} else if (intersects(hero, enemies[i])) {
gameOver();
} else if (enemies[i].y + enemies[i].h >= 500) {
var element = document.getElementById(enemies[i].element);
element.style.visibility = 'hidden';
element.parentNode.removeChild(element);
enemies.splice(i, 1);
i--;
}
}
}
function gameOver() {
var element = document.getElementById(hero.element);
element.style.visibility = 'hidden';
element = document.getElementById('gameover');
element.style.visibility = 'visible';
}
function showSprites() {
setPosition(hero);
for (var i = 0; i < lasers.length; i++) {
setPosition(lasers[i]);
}
for (var i = 0; i < enemies.length; i++) {
setPosition(enemies[i]);
}
var scoreElement = document.getElementById('score');
scoreElement.innerHTML = 'SCORE: ' + score;
}
function updatePositions() {
for (var i = 0; i < enemies.length; i++) {
enemies[i].y += 4;
enemies[i].x += getRandom(7) - 3;
ensureBounds(enemies[i], true);
}
for (var i = 0; i < lasers.length; i++) {
lasers[i].y -= 12;
}
}
function addEnemy() {
var interval = 50;
if (iterations > 1500) {
interval = 5;
} else if (iterations > 1000) {
interval = 20;
} else if (iterations > 500) {
interval = 35;
}
if (getRandom(interval) == 0) {
var elementName = 'enemy' + getRandom(10000000);
var enemy = createSprite(elementName, getRandom(450), -40, 35, 35);
var element = document.createElement('div');
element.id = enemy.element;
element.className = 'enemy';
document.children[0].appendChild(element);
enemies[enemies.length] = enemy;
}
}
function getRandom(maxSize) {
return parseInt(Math.random() * maxSize);
}
function loop() {
if (new Date().getTime() - lastLoopRun > 40) {
updatePositions();
handleControls();
checkCollisions();
addEnemy();
showSprites();
lastLoopRun = new Date().getTime();
iterations++;
}
setTimeout('loop();', 2);
}
document.onkeydown = function(evt) {
toggleKey(evt.keyCode, true);
};
document.onkeyup = function(evt) {
toggleKey(evt.keyCode, false);
};
var hero = createSprite('hero', 250, 460, 20, 20);
var lasers = new Array();
for (var i = 0; i < 3; i++) {
lasers[i] = createSprite('laser' + i, 0, -120, 2, 50);
}
loop();
#hero {
/* background: #ff0000; */
background-image: url("man-of-space.png");
width: 40px;
height: 40px;
position: absolute;
}
#background {
background-image: url("space.png");
/* background: #000000; */
width: 500px;
height: 500px;
position: absolute;
left: 0px;
top: 0px;
}
.laser {
background: #00ff00;
width: 2px;
height: 50px;
position: absolute;
}
.enemy {
background-image: url("spaceship.png");
background-size: 40px 40px;
width: 40px;
height: 40px;
position: absolute;
}
#score {
color: #ffffff;
font-size: 18pt;
position: absolute;
left: 20px;
top: 20px;
}
#gameover {
color: #ff0000;
font-size: 20px;
position: absolute;
left: 160px;
top: 200px;
visibility: hidden;
}
<div id="background"></div>
<div id="hero"></div>
<div class="laser" id="laser0"></div>
<div class="laser" id="laser1"></div>
<div class="laser" id="laser2"></div>
<div id="score"></div>
<div id="gameover">GAME OVER</div>
You could wrap your game UI in a <div id="game" style="display: none;"> element so it will be hidden when the page is loaded. Then wrap your start menu in a <div id="startMenu"> element with a <button id="startButton">Start</button> that will be used to hide the start menu and show the game UI.
In your JS code you could wrap your game in a function so it can be started when you call it.
HTML:
<div id="startMenu">
<button id="startButton">Start</button>
</div>
<div id="game" style="display: none;">
<div id="background"></div>
<div id="hero"></div>
<div class="laser" id="laser0"></div>
<div class="laser" id="laser1"></div>
<div class="laser" id="laser2"></div>
<div id="score"></div>
<div id="gameover">GAME OVER</div>
</div>
JS:
function startGame() {
var LEFT_KEY = 37;
var UP_KEY = 38;
var RIGHT_KEY = 39;
var DOWN_KEY = 40;
var SPACE_KEY = 32;
var HERO_MOVEMENT = 3;
[...Your game code...]
loop();
}
document.getElementById('startButton').onclick = function() {
document.getElementById('startMenu').style.display = "none";
document.getElementById('game').style.display = "";
startGame();
};
Now you have a start menu (<div id="startMenu">) that you can customize however you like, and a game UI (<div id="game">) that will be shown only after the start button is pressed.
Add more HTML would be my suggestion. Maybe make a div that has all the start screen elements you need in it. When the start function happens, set that div's innerHTML to "".
Example:
document.getElementById('yourDivIdHere').innerHTML = '';
I got some simple bomberman game from code pen.For my study,i need to limit how many tiles and target.For tiles max 32 and target 7 (tiles grey & target red).
Here the source : codepen.io/Digiben/pen/oGYGrx
I dont understand how the script create the target and tiles with random algoritm.
Thanks for anyone who look this thread.
window.onload = function(){
//Map Kelas
class Map {
constructor (nbX, nbY, tileSize){
this.nbX = nbX;
this.nbY = nbY;
this.mapArray = new Array(this.nbX);
this.tileSize = tileSize;
this.map = document.getElementById('map');
}
init() {
console.log('Map size: ' + this.nbX * this.nbY);
let i = 0;
let j = 0;
let bool = null;
this.map.style.width = (this.tileSize * this.nbX) + 'px';
this.map.style.height = this.tileSize * this.nbY + 'px';
for (i = 0; i < this.nbX; i++) {
this.mapArray[i] = new Array(this.nbY);
for (j = 0; j < this.nbY; j++) {
bool = Math.random() >= 0.7 ? true : false;
if (bool) {
for (var z = Things.length - 1; i >= 0; i-) {
Things[i]
}
} else if (!bool) {
this.mapArray[i][j] = 1;
}
}
}
}
appendTile(i, j) {
let tile = document.createElement('div');
this.map.appendChild(tile);
tile.style.width = this.tileSize + 'px';
tile.style.height = this.tileSize + 'px';
tile.classList.add('tile');
tile.style.left = (i * this.tileSize) + 'px';
tile.style.top = (j * this.tileSize) + 'px';
}
getMapArray () {
return this.mapArray;
}
getMapSize () {
return {sizeX: this.nbX, sizeY:this.nbY}
}
}
//Create Target
class Target {
constructor (map, tileSize) {
this.mapArray = map.getMapArray();
this.playerSpace = map.getMapSize();
this.targetsArray = new Array();
this.possiblePositionToStartX = new Array();
this.possiblePositionToStartY = new Array();
this.tileSize = tileSize;
this.map = document.getElementById('map');
this.totalTargets = 0;
}
getTotalTargets(){
return this.totalTargets;
}
//Show Total Target
showTotalTargets () {
let totalDiv = document.querySelector('#score strong');
totalDiv.innerHTML = ' / ' + this.totalTargets;
}
showTargets(i, j) {
let tile = document.createElement('div');
this.map.appendChild(tile);
tile.classList.add('target');
tile.style.width = this.tileSize + 'px';
tile.style.height = this.tileSize + 'px';
// set attribute to identify the target when we need to remove it
tile.setAttribute('data-pos', i + ':' + j );
// positionning and styling
tile.style.left = (i * this.tileSize) + 'px';
tile.style.top = (j * this.tileSize) + 'px';
tile.style.backgroundColor = 'red';
tile.style.opacity = 0.5;
}
createTargets() {
//Target looping
for (var i = 1; i < this.playerSpace.sizeX-1; i++) {
//Maks Target 2D 10x10
this.targetsArray[i] = new Array();
if (i == 1) this.targetsArray[i-1] = new Array();
if (i == 8) this.targetsArray[i+1] = new Array();
for (var j = 1; j < this.playerSpace.sizeY-1; j++) {
this.targetsArray[i][j] = 1;
//Target aLgorithm
//Player dont Looping On red Zone
this.possiblePositionToStartX.push(i+1);
this.possiblePositionToStartY.push(j+1);
//Target Array if 0 to display Win on the End
this.targetsArray[i][j] = 0;
//Total Targets
this.totalTargets++;
//Show Target On map
this.showTargets(i, j);
}
}
}
//Show Total Targets
this.showTotalTargets();
}
// Start Player
getPossiblePosToStart() {
//Random Start PLayer
let xPos = this.possiblePositionToStartX[Math.floor(Math.random() * (this.possiblePositionToStartX.length))];
let yPos = this.possiblePositionToStartY[Math.floor(Math.random() * (this.possiblePositionToStartY.length))];
return {x: xPos, y: yPos}
}
//Player Array
getTargetsArray(){
return this.targetsArray;
}
}
//PLayer CLass
class Player {
constructor (mapArray, map, targets, tileSize) {
this.positionArray = mapArray;
this.position = {x: 0, y: 0}
this.playerDiv = document.getElementById('player');
this.playerDiv.style.left = 0;
this.playerDiv.style.top = 0;
this.playerDiv.style.right = 0;
this.playerDiv.style.bottom = 0;
this.playerDiv.style.width = tileSize + 'px';
this.playerDiv.style.height = tileSize + 'px';
this.playerSpace = map.getMapSize();
this.playerMap = map.getMapArray();
this.score = 0;
this.targetsArray = targets.getTargetsArray();
this.totalTargets = targets.getTotalTargets();
this.tileSize = tileSize;
}
//Record Posisition Player
recordPosition(mapArray){
this.positionArray = mapArray;
}
//Reset Score when Restart The game
static resetScore() {
let scoreSpan = document.querySelector('#score span'); scoreSpan.innerHTML = '0';
}
//Set Palyer
setPosition (position){
this.playerDiv.style.left = (position.x * this.tileSize) + 'px';
this.playerDiv.style.top = (position.y * this.tileSize) + 'px';
this.position.x = position.x;
this.position.y = position.y;
}
getPosition() {
return this.position;
}
//Limt Map
moveRight() {
if(this.position.x > this.playerSpace.sizeX-2) return false;
if(this.positionArray[this.position.x+1][this.position.y] != 0){
this.position.x++;
let nb = this.playerDiv.style.left.split('px');
this.playerDiv.style.left = (parseInt(nb[0]) + this.tileSize) + 'px';
console.log('Droite | X : ' + this.playerDiv.style.left);
console.log(this.position.x + ' : ' + this.position.y);
} else {
console.log('Not OK');
}
}
moveDown() {
if(this.position.y > this.playerSpace.sizeY-2) return false;
if(this.positionArray[this.position.x][this.position.y+1] != 0){
this.position.y++;
let nb = this.playerDiv.style.top.split('px');
this.playerDiv.style.top = (parseInt(nb[0]) + this.tileSize) + 'px';
console.log('Bas | Y : ' + this.playerDiv.style.top);
console.log(this.position.x + ' : ' + this.position.y);
} else {
console.log('Not OK');
}
}
moveLeft() {
if(this.position.x == 0) return false;
if(this.positionArray[this.position.x-1][this.position.y] != 0){
this.position.x--;
let nb = this.playerDiv.style.left.split('px');
this.playerDiv.style.left = (parseInt(nb[0]) - this.tileSize) + 'px';
console.log('Gauche | X : ' + this.playerDiv.style.left);
console.log(this.position.x + ' : ' + this.position.y);
} else {
console.log('Not OK');
}
}
moveUp() {
if(this.position.y <= 0) return false;
if(this.positionArray[this.position.x][this.position.y-1] != 0){
this.position.y--;
let nb = this.playerDiv.style.top.split('px');
this.playerDiv.style.top = (parseInt(nb[0]) - this.tileSize) + 'px';
console.log('Haut | Y : ' + this.playerDiv.style.top);
console.log(this.position.x + ' : ' + this.position.y);
} else {
console.log('Not OK');
}
}
//Update Score
updateScore () {
let scoreDiv = document.querySelector('#score span');
scoreDiv.innerHTML = this.score;
//Winner Message
if(this.score == this.totalTargets) document.querySelector ('#win').classList.add('show');
console.log('Score : ' + this.score);
}
//Update Target Array
updateTargetsArray (posx, posy){
this.targetsArray[posx][posy] = 1;
console.log('Array state : ');
console.log(this.targetsArray);
}
//Remove Target
removeTarget(posx, posy) {
let targetToRemove = document.querySelectorAll('.target');
let coords = posx + ':' + posy;
let attr = '';
//Loop To find Right Target accroding Coordinates Player
for (var i = 0; i< targetToRemove.length; i++) {
attr = targetToRemove[i].getAttribute('data-pos');
if(attr == coords) {
targetToRemove[i].remove();
//Update Score
this.score++;
this.updateScore();
}
}
//Remove Html node (Remove Array Target)
if(this.targetsArray[posx][posy] == 0){
this.targetsArray[posx][posy] == 1;
}
}
//Plant Bomb
plantBomb(){
//Make Child Bomb
let map = document.getElementById('map');
let bomb = document.createElement('div');
map.appendChild(bomb);
bomb.style.width = this.tileSize + 'px';
bomb.style.height = this.tileSize + 'px';
//Posision Bomb
bomb.classList.add('bomb');
bomb.style.left = (this.position.x * this.tileSize) + 'px';
bomb.style.top = (this.position.y * this.tileSize) + 'px';
//Variables
var posx = this.position.x;
var posy = this.position.y;
var that = this;
var timer = setInterval(bombTimer, 500, posx, posy, that);
var iter = 0;
//BombTimer
function bombTimer() {
switch (iter) {
case 1:
bomb.classList.add('waiting');
break;
case 2:
bomb.classList.add('before');
bomb.classList.remove('waiting');
break;
case 3:
bomb.classList.add('explode');
bomb.classList.remove('before');
break;
case 4:
clearInterval(timer);
bomb.remove();
that.updateTargetsArray(posx, posy);
that.removeTarget(posx, posy);
default:
break;
}
iter++;
}
}
}
//Game Class
class Game {
constructor (tileSize, mapX, mapY) {
//Create Map
var map = new Map(mapX,mapY, tileSize);
map.init();
//Create Target
var targets = new Target(map, tileSize);
targets.createTargets();
//Create PLayer
var player = new Player(map.getMapArray(), map, targets, tileSize);
//Place The player
player.setPosition(targets.getPossiblePosToStart());
//Keyboard Events
document.onkeydown = checkKey;
function checkKey(e) {
e = e || window.event;
if (e.keyCode == '38') {
player.moveUp();
}
else if (e.keyCode == '40') {
player.moveDown();
}
else if (e.keyCode == '37') {
player.moveLeft();
}
else if (e.keyCode == '39') {
player.moveRight();
}
else if (e.keyCode == '32') {
player.plantBomb();
}
}
}
//Destroy Game
static destroy () {
let targets = document.querySelectorAll('.target');
let tiles = document.querySelectorAll('.tile');
Player.resetScore();
if(tiles){
targets.forEach(function(element) {
element.remove();
});
tiles.forEach(function(element) {
element.remove();
});
}
}
}
class Session {
constructor () {
this.totalTargets = 0;
this.players = {};
this.restartBtn = document.querySelector('#restart');
this.restartBtn.addEventListener('click', function() {
Session.restart();
});
}
static restart () {
Game.destroy();
var game = new Game(25, 10, 10);
}
}
var session = new Session();
};
#map {
width: 500px;
height: 500px;
background: lightgrey;
position: relative;
margin: auto;
}
#game {
width: 500px;
height: 500px;
position: relative;
margin: auto;
}
#map .tile {
width: 50px;
height: 50px;
background: grey;
position: absolute;
outline: 1px solid #eee;
}
#map .target {
width: 50px;
height: 50px;
background: red;
position: absolute;
outline: 1px solid #eee;
}
#map #player {
border-radius: 25%;
width: 50px;
height: 50px;
position: absolute;
background: #222222;
z-index: 1;
transition: 0.1s;
}
.bomb {
border-radius: 100%;
width: 50px;
height: 50px;
position: absolute;
background: #333;
z-index: 1;
transition: 0.3s ease;
}
.bomb.waiting {
animation: waiting 2s infinite;
}
.bomb.before {
animation: before 1s infinite;
}
.bomb.explode {
animation: explode 1s infinite;
}
#score p, #score span {
font-family: sans-serif;
color: #333;
font-size: 16px;
display: inline;
}
#keyframes waiting {
0% {
transform: scale(0.9);
}
100% {
transform: scale(1.1);
}
}
#keyframes before {
0% {
transform: scale(1.0);
background: orange;
}
100% {
transform: scale(1.2);
background: red;
}
}
#keyframes explode {
0% {
transform: scale(1.0);
background: red;
opacity: 1;
}
100% {
transform: scale(2);
background: yellow;
opacity: 0;
}
}
#keyframes win {
0% {
opacity: 0;
}
10% {
opacity: 1;
}
66% {
opacity: 1;
}
100% {
opacity: 0;
}
}
h4 {
font-family: sans-serif;
color: #333;
text-align: center;
}
p, strong {
font-family: sans-serif;
color: #333;
text-align: left;
font-size: 12px;
}
#win {
position: fixed;
left: 0;
right: 0;
top:0;
bottom: 0;
z-index: 9999999;
background: rgba(181, 181, 195, 0.1);
pointer-events: none;
opacity: 0;
}
#win p {
color: red;
font-size: 130px;
text-align: center;
font-family: sans-serif;
text-transform: uppercase;
height: 100%;
margin: 0;
top: 50%;
position: absolute;
left: 50%;
transform: translate(-50%, -25%);
right: 0;
bottom: 0;
font-weight: bold;
text-shadow: 5px 5px #333;
}
#win.show {
animation: win 4s ease;
}
#restart {
text-align: center;
padding: 10px 20px;
font-family: sans-serif;
color: #333;
outline: #ccc 1px solid;
display: table;
margin: auto;
margin-top: 20px;
cursor: pointer;
transition: 0.1s ease;
}
#restart:hover {
background: #eee;
}
<!DOCTYPE html>
<html>
<head>
<title>Bomberman</title>
<link href="bomber.css" type="text/css" rel="stylesheet">
<script type="text/javascript" src="1.js"></script>
</head>
<body>
<h4>Space bar to plant a bomb / Arrows to move </h4>
<div id="win"><p>WIN !</p></div>
<div id="restart"> RESTART </div>
<div id="score"><p>Score: </p><span>0</span><strong> / 0</strong></div>
<section id="game">
<div id="map">
<div id="player"></div>
</div>
</section>
</body>
</html>
I'm not certain I understand your question, but I think you're trying to debug the createTargets method in the Targets class. The problem there is an extra closing bracket (}) right before the line with //Show Total Targets.