Implementing onmouse events in Chrome app - javascript

I have created this code:
window.onload = function() {
for (var i = 10; i < 100; i += 10) {
document.getElementById("overlayInner").innerHTML += '<div style="top:' + ((8 * i) - 15) + 'px;" class="number lat lat' + i + '">' + i + '</div>';
document.getElementById("overlayInner").innerHTML += '<span style="left:' + ((8 * i) - 15) + 'px;" class="number lon lon' + i + '">' + i + '</span>';
}
var map_canvas = document.getElementById("map");
var context = map_canvas.getContext("2d");
for (var x = 80; x < 800; x += 80) {
context.moveTo(x, 45);
context.lineTo(x, 755);
}
var count = 1;
for (var y = 80; y < 800; y += 80) {
if (count != 10) {
context.moveTo(50, y);
context.lineTo(750, y);
}
}
context.strokeStyle = "#7c7c7c";
context.stroke();
};
function move(id, evt) {
var e = document.getElementById(id);
e.style.display = "block";
e.style.left = evt.pageX + 10 + "px";
e.style.top = evt.pageY + 10 + "px";
e.innerHTML = "X: " + Math.round(((evt.pageX * 1.25) / 10)) + " / Y: " + Math.round(((evt.pageY * 1.25) / 10));
}
function hide(id) {
document.getElementById(id).style.display = "none";
}
/* CSS file placeholder. */
body {
padding: 0;
margin: 0;
background: #313335;
}
#map_container {
position: relative;
}
#map {
width: 800px;
height: 800px;
}
#overlay {
width: 800px;
height: 800px;
position: absolute;
top: 0;
left: 0;
}
#overlay:hover {
cursor: crosshair;
}
#overlayInner {
width: 100%;
height: 100%;
display: block;
position: relative;
}
.number {
background: white;
padding: 5px;
border: 2px solid black;
position: absolute;
}
.lat {
left: 25px;
}
.lon {
bottom: 25px;
}
canvas {
border: 1px solid black;
position: relative;
}
canvas:hover {
cursor: crosshair;
}
#coordinates {
position: absolute;
color: white;
display: none;
}
<canvas id="map" width="800px" height="800px"></canvas>
<div id="overlay" onmousemove="move('coordinates',event)" onmouseout="hide('coordinates')">
<div id="overlayInner"></div>
</div>
<span id="coordinates"></span>
It seems to work in the Chrome browser both when I run it through the stack snippet or when I run it as a website. However, when I run it as a Chrome app I get no coordinates.
I am new to Chrome Apps so I am not sure if it is possible to achieve this. However, I thought I would ask to see if it needs to be written differently, maybe there is an error in my code that the browser is fixing at runtime? This code is just standard Javascript so I can't understand why it doesn't work.

Chrome Extensions do not allow inline-event handlers
onmousemove="move('coordinates',event)" onmouseout="hide('coordinates')"
The following code should do the trick.
eO = document.getElementById('overlay');
eO.addEventListener("mousemove", function(evt){
move('coordinates', evt);
});
eO.addEventListener("mouseout", function(){
hide('coordinates');
});

Related

Collision or overlap - JavaScript

