Clicking div does not change the width and height - javascript

I made a clicking div. After clicking the div (some_id1, someenter code here_id2), you need to change the value on each div (width, height, background-color).
Background-color works normally, but width and height are not working. I cannot find out where I made a mistake.
var div = document.getElementsByTagName("div");
var divCount = div.length;
var clickedDivId
for (var i = 0; i < divCount; i += 1) {
div[i].onclick = function(e) {
clickedDivId = this.id
};
}
function ColorChange(){
if(clickedDivId == "some_id1"){
var x = document.getElementById("divbackgroundcolor").value;
document.getElementById(clickedDivId).style.backgroundColor = x;
}
if(clickedDivId == "some_id2"){
var y = document.getElementById("divbackgroundcolor").value;
document.getElementById(clickedDivId).style.backgroundColor = y;
}
}
function ChengeWidth(){
if(clickedDivId == "some_id1"){
var z = document.getElementById("divwidth").value;
document.getElementById(clickedDivId).style.width = z;
}
if(clickedDivId == "some_id2"){
var w = document.getElementById("divwidth").value;
document.getElementById(clickedDivId).style.width = w;
}
}
#some_id1{
width: 50px;
height: 50px;
margin: 10px;
background-color: red;
}
#some_id2{
width: 50px;
height: 50px;
margin: 10px;
background-color: red;
}
<select id="divwidth" onchange="ChengeWidth()">
<option value="100px">100px</option>
</select>
<input type="color" id="divbackgroundcolor" onchange="ColorChange()">
<div class="some_style" id="some_id1"></div>
<div class="some_style" id="some_id2"></div>

var div = document.getElementsByTagName("div");
var divCount = div.length;
var clickedDivId
for (var i = 0; i < divCount; i += 1) {
div[i].onclick = function(e) {
clickedDivId = this.id
};
}
function ColorChange(){
if(clickedDivId == "some_id1"){
var x = document.getElementById("divbackgroundcolor").value;
document.getElementById(clickedDivId).style.backgroundColor = x;
}
if(clickedDivId == "some_id2"){
var y = document.getElementById("divbackgroundcolor").value;
document.getElementById(clickedDivId).style.backgroundColor = y;
}
}
function ChengeWidth(){
if(clickedDivId == "some_id1"){
var z = document.getElementById("divwidth").value;
document.getElementById(clickedDivId).style.width = z;
}
if(clickedDivId == "some_id2"){
var w = document.getElementById("divwidth").value;
document.getElementById(clickedDivId).style.width = w;
}
}
#some_id1{
width: 50px;
height: 50px;
margin: 10px;
background-color: red;
}
#some_id2{
width: 50px;
height: 50px;
margin: 10px;
background-color: red;
}
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
</head>
<body>
<select id="divwidth" onchange="ChengeWidth()">
<option value="100px">100px</option>
<option value="200px">200px</option>
<option value="300px">300px</option>
<option value="50px">50px</option>
</select>
<input type="color" id="divbackgroundcolor" onchange="ColorChange()">
<div class="some_style" id="some_id1"></div>
<div class="some_style" id="some_id2"></div>
</body>
</html>

The menu only has one option, so you can't change the value and the onchange event never triggers. If you give it multiple options, the code works.
var div = document.getElementsByTagName("div");
var divCount = div.length;
var clickedDivId
for (var i = 0; i < divCount; i += 1) {
div[i].onclick = function(e) {
clickedDivId = this.id
};
}
function ColorChange() {
if (clickedDivId == "some_id1") {
var x = document.getElementById("divbackgroundcolor").value;
document.getElementById(clickedDivId).style.backgroundColor = x;
}
if (clickedDivId == "some_id2") {
var y = document.getElementById("divbackgroundcolor").value;
document.getElementById(clickedDivId).style.backgroundColor = y;
}
}
function ChengeWidth() {
if (clickedDivId == "some_id1") {
var z = document.getElementById("divwidth").value;
document.getElementById(clickedDivId).style.width = z;
}
if (clickedDivId == "some_id2") {
var w = document.getElementById("divwidth").value;
document.getElementById(clickedDivId).style.width = w;
}
}
#some_id1 {
width: 50px;
height: 50px;
margin: 10px;
background-color: red;
}
#some_id2 {
width: 50px;
height: 50px;
margin: 10px;
background-color: red;
}
<select id="divwidth" onchange="ChengeWidth()">
<option value="50px">50px</option>
<option value="100px">100px</option>
<option value="150px">150px</option>
<option value="200px">200px</option>
</select>
<input type="color" id="divbackgroundcolor" onchange="ColorChange()">
<div class="some_style" id="some_id1"></div>
<div class="some_style" id="some_id2"></div>