I'm trying to create a game where you control circle1 and make it go to circle2 and when this overlap happens there is an alert that says "Game Over".
I created a function that activates when the page loads and every 1000ms repeats the function, the problem is that as soon as I update the page, even if circle1 is not superimposed on circle2, it gives me an alert, and when I press ok, it opens another and so on...
Can you correct me? What am I doing wrong?
HTML:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Index</title>
<link href="style.css" rel="stylesheet" type="text/css">
<script src="script.js"></script>
</head>
<body onload="checkCollision()">
<div id="content"></div>
<div id="contentTwo"></div>
<div id="buttonDiv">
<button onclick="moveUp()" class="buttonUp">⇧</button>
<br>
<button onclick="moveLeft()">⇦</button>
<button onclick="moveDown()">⇩</button>
<button onclick="moveRight()">⇨</button>
</div>
</body>
</html>
CSS:
body {
background-color: #222222;
}
#content {
background-color: #aaaaaa;
width: 60px;
height: 60px;
position: relative;
border-radius: 50px;
left: 200px;
top: 20px;
}
#contentTwo {
background-color: #dddddd;
width: 40px;
height: 40px;
position: relative;
top: 80px;
border-radius: 50px;
}
button {
width: 50px;
height: 50px;
font-size: 30px;
font-weight: bold;
margin: auto;
}
.buttonUp {
margin-top: 300px;
}
#buttonDiv {
text-align: center;
width: auto;
height: auto;
background-color: transparent;
}
JavaScript:
var pixelTop = 20;
var pixelLeft = 200;
function checkCollision() {
if (document.getElementById("content").top === document.getElementById("contentTwo").top) {
alert("Game Over");
}
setTimeout("checkCollision()",1000);
}
function moveUp() {
pixelTop += -10;
document.getElementById("content").style.top = pixelTop+"px";
}
function moveLeft() {
pixelLeft += -10;
document.getElementById("content").style.left = pixelLeft+"px";
}
function moveDown() {
pixelTop += 10;
document.getElementById("content").style.top = pixelTop+"px";
}
function moveRight() {
pixelLeft += 10;
document.getElementById("content").style.left = pixelLeft+"px";
}
I want when circle1 is in the same position as circle2, a "Game Over" alert appears.
Snippet:
var pixelTop = 20;
var pixelLeft = 200;
function checkCollision() {
if (document.getElementById("content").top === document.getElementById("contentTwo").top) {
alert("Game Over");
}
setTimeout("checkCollision()", 1000);
}
function moveUp() {
pixelTop += -10;
document.getElementById("content").style.top = pixelTop + "px";
}
function moveLeft() {
pixelLeft += -10;
document.getElementById("content").style.left = pixelLeft + "px";
}
function moveDown() {
pixelTop += 10;
document.getElementById("content").style.top = pixelTop + "px";
}
function moveRight() {
pixelLeft += 10;
document.getElementById("content").style.left = pixelLeft + "px";
}
body {
background-color: #222222;
}
#content {
background-color: #aaaaaa;
width: 60px;
height: 60px;
position: relative;
border-radius: 50px;
left: 200px;
top: 20px;
}
#contentTwo {
background-color: #dddddd;
width: 40px;
height: 40px;
position: relative;
top: 80px;
border-radius: 50px;
}
button {
width: 50px;
height: 50px;
font-size: 30px;
font-weight: bold;
margin: auto;
}
.buttonUp {
margin-top: 300px;
}
#buttonDiv {
text-align: center;
width: auto;
height: auto;
background-color: transparent;
}
<body onload="checkCollision()">
<div id="content"></div>
<div id="contentTwo"></div>
<div id="buttonDiv">
<button onclick="moveUp()" class="buttonUp">⇧</button>
<br>
<button onclick="moveLeft()">⇦</button>
<button onclick="moveDown()">⇩</button>
<button onclick="moveRight()">⇨</button>
</div>
</body>
There are a few flaws in the way you're trying to achieve your goal here.
First of all, the reason it happens is that you're trying to access the 'top' css attribute incorrectly, therefore the result in undefined and equal for both sides of the condition:
document.getElementById("content").top // undefined
document.getElementById("contentTwo").top // undefined
Since both of them are undefined, they are equal. Instead, if you'd want to access the 'top' css attribute you'll need to use the following method:
getComputedStyle(document.getElementById("content")).top
You can read more here:
https://developer.mozilla.org/en-US/docs/Web/API/Window/getComputedStyle
Second, there is an issue with the logic you're trying to implement, even in a case where the content top attribute would equal to contentTwo top attribute, that still doesn't mean that the 2 elements intersects.
Not sure if it's the best approach, but what I'd do instead is use the getBoundingClientRect method - https://developer.mozilla.org/en-US/docs/Web/API/Element/getBoundingClientRect
That way you can get all the needed information(such as - x, y, width, height, left, right, bottom, top) in order to calculate whether the 2 circles intersects or not.
You should be able to calculate the distance between the 2 objects and then determine whether the 2 objects intersects or not, here is an example you can use for reference:
https://developer.mozilla.org/en-US/docs/Games/Techniques/2D_collision_detection
Last, I'd suggest trying to add logs in case you're having an unexpected scenario, by simply logging the result of the condition you could've easily seen that something is wrong there.
#pardovot
Yes i solved it, thanks a lot, this is the JavaScript code:
var pixelTop = 20;
var pixelLeft = 200;
function moveUp() {
pixelTop += -10;
document.getElementById("content").style.top = pixelTop+"px";
}
function moveLeft() {
pixelLeft += -10;
document.getElementById("content").style.left = pixelLeft+"px";
}
function moveDown() {
pixelTop += 10;
document.getElementById("content").style.top = pixelTop+"px";
}
function moveRight() {
pixelLeft += 10;
document.getElementById("content").style.left = pixelLeft+"px";
}
function checkCollision() {
var content1 = document.getElementById("content");
var position1 = content1.getBoundingClientRect();
var x1 = position1.left;
var y1 = position1.top;
var w1 = position1.width;
var h1 = position1.height;
var content2 = document.getElementById("contentTwo");
var position2 = content2.getBoundingClientRect();
var x2 = position2.left;
var y2 = position2.top;
var w2 = position2.width;
var h2 = position2.height;
if (x1 < x2 + w2 && x1 + w1 > x2 && y1 < y2 + h2 && y1 + h1 > y2) {
console.log("Hitted")
}
setTimeout("checkCollision()",1);
}

Detect collision (video game js)

I am building a video game where fireballs drop from the top screen. The spaceship, moved by controllers, must avoid those fireballs in order win. My issue is that I do not know how to detect when the spaceship collides into fireballs. However, I found this link: Detect if animated object touched another object in DOM. I analysed this code and it seems it only works for his issue particularly. Do you guys know how to do this?
Code for image spaceship and fireball:
<img src="Photo/fireball.png" id="fireball">
<img src="Photo/Spaceship1.png" id="icon-p">
Code for spaceship:
let rect = icon
let pos = {top: 1000, left: 570}
const keys = {}
window.addEventListener("keydown", function(e) {keys[e.keyCode] = true})
window.addEventListener("keyup", function(e) {keys[e.keyCode] = false})
const loop = function() {
if (keys[37] || keys[81]) {pos.left -= 10}
if (keys[39] || keys[68]) {pos.left += 10}
if (keys[38] || keys[90]) {pos.top -= 10}
if (keys[40] || keys[83]) {pos.top += 10}
var owidth = display.offsetWidth
var oheight = display.offsetHeight
var iwidth = rect.offsetWidth
var iheight = rect.offsetHeight
if (pos.left < 0) pos.left = -10
if (pos.top < 0) pos.top = -10
if (pos.left + iwidth >= owidth) pos.left = owidth-iwidth
if (pos.top + iheight >= oheight) pos.top= oheight-iheight
rect.setAttribute("data", owidth + ":" + oheight)
rect.style.left = pos.left + "px"; rect.style.top = pos.top + "px"}
let sens = setInterval(loop, 1000 / 60)
Code for fireball:
function fFireball(offset) {
return Math.floor(Math.random() * (window.innerWidth - offset))}
let fireballElement = document.querySelector("#fireball");
let fireball = {x: fFireball(fireballElement.offsetWidth), y: 0}
const fireLoop = function() {
fireball.y += 2
fireballElement.style.top = fireball.y + 'px'
if (fireball.y > window.innerHeight) {
fireball.x = fFireball(fireballElement.offsetWidth)
fireballElement.style.left = fireball.x + 'px'; fireball.y = 0}}
fireballElement.style.left = fireball.x + 'px'
let fireInterval = setInterval(fireLoop, 1000 / 100)
Thanks!
here I've integrated collision detection for your game. The most notable thing is in this function:
function checkCollision() {
var elem = document.getElementById("icon");
var elem2 = document.getElementById("fireball");
if ( detectOverlap(elem, elem2) && elem2.getAttribute('hit')=='false' ){
hits++; // detect hit and increase
elem2.setAttribute('hit', true); // set attribute to not have flooding
console.log( hits ); // console it just to see it
}
setTimeout( checkCollision, 20);
}
In lower window you can test demo that I've built for you without images but some random boxes as images :)
Good luck with game man, cool
//////////
"use strict"
//Stay on focus
function stayOnFocus() {
setTimeout(function() {
alert("Do not exit window or game progression will be lost!")
}, 1000)
}
let hits = 0
//"A" keypress plays Music
document.addEventListener('keydown', function(e) {
if (e.keyCode !== 173) {
//document.getElementById('audio').play()
}
})
//Input Validation
let icon = document.getElementById("icon")
let fireballElement = document.querySelector("#fireball")
var input = document.getElementById("input")
input.addEventListener("keydown", function(event) {
if (event.keyCode === 13) {
event.preventDefault();
document.getElementById("begin-timer").click()
}
})
//CountDown (3...2...1)
var count = 3
function countDown() {
function preventCountFast() {
document.getElementById("count").innerHTML = count
if (count > 0) {
count--
} else {
clearInterval(ncount);
document.getElementById("count").style.display = "none"
}
}
var ncount = setInterval(preventCountFast, 1000)
}
//Name displayed + space(switch between images) + parameter icon displayed
function Username(field) {
field = input.value
if (field == "") {
alert("Complete blanks");
return false
}
document.getElementById("askName").style.display = "none"
setTimeout(function() {
document.getElementById("name").innerHTML = "Player: " + field
icon.style.display = 'block';
fireballElement.style.display = "block"
const images = ["https://placehold.it/30x30", "https://placehold.it/90x90",
"https://placehold.it/120x40", "https://placehold.it/100x100"
]
document.body.onkeyup = function(e) {
if (e.keyCode === 32) {
hits++;
icon.src = images[hits % 5]
}
}
checkCollision();
}, 4000)
}
//Spaceship moves into space + prevent going out borders
let display = document.getElementById("body");
let rect = icon
let pos = {
top: 1000,
left: 570
}
const keys = {}
window.addEventListener("keydown", function(e) {
keys[e.keyCode] = true
})
window.addEventListener("keyup", function(e) {
keys[e.keyCode] = false
})
const loop = function() {
if (keys[37] || keys[81]) {
pos.left -= 10
}
if (keys[39] || keys[68]) {
pos.left += 10
}
if (keys[38] || keys[90]) {
pos.top -= 10
}
if (keys[40] || keys[83]) {
pos.top += 10
}
var owidth = display.offsetWidth
var oheight = display.offsetHeight
var iwidth = rect.offsetWidth
var iheight = rect.offsetHeight
if (pos.left < 0) pos.left = -10
if (pos.top < 0) pos.top = -10
if (pos.left + iwidth >= owidth) pos.left = owidth - iwidth
if (pos.top + iheight >= oheight) pos.top = oheight - iheight
rect.setAttribute("data", owidth + ":" + oheight)
rect.style.left = pos.left + "px";
rect.style.top = pos.top + "px"
}
let sens = setInterval(loop, 1000 / 60)
//Parameter Sensibility
let param = document.getElementById("parameters")
let b2 = document.getElementById("body2")
document.getElementById("general").addEventListener("click", function() {
param.style.display = "block";
b2.style.display = "none"
})
function validateSens() {
b2.style.display = "block";
param.style.display = "none";
clearInterval(sens)
let sensibilty = parseFloat(document.getElementById("sensibilty").value)
switch (sensibilty) {
case 1:
sens = setInterval(loop, 1000 / 40);
break;
case 2:
sens = setInterval(loop, 1000 / 60);
break;
case 3:
sens = setInterval(loop, 1000 / 80);
break;
default:
alert("Sorry, a bug occured")
}
}
//Fireball script
function fFireball(offset) {
return Math.floor(Math.random() * (window.innerWidth - offset))
}
let fireball = {
x: fFireball(fireballElement.offsetWidth),
y: 0
}
const fireLoop = function() {
fireball.y += 2;
fireballElement.style.top = fireball.y + 'px'
if (fireball.y > window.innerHeight) {
fireball.x = fFireball(fireballElement.offsetWidth)
fireballElement.style.left = fireball.x + 'px';
fireball.y = 0;
fireballElement.setAttribute('hit', false );
}
}
fireballElement.style.left = fireball.x + 'px'
let fireInterval = setInterval(fireLoop, 1000 / 100)
function checkCollision() {
var elem = document.getElementById("icon");
var elem2 = document.getElementById("fireball");
if (detectOverlap(elem, elem2) && elem2.getAttribute('hit')=='false' ){
hits++; // detect hit
elem2.setAttribute('hit', true);
aler("hi")
}
setTimeout( checkCollision, 20);
}
// detect fn
var detectOverlap = (function() {
function getPositions(elem) {
var pos = elem.getBoundingClientRect();
return [
[pos.left, pos.right],
[pos.top, pos.bottom]
];
}
function comparePositions(p1, p2) {
var r1, r2;
r1 = p1[0] < p2[0] ? p1 : p2;
r2 = p1[0] < p2[0] ? p2 : p1;
return r1[1] > r2[0] || r1[0] === r2[0];
}
return function(a, b) {
var pos1 = getPositions(a),
pos2 = getPositions(b);
return comparePositions(pos1[0], pos2[0]) && comparePositions(pos1[1], pos2[1]);
};
})();
body {
user-select: none;
margin: 0px;
height: 100vh;
padding: 0;
width: 100%;
background-image: url(Photo/bg.jpg);
background-repeat: no-repeat;
background-attachment: fixed;
animation: intro-fade 3s;
background-size: cover;
overflow: hidden;
}
#askName {
display: block;
z-index: 1;
margin-left: auto;
margin-top: 12%;
margin-right: auto;
width: 400px;
text-align: center;
background-color: #737373;
opacity: 0.8;
border-radius: 15px;
padding: 40px 50px 40px 50px;
}
#askName:hover {
opacity: 0.9
}
#askName>label {
text-align: center;
font-size: 150%;
font-weight: lighter;
text-align: center;
}
#askName>input {
display: block;
font-size: 100%;
margin: 30px auto 20px auto;
border: none;
border-radius: 10px;
padding: 10px 20px 10px 20px;
}
#askName>button {
background-color: #e6e6e6;
cursor: pointer;
padding: 10px 20px 10px 20px;
border: none;
border-radius: 10px;
}
#count {
margin-top: 13%;
animation: count-down 16s;
font-weight: lighter;
font-family: cursive;
text-align: center;
color: black;
font-size: 200px;
}
h6 {
margin-right: 20px;
padding-top: 5px;
font-weight: normal;
font-family: sans-serif;
margin-top: 0px;
color: white;
text-align: center;
font-size: 190%;
cursor: default;
}
h6:hover {
font-size: 210%
}
#icon {
position: absolute;
top: 0;
left: 0;
cursor: none;
width: 9%;
}
#general {
position: absolute;
cursor: pointer;
min-width: 4%;
top: 10px;
width: 4%;
right: 10px;
}
#general:hover {
transform: rotate(-100deg)
}
#parameters {
text-align: center;
display: none;
animation: intro-fade 3s;
height: auto;
border: none;
background-color: #d9d9d9;
color: black;
position: absolute;
padding: 0px 60px 20px 60px;
left: 50%;
width: auto;
min-width: 200px;
top: 50%;
transform: translate(-50%, -50%);
border-radius: 13px;
}
h3 {
color: black;
font-weight: normal;
font-size: 150%;
}
#sensibilty {
display: block;
margin-right: auto;
margin-left: auto;
}
#validateSens {
margin-top: 20px;
border: none;
padding: 10px;
border-radius: 5px;
cursor: pointer;
}
#keyframes intro-fade {
from {
opacity: 0
}
to {
opacity: 1
}
}
#keyframes count-down {
from {
transform: scale(0)
}
to {
transform: scale(1)
}
}
<body id="body" onload="stayOnFocus()">
<img src="https://placehold.it/350x350" id="general">
<section id="parameters">
<h3> Choose your sensibility </h3>
<input type="range" id="sensibilty" min="1" max="3" value="2">
<button id="validateSens" onclick="validateSens()"> Submit </button>
</section>
<main id="body2">
<form id="askName" title="Write your name"> <label> Enter your username: </label>
<input id="input" type="text" maxlength="10" autofocus>
<button type="button" onclick="countDown(); return Username()" id="begin-timer"> Submit </button>
</form>
<h6 id="name"></h6>
<h2 id="count"></h2>
<img src="https://placehold.it/50x52" id="fireball" style="display:none; width:3%; position:absolute; cursor:none">
<img src="https://placehold.it/80x40" id="icon" style="display:none">
</main>