HTML
<div id="some_id1" class="clickable"></div>
<div id="some_id2" class="clickable"></div>
CSS
.clickable {
width: 50px;
height: 50px;
margin: 10px;
}
Javascript
let current;
function changeColor() {
const color = document.getElementById("divbackgroundcolor").value;
current.style.backgroundColor = color;
}
function changeWidth() {
const width = document.getElementById("divwidth").value;
current.style.width = width;
}
function initialize() {
const clickable = document.querySelectorAll('.clickable');
clickable.forEach((item) => {
item.onClick = () => {
current = this;
changeColor();
changeWidth();
}
});
}
initialize();
My approach would be to split the problem in small chunks as you can see in my javascript proposal. Basically each method is a step which can be fully tested before moving on to the next portion:
Add event handlers to elements (I changed it to a class, rather than applying it to all <div>-elements). Use console.log to make sure everything works as expected.
Change the color; first call it immediately without the click handling in between. Does it work? Probably not because I did not include #divwidth in my example, but hopefully you see the approach I'm aiming for.
Next change the width; same as previous: I did not include #divbackgroundcolor so it won't work yet
Finally tie everything together and call the methods within the click handler
Hopefully I've pointed you in the right direction; good luck!

Related

Slide Touch and mouse with Pure Javascript

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>

How to drag images in JS

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>

Stop javascript "animation" onclick div

I'm a beginner in javascript and I'm trying to make a very simple game. I know that my code is not the best, but i want to make it working. I want to stop function nahoru() or make it move to the other way and after it touches the bottom of the page/100%, make it repeat.
<html>
<head>
<script>
function naloud() {
var elem = document.getElementById("krtek");
elem.style.top = '100%';
var eleme = document.getElementById("krtek2");
eleme.style.top = '100%';
var elemen = document.getElementById("krtek3");
elemen.style.top = '100%';
}
var pos = 100;
var los = 0;
function nahoru() {
var elemend = document.getElementById("batn");
elemend.style.opacity = '0';
var elem = document.getElementById("krtek");
var id = setInterval(frame, 30);
function frame() {
if (pos == 0) {
clearInterval(id);
document.write('<center>GAME OVER<br>YOUR SCORE: ' + skore +
'<br>Press F5 for restart.')
} else {
pos = pos - 1;
elem.style.top = pos + '%';
}
}
}
var skore = 0;
function pric() {
skore++;
document.getElementById("skore").innerHTML = "Skore: " + skore;
elem.style.top = '+100%';
}
</script>
<style>
.prvni {
position: absolute;
width: 10%;
height: 110%;
left: 10%;
background-color: brown;
}
.druhy {
position: absolute;
width: 10%;
height: 110%;
left: 45%;
background-color: brown;
}
.treti {
position: absolute;
width: 10%;
height: 110%;
left: 80%;
background-color: brown;
}
</style>
</head>
<body onload="naloud()">
<button onclick="nahoru()" id="batn">START</button>
<div id="skore">Skore: 0</div>
<div id="krtek" class="prvni" onclick="pric()"></div>
<div id="krtek2" class="druhy" onclick="pric()"></div>
<div id="krtek3" class="treti" onclick="pric()"></div>
</body>
</html>
Declare id outside nahoru function,
like here
var pos = 100;
var los = 0;
var id = null;
Set interval in nahoru function,
like this (important, remove var from here)
id = setInterval(frame, 30);
Now clear interval in pric function
like this
function pric(elem) {
skore++;
clearInterval(id);
document.getElementById("skore").innerHTML = "Skore: " + skore;
elem.style.top = '+100%';
}
Working https://jsfiddle.net/ee1bdL5k/
You need declare this var outside from function, for the pric function:
var elem, eleme, elemen;
function naloud() {
elem = document.getElementById("krtek");
elem.style.top = '100%';
eleme = document.getElementById("krtek2");
eleme.style.top = '100%';
elemen = document.getElementById("krtek3");
elemen.style.top = '100%';
}