Issues with div size and position updates on mouse move event

I'm implementing a simple horizontal split pane using html, css, and javascript, adapted from this post.
While everything works smoothly for the vertical split pane, the horizontal implementation is jerky. The div sizes and positions jump to an unexpected value, but I am unable to spot when.
The issue is very subtle on below snippet, but some jumpiness and lagging can be observed.
Snippet below:
function dragElement(element, direction) {
var md;
const first = document.getElementById("map");
const second = document.getElementById("table");
element.onmousedown = onMouseDown;
function onMouseDown(e) {
md = {
e,
offsetLeft: element.offsetLeft,
offsetTop: element.offsetTop,
offsetBottom: element.offsetBottom,
firstWidth: first.offsetWidth,
secondWidth: second.offsetWidth,
firstHeight: first.offsetHeight,
secondHeight: first.offsetHeight
};
document.onmousemove = onMouseMove;
document.onmouseup = () => {
document.onmousemove = document.onmouseup = null;
}
}
function onMouseMove(e) {
var delta = {
x: e.clientX - md.e.x,
y: e.clientY - md.e.y
};
if (direction === "H") {
delta.x = Math.min(Math.max(delta.x, - md.firstWidth),
md.secondWidth);
element.style.left = md.offsetLeft + delta.x + "px";
first.style.width = (md.firstWidth + delta.x) + "px";
second.style.width = (md.secondWidth - delta.x) + "px";
}
if (direction === "V") {
delta.y = Math.min(Math.max(delta.y, - md.firstHeight), md.secondHeight);
element.style.top = md.offsetTop + delta.y + "px";
first.style.height = (md.firstHeight + delta.y) + "px";
second.style.height = (md.secondHeight - delta.y) + "px";
}
}
}
dragElement(document.getElementById("separator"), "V");
html,
body {
width: 100%;
height: 100%;
padding: 0;
margin: 0;
}
.splitter {
width: 100%;
height: 100%;
display: flex;
flex-direction: column;
}
/*for horizontal*/
#separator {
cursor: row-resize;
background-color: #aaa;
background-repeat: no-repeat;
background-position: center;
width: 100%;
height: 10px;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
}
#map {
width: 100%;
height: 20%;
min-height: 10px;
padding: 0;
margin: 0;
}
#table {
width: 100%;
height: 20%;
min-height: 10px;
}
<div class="splitter">
<div id="map"></div>
<div id="separator"></div>
<div id="table"></div>
</div>
The reason is the secondHeight is getting 0 when we move up and down.
So I get splitter class height and subtract the firstHeight form that and value equals to secondHeight.
secondHeight: (splitter.offsetHeight - first.offsetHeight)
function dragElement(element, direction) {
var md;
const first = document.getElementById("map");
const second = document.getElementById("table");
const splitter = document.getElementById("container");
element.onmousedown = onMouseDown;
function onMouseDown(e) {
md = {
e,
offsetLeft: element.offsetLeft,
offsetTop: element.offsetTop,
offsetBottom: element.offsetBottom,
firstWidth: first.offsetWidth,
secondWidth: second.offsetWidth,
firstHeight: first.offsetHeight,
secondHeight: (splitter.offsetHeight - first.offsetHeight)
};
document.onmousemove = onMouseMove;
document.onmouseup = () => {
document.onmousemove = document.onmouseup = null;
}
}
function onMouseMove(e) {
var delta = {
x: e.clientX - md.e.x,
y: e.clientY - md.e.y
};
if (direction === "H") {
delta.x = Math.min(Math.max(delta.x, -md.firstWidth),
md.secondWidth);
element.style.left = md.offsetLeft + delta.x + "px";
first.style.width = (md.firstWidth + delta.x) + "px";
second.style.width = (md.secondWidth - delta.x) + "px";
}
if (direction === "V") {
delta.y = Math.min(Math.max(delta.y, -md.firstHeight), md.secondHeight);
element.style.top = md.offsetTop + delta.y + "px";
first.style.height = (md.firstHeight + delta.y) + "px";
second.style.height = (md.secondHeight - delta.y) + "px";
}
}
}
dragElement(document.getElementById("separator"), "V");
html,
body {
width: 100%;
height: 100%;
padding: 0;
margin: 0;
}
.splitter {
width: 100%;
height: 100%;
display: flex;
flex-direction: column;
}
/*for horizontal*/
#separator {
cursor: row-resize;
background-color: #aaa;
background-repeat: no-repeat;
background-position: center;
width: 100%;
height: 10px;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
}
#map {
width: 100%;
height: 20%;
min-height: 10px;
padding: 0;
margin: 0;
}
#table {
width: 100%;
height: 20%;
min-height: 10px;
}
<div id="container" class="splitter">
<div id="map"></div>
<div id="separator"></div>
<div id="table"></div>
</div>