Animating multiple divs in a loop using plain javascript

I'm having three blue squares on my webpage. Each square is 50px by 50px in size. I wish to slowly increase the size of each squares to 80px by 80px one after the other.
Instead of the expected result above, only the last square size got changed.
Please how can I get the code below to work.
<!DOCTYPE html>
<html>
<head>
<title>zoom box</title>
<script>
function zoom() {
var box;
const height = 50;
var boxes = document.getElementsByClassName('box');
var id;
for (i = 0; i < boxes.length; i++) {
box = boxes[i];
h = height;
frame();
}
function frame() {
h++;
if (h >= 80) {
return;
}
box.style.height = h + 'px';
box.style.width = h + 'px';
setTimeout(frame, 100);
}
}
</script>
<head>
<body width="100%" height="100%" onload="zoom()">
<div style="width: 20em; height: 20em; margin:auto; border-style:solid;display:flex; justify-content: space-between;">
<div class="box" style="background-color: blue; width:50px; height: 50px; margin:auto">
</div>
<div class="box" style="background-color: blue; width:50px; height: 50px; margin:auto">
</div>
<div class="box" style="background-color: blue; width:50px; height: 50px; margin:auto">
</div>
</div>
</body>
</html>
function zoom() {
var box;
const height = 50;
var boxes = document.getElementsByClassName('box');
var array = [];
var id;
for (var i = 0; i < boxes.length; i++) {
box = boxes[i];
console.log(box)
h = height;
if(i == 0){
array[i] = true;
}else{
array[i] = false;
}
frame(box,i,height);
}
function frame(box,i,h) {
if (h >= 80) {
for(var j = 0; j < array.length ; j++){
if(j != i && array[j] == false){
array[j] = true;
break;
}
}
array[i] = true;
return box;
}
console.log(i + " " + array[i]);
if(array[i]){
h++;
box.style.height = h + 'px';
box.style.width = h + 'px';
}
setTimeout(function(){
frame(box,i,h);
}, 100);
}
}

update .style attributes with setInterval

I'm trying to move the position of a div element at set intervals however the setInterval method executes once and then stops. setInterval() doesn't update .style.transform repeatedly every 200 milliseconds as intended.
<!DOCTYPE html>
<html>
<head>
<title>Snake game</title>
<style type="text/css">
.container {
width: 500px;
height: 500px;
border: 2px solid black;
}
#snakehead {
width: 5px;
height: 5px;
background: pink;
position: relative;
left: 0px;
}
</style>
<script type="text/javascript" src="snake.js"></script>
</head>
<body>
<div class="container">
<div id="snakehead"></div>
</div>
</body>
</html>
Javascript: Ideally I'd also like to be able to move the snakehead in any direction with vx and vy. Anyway to put those values into .style.transform = translateX()?
function snakepos() {
var x = 0;
var y = 0;
var vx = 1;
var vy = 0;
return {
move: function() {
x += vx;
y += vy;
var snakehead = document.querySelector("#snakehead");
snakedhead.style.left = "5px";
}
};
}
window.onload = function() {
console.log("hi");
var container = document.querySelector(".container");
var snake = snakepos();
setInterval(function() {
snake.move();
}, 200);
}
I know this can be done much easier in jQuery with .css but I'd to how this can be done in vanilla javascript. Thank you in advance.
snakehead.style.left = (snakedhead.style.left + "5px");
or
snakehead.style.left = (snakedhead.style.left - "5px");
I'd recommend something in a style a bit more familiar to me:
function snakepos() {
this.x = 0;
this.y = 0;
this.vx = 1;
this.vy = 1;
this.snakehead = document.querySelector("#snakehead");
var me = this;
this.move = function() {
me.x += me.vx;
me.y += me.vy;
me.snakehead.style.top = me.y + "px";
me.snakehead.style.left = me.x + "px";
};
return this;
}
console.log("hi");
var container = document.querySelector(".container");
var snake = new snakepos();
setInterval(function() {
snake.move();
}, 200);
See fiddle: https://jsfiddle.net/theredhead/td8opb0b/1/

Categories