How to Dynamically Move Div by Clicking and Dragging

I want to move div according to mouse position within the parent div after click on it.When we leave the mouse pointer then set the div position.
I have searched everywhere and it has led me to over-complicated ways of doing the same thing and involves the use of j-query. I need to strictly use javascript for what I am trying to do.
it's css code
body {
margin: 0px;
padding: 0px;
}
.crop-container{
width: 500px;
height: 500px;
border:5px solid black;
position: relative;
}
.crop-lense{
width: 100px;
height: 100px;
border: 5px dotted black;
position: relative;
z-index: 10;
resize: both;
background-color: transparent;
}
It's html code
<div class="crop-container" id="container" onmousemove="showCoords(event)">
<div class="crop-lense" id="lense">
</div>
</div>
It's javascript code
var lense = document.getElementById('lense');
var container = document.getElementById("container");
var lensemflag = false;
var x;
var y;
lense.addEventListener('mousedown',function(){
lensemflag = true;
console.log(lensemflag);
});
lense.addEventListener('mouseup',function(){
lensemflag = false;
console.log(lensemflag);
});
function showCoords(event) {
x = event.offsetX;
y = event.offsetY;
y = y - 50;
x = x - 50;
}
if(lensemflag==true){
setInterval(function() {
lense.style.top = y + 'px';
lense.style.left = x + 'px';
},
1);
}
Shortest answer:
var lense = document.getElementById("lense");
var container = document.getElementById("container");
var x;
var y;
lense.addEventListener("mousedown", function() {
lense.addEventListener("mousemove", showCoords)
});
lense.addEventListener("mouseup", removeListener);
lense.addEventListener("mouseout", removeListener);
function removeListener() {
lense.removeEventListener("mousemove", showCoords)
}
function showCoords(event) {
if(container.offsetWidth >= event.pageX + lense.offsetWidth / 2 + 10 &&
container.offsetHeight >= event.pageY + lense.offsetHeight / 2 + 10 &&
event.pageX - lense.offsetWidth / 2 > 0 &&
event.pageY - lense.offsetHeight / 2 > 0){
x = event.pageX - lense.offsetWidth / 2;
y = event.pageY - lense.offsetHeight / 2;
lense.style.top = y + "px";
lense.style.left = x + "px";
}
}
body {
margin: 0px;
padding: 0px;
}
.crop-container{
width: 500px;
height: 500px;
border:5px solid black;
position: relative;
}
.crop-lense{
width: 100px;
height: 100px;
border: 5px dotted black;
position: relative;
z-index: 10;
resize: both;
background-color: transparent;
t
}
<div class="crop-container" id="container">
<div class="crop-lense" id="lense">
</div>
</div>

how to make a div return to starting point when the div slides to end

I'm trying to make am image scroll that uses control button and also slides automatically, my problem now is I need to know how to return the div to starting point when the div hit end on left side or on right side, what I could get so far is to know when the div hit an end but don't know how to return it to starting point in case of automatic sliding.
var n = 3; //total number of slides to be display at once
var totalDeal = 9; //total deals to be display
var sliderTotalWidth = 100; //in percentage append % later
var z = (100 / totalDeal) + '%'; //ddslides width
var x = totalDeal / n;
var counter = 1;
$(".dialyDealSlider").css('width', x + '00%');
//$(".ddslides").css('width', ddslidesWidth);
fillDailyDeal(totalDeal, z);
function fillDailyDeal(totalDeal, z) {
var imgUrl = '{$img}';
var ext = '.jpg';
var width = "width:" + z
for (var i = 1; i <= totalDeal; i++) {
var myDiv = $(
"<div class='ddslides' style='" + width + "' >" +
'<div class="dddesc">' +
'<div class="ddtitle">' +
'The is the title of the item it\'s a long title' +
'</div>' +
"<div class='ddprice'>$"+i+"00</div>" +
'<button class="ddview" title="View Item">view item</button>' +
'</div>' +
'<div class="ddimg">' +
'</div>' +
'<div class="vDivider"></div>' +
'<div class="ddSaleBadge">sold 44%</div>' +
'</div>');
$("#dialyDealSlider").append(myDiv);
}
}
$("#prev, #next").click(function() {
if (this.id == "next") {
counter++;
} else {
counter--;
}
//console.log(counter);
if (counter == x) {
alert('rigth end');
//$("#dialyDealSlider").css('left', '0px');
}
if (counter == 1) {
alert('left end');
}
var ddslidesWidth = $(".ddslides").width();
var dir = this.id == "next" ? '-=' : '+=';
var width = ddslidesWidth * n;
//alert(leftpos);
$("#dialyDealSlider").animate({
left: dir + width
}, 800);
});
my code is here JSFIDDLE: https://jsfiddle.net/sammyzeal/LqpL1n2g/
As we can see in the above fiddle, when we slide the div and the price is between $700 and $900 we hit an end then there's an alert, on this point if a user keeps on clicking this next button how do I scroll to the starting point which is between price $100 and $300, I hope my question is cleared and thanks in advance for any help
I just saw that you updated the code as i said , good work. So i wont hesitate to help now, you should make a separate slideNow() function that slides next or previous and you should increment/decrement the counter after checking the current or previous slides, if it is the last slide create a function separate to goToStart() to move to the first slide and if it is th first slide just return from there and do nothing, you can use the following script and test it with various combinations like, first going to the last slide by clicking and then on the last slide click next and see if it goes to the first on and then try clicking left from the first slide and verify if it goes left or stays still.
See a demo below
var n = 3; //total number of slides to be display at once
var totalDeal = 9; //total deals to be display
var sliderTotalWidth = 100; //in percentage append % later
var z = (100 / totalDeal) + '%'; //ddslides width
var x = totalDeal / n;
var counter = 1;
$(".dialyDealSlider").css('width', x + '00%');
//$(".ddslides").css('width', ddslidesWidth);
fillDailyDeal(totalDeal, z);
function fillDailyDeal(totalDeal, z) {
var imgUrl = '{$img}';
var ext = '.jpg';
var width = "width:" + z
for (var i = 1; i <= totalDeal; i++) {
var myDiv = $(
"<div class='ddslides' style='" + width + "' >" +
'<div class="dddesc">' +
'<div class="ddtitle">' +
'The is the title of the item it\'s a long title' +
'</div>' +
"<div class='ddprice'>$" + i + "00</div>" +
'<button class="ddview" title="View Item">view item</button>' +
'</div>' +
'<div class="ddimg">' +
'</div>' +
'<div class="vDivider"></div>' +
'<div class="ddSaleBadge">sold 44%</div>' +
'</div>');
$("#dialyDealSlider").append(myDiv);
}
}
$("#prev, #next").click(function() {
var target = this.id;
//console.log(counter);
if (counter == x && target == "next") {
counter = 1;
goToStart();
return;
}
if (counter == 1 && target == "prev") {
return;
}
if (target == "next") {
counter++;
} else {
counter--;
}
//slide the slides
slideNow(target, n);
});
function goToStart() {
$("#dialyDealSlider").animate({
left: 0
}, 800);
}
function slideNow(target, n) {
var ddslidesWidth = $(".ddslides").width();
var dir = target == "next" ? '-=' : '+=';
var width = ddslidesWidth * n;
//alert(leftpos);
$("#dialyDealSlider").animate({
left: dir + width
}, 800);
}
.dailyDeal {
height: 150px;
width: 100%;
margin-top: 15px;
padding: 0 !important;
}
.dialyDealBox {
float: left;
height: 150px;
padding: 0 !important;
overflow: hidden;
}
.dialyDealSlider {
width: 100%;
height: 150px;
position: absolute;
border: 1px solid #ddd;
}
.ddslides {
height: 150px;
width: 2%;
float: left;
background-color: #fff;
position: relative;
padding: 10px 0;
}
#media only screen and (max-width: 768px) {
.ddslides {
width: 16.66%;
}
}
#media (max-width:320px) {
.ddslides {
width: 33.33%;
}
}
.ddimg {
float: left;
margin: auto;
height: 100%;
width: 32%;
margin-right: 4px;
}
.ddimg>a>img {
height: 100%;
width: 100%;
}
.dddesc {
float: left;
margin: auto;
height: 100%;
width: 65%;
padding: 0 10px 0 15px;
}
.ddSaleBadge {
position: absolute;
top: 5px;
right: 5px;
width: 37px;
height: 38px;
padding: 5px 2px 4px 3px;
overflow: hidden;
background: url("/trobay/img/icon/label.png") no-repeat 50% 50%;
line-height: 14px;
text-align: center;
color: #fff;
}
.ddtitle {
margin-bottom: 10px;
}
.ddtitle>a {
font-size: 14px;
color: #666666;
text-decoration: none;
}
.ddtitle>a:hover {
color: #e4393c;
text-decoration: none;
}
.ddprice {
color: #e4393c;
font-size: 16px;
margin-bottom: 10px;
}
.ddview {
color: #fff;
background-color: #e4393c;
font-size: 14px;
border: 0;
outline: 0;
padding: 4px;
font-weight: bold;
}
.ddslider-prev {
cursor: pointer;
position: absolute;
top: 50%;
width: auto;
margin-top: -22px;
padding: 5px;
color: #666666;
font-weight: bold;
font-size: 18px;
transition: 0.6s ease;
left: 0;
z-index: 10;
background-color: rgba(221, 221, 221, 1);
display: block;
}
.ddslider-next {
cursor: pointer;
position: absolute;
right: 0;
top: 50%;
width: auto;
margin-top: -22px;
padding: 5px;
color: #666666;
font-weight: bold;
font-size: 18px;
transition: 0.6s ease;
z-index: 10;
background-color: rgba(221, 221, 221, 1);
display: block;
}
.vDivider {
height: 130px;
border-right: 1px dotted #666;
position: absolute;
top: 10px;
;
right: 0;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="row">
<div class="dailyDeal col-md-12">
<div class="dialyDealBox col-xs-10" id="dialyDealBox">
<div class="dialyDealSlider" id="dialyDealSlider">
</div>
<div class="ddslider-prev" id="prev">❮</div>
<div class="ddslider-next" id="next">❯</div>
</div>
</div>
</div>

Categories

Resources