How to restrict image dragging inside div? - javascript

I have attached snippet where I have an image which is draggable and zoomable inside a div. But there is one issue, when moving image from left to right, it should not be able to move if the corner of image meets the corner of parent for both X and Y. I actually want to know when the corners of image meets with parent div corners because I dont want to allow dragging when this condition meets. Background red color should not be visible when dragging image.
window.repositionImage = function(event){
var element = document.getElementById('img');
element.addEventListener('mousedown', function(e){
e.stopPropagation();
element.style.cursor = "grabbing";
if (e.target != element) return;
var offsetX = e.pageX - element.offsetLeft;
var offsetY = e.pageY - element.offsetTop;
var move = function(e){
element.style.left = e.pageX - offsetX + "px";
element.style.top = e.pageY - offsetY + "px";
}
var stop = function(){
element.style.cursor = "default";
document.removeEventListener("mousemove", move);
document.removeEventListener("mouseup", stop);
}
document.addEventListener("mousemove", move);
document.addEventListener("mouseup", stop);
})
}
window.panChangeHandler = function(e){
var element = document.getElementById('img');
if (e.target.value == 0) {
element.style.left = "0px";
element.style.top = "0px";
}
img.style.transform = `scale(1.${e.target.value})`;
}
.item {
border: 1px solid;
background: red;
width: 300px;
height: 300px;
overflow: hidden;
position:relative;
}
.item img {
position:absolute;
width: 100%;
height: 100%;
-webkit-user-drag: none;
left:0;
top:0;
}
.slider {
z-index: 9;
position: absolute;
left: 0;
top: 0;
margin-left: -20px;
margin-top: 70px;
writing-mode: bt-lr; /* IE */
-webkit-appearance: slider-vertical; /* WebKit */
transform: rotateZ(270deg);
}
.slider input {
width: 80px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class='item'>
<span class='slider'>
<input type='range' aria-orientation="vertical"
value="0" min="0" max="9" step="1" oninput="panChangeHandler(event)"
/>
</span>
<img id='img' src="https://images.unsplash.com/photo-1494548162494-384bba4ab999?ixlib=rb-1.2.1&w=1000&q=80" alt='image' onmouseover="repositionImage(event)" />
</div>

There is a simple css fix you can try but I'm not sure about it's crossbrowser compatibility. Change the .item img position to sticky.
window.repositionImage = function(event){
var element = document.getElementById('img');
element.addEventListener('mousedown', function(e){
e.stopPropagation();
element.style.cursor = "grabbing";
if (e.target != element) return;
var offsetX = e.pageX - element.offsetLeft;
var offsetY = e.pageY - element.offsetTop;
var move = function(e){
element.style.left = e.pageX - offsetX + "px";
element.style.top = e.pageY - offsetY + "px";
}
var stop = function(){
element.style.cursor = "default";
document.removeEventListener("mousemove", move);
document.removeEventListener("mouseup", stop);
}
document.addEventListener("mousemove", move);
document.addEventListener("mouseup", stop);
})
}
window.panChangeHandler = function(e){
var element = document.getElementById('img');
img.style.transform = `scale(1.${e.target.value})`;
}
document.getElementById("img").disabled = true;
.item {
border: 1px solid;
background: red;
width: 300px;
height: 300px;
overflow: hidden;
position:relative;
}
.item img {
position: sticky;
width: 100%;
height: 100%;
-webkit-user-drag: none;
left:0;
top:0;
}
.slider {
z-index: 9;
position: absolute;
left: 0;
top: 0;
margin-left: -20px;
margin-top: 70px;
writing-mode: bt-lr; /* IE */
-webkit-appearance: slider-vertical; /* WebKit */
transform: rotateZ(270deg);
}
.slider input {
width: 80px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class='item'>
<span class='slider'>
<input type='range' aria-orientation="vertical"
value="0" min="0" max="9" step="1" oninput="panChangeHandler(event)"
/>
</span>
<img id='img' src="https://images.unsplash.com/photo-1494548162494-384bba4ab999?ixlib=rb-1.2.1&w=1000&q=80" alt='image' onmouseover="repositionImage(event)" />
</div>

Check
if (e.target.tagName == "DIV" ) return;
On drop event

I managed to solve this issue:
function parseComplexStyleProperty(str) {
var regex = /(\w+)\((.+?)\)/g,
transform = {},
match;
while ((match = regex.exec(str))) transform[match[1]] = match[2];
return transform;
};
window.repositionImage = function(event){
var element = document.getElementById('img');
element.addEventListener('mousedown', function(e){
e.stopPropagation();
element.style.cursor = "grabbing";
if (e.target != element) return;
var offsetX = e.pageX - element.offsetLeft;
var offsetY = e.pageY - element.offsetTop;
var x = 0;
var y = 0;
var move = function(e){
x = e.pageX - offsetX;
y = e.pageY - offsetY;
element.style.left = e.pageX - offsetX + "px";
element.style.top = e.pageY - offsetY + "px";
}
var stop = function(){
element.style.cursor = "default";
var t = parseComplexStyleProperty(element.style.transform);
if (!Object.keys(t).length) {
element.style.left = "0px";
element.style.top = "0px";
}
else {
var imageWidth = element.clientWidth * parseFloat(t.scale);
var imageHeight =
element.clientHeight * parseFloat(t.scale);
var pointToSubX = Math.trunc(
(imageWidth - parent.clientWidth) / 2
);
var pointToSubY = Math.trunc(
(imageHeight - parent.clientHeight) / 2
);
if (x > pointToSubX || x < -pointToSubX) {
if (x > pointToSubX)
element.style.left = pointToSubX + "px";
else element.style.left = -pointToSubX + "px";
}
if (y > pointToSubY || y < -pointToSubY) {
if (y > pointToSubY)
element.style.top = pointToSubY + "px";
else element.style.top = -pointToSubY + "px";
}
document.removeEventListener("mousemove", move);
document.removeEventListener("mouseup", stop);
}
}
document.addEventListener("mousemove", move);
document.addEventListener("mouseup", stop);
})
}
window.panChangeHandler = function(e){
var element = document.getElementById('img');
img.style.transform = `scale(1.${e.target.value})`;
}
document.getElementById("img").disabled = true;
.item {
margin-right: 1px;
height: 200px;
background: white;
overflow: hidden;
position: relative;
}
.item img {
transform: scale(1);
position: relative;
background-color: #eee;
width: 100%;
height: 100%;
-webkit-user-drag: none;
left:0;
top:0;
}
.slider {
z-index: 9;
position: absolute;
left: 0;
top: 0;
margin-left: -20px;
margin-top: 70px;
writing-mode: bt-lr; /* IE */
-webkit-appearance: slider-vertical; /* WebKit */
transform: rotateZ(270deg);
}
.slider input {
width: 80px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class='item'>
<span class='slider'>
<input type='range' aria-orientation="vertical"
value="0" min="0" max="9" step="1" oninput="panChangeHandler(event)"
/>
</span>
<img id='img' src="https://images.unsplash.com/photo-1494548162494-384bba4ab999?ixlib=rb-1.2.1&w=1000&q=80" alt='image'
onmouseover="repositionImage(event)" />
</div>

Related

resizing a div without changing the position of sides

I have made a div with handles that can be used to resize it. Those work well when the rotation of the div is 0 deg. But when angle of rotation changes and I try to resize the div from one side, the position of other sides changes. I want to keep the position fixed of rest of sides when I try to resize it at from one handle. Here is my code: Help me what type of changes should I do in it.
const resizableDiv = document.querySelector('#resizable-div');
const handles = document.querySelectorAll('.handle');
let isResizing = false;
let currentHandle = null;
let originalWidth = 0;
let originalHeight = 0;
let originalX = 0;
let originalY = 0;
let currentX = 0;
let currentY = 0;
handles.forEach(handle => {
handle.addEventListener('mousedown', e => {
isResizing = true;
currentHandle = handle;
originalWidth = resizableDiv.offsetWidth;
originalHeight = resizableDiv.offsetHeight;
originalX = resizableDiv.offsetLeft;
originalY = resizableDiv.offsetTop;
currentX = e.pageX;
currentY = e.pageY;
});
});
document.addEventListener('mouseup', () => {
isResizing = false;
});
document.addEventListener('mousemove', e => {
if (!isResizing) return;
let deltaX = e.pageX - currentX;
let deltaY = e.pageY - currentY;
if (currentHandle.classList.contains('handle-n')) {
resizableDiv.style.height = originalHeight - deltaY + 'px';
resizableDiv.style.top = originalY + deltaY + 'px';
} else if (currentHandle.classList.contains('handle-e')) {
resizableDiv.style.width = originalWidth + deltaX + 'px';
} else if (currentHandle.classList.contains('handle-s')) {
resizableDiv.style.height = originalHeight + deltaY + 'px';
} else if (currentHandle.classList.contains('handle-w')) {
resizableDiv.style.width = originalWidth - deltaX + 'px';
resizableDiv.style.left = originalX + deltaX + 'px';
}
});
// rotation
const rotateHandle = document.querySelector('.rotate-handle');
let isDragging = false;
let currentDeg = 0;
let startX = 0;
let startY = 0;
rotateHandle.addEventListener('mousedown', function(e) {
isDragging = true;
startX = e.clientX;
startY = e.clientY;
});
document.addEventListener('mouseup', function() {
isDragging = false;
});
document.addEventListener('mousemove', function(e) {
if (!isDragging) return;
const deltaX = e.clientX - startX;
const deltaY = e.clientY - startY;
currentDeg = Math.atan2(deltaY, deltaX) * (180 / Math.PI);
resizableDiv.style.transform = `rotate(${currentDeg}deg)`;
});
#resizable-div {
position: absolute;
width: 200px;
height: 200px;
left: 50px;
top: 50px;
background-color: #ddd;
}
.handle {
position: absolute;
width: 10px;
height: 10px;
background-color: #fff;
border: 1px solid #000;
}
.handle-n {
top: -5px;
left: 50%;
transform: translateX(-50%);
cursor: n-resize;
}
.handle-e {
right: -5px;
top: 50%;
transform: translateY(-50%);
cursor: e-resize;
}
.handle-s {
bottom: -5px;
left: 50%;
transform: translateX(-50%);
cursor: s-resize;
}
.handle-w {
left: -5px;
top: 50%;
transform: translateY(-50%);
cursor: w-resize;
}
.rotate-handle {
bottom: 0px;
right: 0px;
border-radius: 50%;
background-color: white;
cursor: pointer;
}
<div id="resizable-div">
<div class="handle handle-n"></div>
<div class="handle handle-e"></div>
<div class="handle handle-s"></div>
<div class="handle handle-w"></div>
<div class="handle rotate-handle"></div>
</div>
Try This:
I removed the left and top event from JS, anded a container to the resizable-div element and added flex to it.
const resizableDiv = document.querySelector('#resizable-div');
const handles = document.querySelectorAll('.handle');
let isResizing = false;
let currentHandle = null;
let originalWidth = 0;
let originalHeight = 0;
let originalX = 0;
let originalY = 0;
let currentX = 0;
let currentY = 0;
handles.forEach(handle => {
handle.addEventListener('mousedown', e => {
isResizing = true;
currentHandle = handle;
originalWidth = resizableDiv.offsetWidth;
originalHeight = resizableDiv.offsetHeight;
originalX = resizableDiv.offsetLeft;
originalY = resizableDiv.offsetTop;
currentX = e.pageX;
currentY = e.pageY;
});
});
document.addEventListener('mouseup', () => {
isResizing = false;
});
document.addEventListener('mousemove', e => {
if (!isResizing) return;
let deltaX = e.pageX - currentX;
let deltaY = e.pageY - currentY;
if (currentHandle.classList.contains('handle-n')) {
resizableDiv.style.height = originalHeight - deltaY + 'px';
} else if (currentHandle.classList.contains('handle-e')) {
resizableDiv.style.width = originalWidth + deltaX + 'px';
} else if (currentHandle.classList.contains('handle-s')) {
resizableDiv.style.height = originalHeight + deltaY + 'px';
} else if (currentHandle.classList.contains('handle-w')) {
resizableDiv.style.width = originalWidth - deltaX + 'px';
}
});
// rotation
const rotateHandle = document.querySelector('.rotate-handle');
let isDragging = false;
let currentDeg = 0;
let startX = 0;
let startY = 0;
rotateHandle.addEventListener('mousedown', function(e) {
isDragging = true;
startX = e.clientX;
startY = e.clientY;
});
document.addEventListener('mouseup', function() {
isDragging = false;
});
document.addEventListener('mousemove', function(e) {
if (!isDragging) return;
const deltaX = e.clientX - startX;
const deltaY = e.clientY - startY;
currentDeg = Math.atan2(deltaY, deltaX) * (180 / Math.PI);
resizableDiv.style.transform = `rotate(${currentDeg}deg)`;
});
.container{
position:relative;
min-height:100vh;
display:flex;
justify-content:center;
align-items:center;
}
#resizable-div {
position: absolute;
width: 200px;
height: 200px;
background-color: #ddd;
transform-orgin:top left;
}
.handle {
position: absolute;
width: 10px;
height: 10px;
background-color: #fff;
border: 1px solid #000;
}
.handle-n {
top: -5px;
left: 50%;
transform: translateX(-50%);
cursor: n-resize;
}
.handle-e {
right: -5px;
top: 50%;
transform: translateY(-50%);
cursor: e-resize;
}
.handle-s {
bottom: -5px;
left: 50%;
transform: translateX(-50%);
cursor: s-resize;
}
.handle-w {
left: -5px;
top: 50%;
transform: translateY(-50%);
cursor: w-resize;
}
.rotate-handle {
bottom: 0px;
right: 0px;
border-radius: 50%;
background-color: white;
cursor: pointer;
}
<div class="container">
<div id="resizable-div">
<div class="handle handle-n"></div>
<div class="handle handle-e"></div>
<div class="handle handle-s"></div>
<div class="handle handle-w"></div>
<div class="handle rotate-handle"></div>
</div>
</div>

How to limit the direction of resize of a container with mouse

I have a container which can resize from right-side and bottom .
It is resizing correctly but in both sides that is in height and width at the same time in unlimited length .
Can there be a way to limit direction of resize either bottom side or right side increase or decrease in size .
Single side increase is only possible when using 1 condition in if
Here is the code :
const panel = document.getElementById("styleChangeOuterTag");
let m_pos;
let m_pos1;
function resize(e) {
const dx = m_pos - e.x;
const dy = m_pos1 - e.y;
m_pos = e.x;
m_pos1 = e.y;
panel.style.width = (parseInt(getComputedStyle(panel).width) - dx) + "px";
panel.style.height = (parseInt(getComputedStyle(panel).height) - dy) + "px";
}
panel.addEventListener("mousedown", function(e) {
if (e.offsetX > panel.clientWidth - 10) {
m_pos = e.x;
document.addEventListener("mousemove", resize);
} else if (e.offsetY > panel.clientHeight - 10) {
m_pos1 = e.y;
document.addEventListener("mousemove", resize);
}
});
document.addEventListener("mouseup", function() {
document.removeEventListener("mousemove", resize);
});
#styleChangeOuterTag {
/* display: none; */
/* position: fixed; */
position: relative;
top: 0;
left: 0;
width: 300px;
height: 300px;
padding: 2vw 1.5vw;
background-color: rgb(255, 245, 245);
border: 2px solid rgb(255, 60, 255);
border-radius: 3px;
z-index: 5;
user-select: none;
}
#styleChangeOuterTag::after {
content: '';
background-color: #ccc;
position: absolute;
top: 0;
right: 0;
width: 10px;
height: 100%;
cursor: ew-resize;
}
#styleChangeOuterTag::before {
content: '';
background-color: #ccc;
position: absolute;
bottom: 0;
right: 0;
width: 100%;
height: 10px;
cursor: ns-resize;
}
#styleOptionDetails {
border: 2px solid purple;
border-radius: 3px;
padding: 1vw;
overflow: auto;
}
<div id="styleChangeOuterTag">
<hr>
<div id="styleOptionDetails">
</div>
</div>
Can you tell about how to size the clickable width(grey part in Container-which trigger resize) as now it not right in size and don't work in whole width
created with e.offsetX > panel.clientWidth - 10
Thanks for help in advance
You may add additional condition in to your resize function, something like this:
const minWidth = 150
const maxWidth = 500
const minHeight = 150
const maxHeight = 500
function resize(e) {
const dx = m_pos - e.x;
const dy = m_pos1 - e.y;
m_pos = e.x;
m_pos1 = e.y;
const newWidth = parseInt(getComputedStyle(panel).width) - dx
const newHeight = parseInt(getComputedStyle(panel).height - dy
if (newWidth > minWidth && newWidth < maxWidth) {
panel.style.width = newWidth + "px";
}
if (newHeight > minHeight && newHeight < maxHeight) {
panel.style.height = newHeight + "px";
}
}

How can i show the position of a circle following mouse in other divs in Javascript

I want to find the position of a circle that's following the mouse in two boxes
and the position of the circle when it's out of them. In addition when it (the circle) goes to red box the circle color changes to black, when it goes to red box it's color changes to red and when it's over neither of them it's blue.
I have included the picture here.
window.addEventListener("mousemove", function(e) {
let x = e.clientX;
let y = e.clientY;
let mouse = "Mouse : " + x + " " + y;
document.getElementById("mouseText").innerText = mouse;
let circle = document.getElementById("circleText");
let newX = e.clientX + 5;
let newY = e.clientY + 5;
let newCircle = "circle : " + newX + " " + newY;
document.getElementById("circleText").innerText = newCircle;
let circle2 = document.getElementById("circle");
circle2.style.marginTop = `${newY}px`;
circle2.style.marginLeft = `${newX}px`;
});
function onMousemove(e) {
var m_posx = 0,
m_posy = 0,
e_posx = 0,
e_posy = 0,
obj = this;
//get mouse position on document crossbrowser
if (!e) {
e = window.event;
}
if (e.pageX || e.pageY) {
m_posx = e.pageX;
m_posy = e.pageY;
} else if (e.clientX || e.clientY) {
m_posx =
e.clientX +
document.body.scrollLeft +
document.documentElement.scrollLeft;
m_posy =
e.clientY + document.body.scrollTop + document.documentElement.scrollTop;
}
//get parent element position in document
if (obj.offsetParent) {
do {
e_posx += obj.offsetLeft;
e_posy += obj.offsetTop;
} while ((obj = obj.offsetParent));
}
// mouse position minus elm position is mouseposition relative to element:
dbg.innerHTML =
" X Position: " + (m_posx - e_posx) + " Y Position: " + (m_posy - e_posy);
}
html {
position: relative;
}
#circle {
width: 15px;
height: 15px;
background-color: blue;
border-radius: 50px;
position: absolute;
}
#row {
display: flex;
margin: 0 200px;
}
#blackShape {
position: relative;
width: 250px;
height: 250px;
background-color: black;
margin-top: 125px;
margin-left: 300px;
right: 180px;
}
#redCircle {
position: absolute;
width: 25px;
height: 25px;
background-color: red;
border-radius: 50px;
top: 50%;
left: 45%;
}
#redShape {
position: relative;
width: 250px;
height: 250px;
background-color: red;
margin-top: 125px;
margin-right: 150px;
}
#blackCircle {
position: absolute;
width: 25px;
height: 25px;
background-color: black;
border-radius: 50px;
top: 50%;
left: 45%;
}
<div id="mouseText"></div>
<div id="circleText"></div>
<div id="circle"></div>
<div id="dbg"></div>
<div id="row">
<div id="blackShape">
<div id="redCircle"></div>
</div>
<div id="redShape">
<div id="blackCircle"></div>
</div>
</div>
This script adjusts the position and size of the elements and listens when the blue circle will fall in these areas. When it leaves the area, the color style returns to its original state.
Example when the blue dot is in the region:
After resizing the "Run code snippet" screen, it may not work correctly. Please copy the code and try it.
var pos = 5; //<-- Circle position
var csz = 15; //<-- Circle size
var c = document.getElementById('circle');
window.onload = window.onresize = elPositions;
function elPositions() {
blc = document.getElementById('blackShape');
blcH = blc.offsetHeight;
blcW = blc.offsetWidth;
blcT = blc.offsetTop;
blcL = blc.offsetLeft;
red = document.getElementById('redShape');
redH = red.offsetHeight;
redW = red.offsetWidth;
redT = red.offsetTop;
redL = red.offsetLeft;
}
function changeColor(y, x) {
if (redT - pos < y && redT + redH - pos - csz > y && redL - pos < x && redL + redW - pos - csz > x) {
c.style.backgroundColor = 'black';
}
else if (blcT - pos < y && blcT + blcH - pos - csz > y && blcL - pos < x && blcL + blcW - pos - csz > x) {
c.style.backgroundColor = 'red';
}
else {
c.style.backgroundColor = '';
}
}
////////////////////////////////////////////////
window.addEventListener("mousemove", function (e) {
let x = e.clientX;
let y = e.clientY;
let mouse = "Mouse : " + x + " " + y;
document.getElementById("mouseText").innerText = mouse;
let circle = document.getElementById("circleText");
let newX = e.clientX + pos;
let newY = e.clientY + pos;
let newCircle = "circle : " + newX + " " + newY;
document.getElementById("circleText").innerText = newCircle;
let circle2 = document.getElementById("circle");
circle2.style.marginTop = newY + 'px';
circle2.style.marginLeft = newX + 'px';
changeColor(newY, newX); //<-- New Line
});
function onMousemove(e) {
var m_posx = 0,
m_posy = 0,
e_posx = 0,
e_posy = 0,
obj = this;
//get mouse position on document crossbrowser
if (!e) {
e = window.event;
}
if (e.pageX || e.pageY) {
m_posx = e.pageX;
m_posy = e.pageY;
}
else if (e.clientX || e.clientY) {
m_posx = e.clientX + document.body.scrollLeft + document.documentElement.scrollLeft;
m_posy = e.clientY + document.body.scrollTop + document.documentElement.scrollTop;
}
//get parent element position in document
if (obj.offsetParent) {
do {
e_posx += obj.offsetLeft;
e_posy += obj.offsetTop;
}
while ((obj = obj.offsetParent));
}
// mouse position minus elm position is mouseposition relative to element:
dbg.innerHTML = " X Position: " + (m_posx - e_posx) + " Y Position: " + (m_posy - e_posy);
}
html {
position: relative;
}
#circle {
width: 15px;
height: 15px;
background-color: blue;
border-radius: 50px;
position: absolute;
z-index: 1; /*<-- New Line*/
}
#row {
display: flex;
margin: 0 200px;
}
#blackShape {
position: relative;
width: 250px;
height: 250px;
background-color: black;
margin-top: 125px;
margin-left: 300px;
right: 180px;
}
#redCircle {
position: absolute;
width: 25px;
height: 25px;
background-color: red;
border-radius: 50px;
top: 50%;
left: 45%;
}
#redShape {
position: relative;
width: 250px;
height: 250px;
background-color: red;
margin-top: 125px;
margin-right: 150px;
}
#blackCircle {
position: absolute;
width: 25px;
height: 25px;
background-color: black;
border-radius: 50px;
top: 50%;
left: 45%;
}
<div id="mouseText"></div>
<div id="circleText"></div>
<div id="circle"></div>
<div id="dbg"></div>
<div id="row">
<div id="blackShape">
<div id="redCircle"></div>
</div>
<div id="redShape">
<div id="blackCircle"></div>
</div>
</div>
Example when the mouse cursor is in the region:
document.getElementById('blackShape').addEventListener("mouseover", getColor);
document.getElementById('blackShape').addEventListener("mouseout", retColor);
document.getElementById('redShape').addEventListener("mouseover", getColor);
document.getElementById('redShape').addEventListener("mouseout", retColor);
function getColor() {
var x = this.id;
var c = document.getElementById('circle');
if(x === 'redShape') {
c.style.backgroundColor = 'black'
}
else if (x === 'blackShape') {
c.style.backgroundColor = 'red'
}
}
function retColor() {
var c = document.getElementById('circle');
c.style.backgroundColor = '';
}
////////////////////////////////////////////////
window.addEventListener("mousemove", function (e) {
let x = e.clientX;
let y = e.clientY;
let mouse = "Mouse : " + x + " " + y;
document.getElementById("mouseText").innerText = mouse;
let circle = document.getElementById("circleText");
let newX = e.clientX + 5;
let newY = e.clientY + 5;
let newCircle = "circle : " + newX + " " + newY;
document.getElementById("circleText").innerText = newCircle;
let circle2 = document.getElementById("circle");
circle2.style.marginTop = newY + 'px';
circle2.style.marginLeft = newX + 'px';
});
function onMousemove(e) {
var m_posx = 0,
m_posy = 0,
e_posx = 0,
e_posy = 0,
obj = this;
//get mouse position on document crossbrowser
if (!e) {
e = window.event;
}
if (e.pageX || e.pageY) {
m_posx = e.pageX;
m_posy = e.pageY;
}
else if (e.clientX || e.clientY) {
m_posx = e.clientX + document.body.scrollLeft + document.documentElement.scrollLeft;
m_posy = e.clientY + document.body.scrollTop + document.documentElement.scrollTop;
}
//get parent element position in document
if (obj.offsetParent) {
do {
e_posx += obj.offsetLeft;
e_posy += obj.offsetTop;
}
while ((obj = obj.offsetParent));
}
// mouse position minus elm position is mouseposition relative to element:
dbg.innerHTML = " X Position: " + (m_posx - e_posx) + " Y Position: " + (m_posy - e_posy);
}
html {
position: relative;
}
#circle {
width: 15px;
height: 15px;
background-color: blue;
border-radius: 50px;
position: absolute;
z-index: 1; /*<-- New Line*/
}
#row {
display: flex;
margin: 0 200px;
}
#blackShape {
position: relative;
width: 250px;
height: 250px;
background-color: black;
margin-top: 125px;
margin-left: 300px;
right: 180px;
}
#redCircle {
position: absolute;
width: 25px;
height: 25px;
background-color: red;
border-radius: 50px;
top: 50%;
left: 45%;
}
#redShape {
position: relative;
width: 250px;
height: 250px;
background-color: red;
margin-top: 125px;
margin-right: 150px;
}
#blackCircle {
position: absolute;
width: 25px;
height: 25px;
background-color: black;
border-radius: 50px;
top: 50%;
left: 45%;
}
<div id="mouseText"></div>
<div id="circleText"></div>
<div id="circle"></div>
<div id="dbg"></div>
<div id="row">
<div id="blackShape">
<div id="redCircle"></div>
</div>
<div id="redShape">
<div id="blackCircle"></div>
</div>
</div>

How can I move tooltip on top of the mouse pointer?

let screenLog = document.querySelector('#screen-log');
document.addEventListener('mousemove', logKey);
var imgHgt = document.getElementById('box');
function logKey(e) {
var d = document.getElementById('TextHidden');
d.style.position = "absolute";
d.style.left = e.clientX +'px';
d.style.top = e.clientY +'px';
screenLog.innerHTML = `${e.clientX}, ${e.clientY}` + "<br>Image Height = " + imgHgt.offsetHeight + "<br>Image Width = " + imgHgt.offsetWidth;
}
#box { width: 40%; display: block; position: absolute; overflow: hidden; }
.image { display: block; width: 100%; z-index: 1; }
#TextHidden { display: none; color: red; font-size; 20px; z-index: 10; } #box:hover #TextHidden { display: block; }
#screen-log { z-index: 11; }
<div id="box">
<img src="https://res.cloudinary.com/vaqar/image/upload/v1499826226/DSC_0361_y3mv4r.jpg" class="image"></p> </img>
<div id="TextHidden">Hovering<p id="screen-log"></p></div>
</div>
I am trying to move comments on top of the the mouse pointer, but having no success.
Change your left and top position pixels like,
d.style.left = (e.clientX - 50) +'px';
d.style.top = (e.clientY - 100) +'px';
And the snippet as follows,
let screenLog = document.querySelector('#screen-log');
document.addEventListener('mousemove', logKey);
var imgHgt = document.getElementById('box');
function logKey(e) {
var d = document.getElementById('TextHidden');
d.style.position = "absolute";
d.style.left = (e.clientX - 50) +'px';
d.style.top = (e.clientY - 100) +'px';
screenLog.innerHTML = `${e.clientX}, ${e.clientY}` + "<br>Image Height = " + imgHgt.offsetHeight + "<br>Image Width = " + imgHgt.offsetWidth;
}
#box { width: 40%; display: block; position: absolute; overflow: hidden; }
.image { display: block; width: 100%; z-index: 1; }
#TextHidden { display: none; color: red; font-size; 20px; z-index: 10; } #box:hover #TextHidden { display: block; }
#screen-log { z-index: 11; }
<div id="box">
<img src="https://res.cloudinary.com/vaqar/image/upload/v1499826226/DSC_0361_y3mv4r.jpg" class="image"></p> </img>
<div id="TextHidden">Hovering<p id="screen-log"></p></div>
</div>
Your approach is working in principle, but you don't see the moving text because it is currently hidden. Note that I commented out the overflow: hidden and display: none properties in your stylesheet.
let screenLog = document.querySelector('#screen-log');
document.addEventListener('mousemove', logKey);
var imgHgt = document.getElementById('box');
function logKey(e) {
var d = document.getElementById('TextHidden');
d.style.position = "absolute";
d.style.left = e.clientX + 'px';
d.style.top = e.clientY + 'px';
screenLog.innerHTML = `${e.clientX}, ${e.clientY}` + "<br>Image Height = " + imgHgt.offsetHeight + "<br>Image Width = " + imgHgt.offsetWidth;
}
#box {
width: 40%;
display: block;
position: absolute;
#overflow: hidden;
}
.image {
display: block;
width: 100%;
z-index: 1;
}
#TextHidden {
#display: none;
color: red;
font-size: 20px;
z-index: 10;
}
#box:hover #TextHidden {
display: block;
}
#screen-log {
z-index: 11;
}
<div id="box">
<div id="TextHidden">
<p id="screen-log"></p>
</div>
</div>

Onclick in body change div position with javascript coordinates

i just want to change div position onclick, when i click in the body i want div to appear there.
#elem{
width: 100px;
height: 100px;
border: 1px solid red;
position: absolute;
top: 0;
left: 150px;
}
var elem = document.getElementById("elem");
elem.onclick = funct;
function funct( event ){
var x = event.clientX;
var y = event.clientY;
this.style.top = y + 'px';
this.style.left = x + 'px';
}
Here's the working example. You need to add event listener to document/body element:
var target = document.getElementById('target');
document.addEventListener('click', function (e) {
target.style.left = e.clientX + 'px';
target.style.top = e.clientY + 'px';
});
#target {
width: 50px;
height: 50px;
background-color: #ccc;
position: absolute;
}
<div id="target"></div>
You can expand the handler further and center the div on the cursor position as well:
var target = document.getElementById('target');
document.addEventListener('click', function (e) {
target.style.left = e.clientX - target.offsetWidth / 2 + 'px';
target.style.top = e.clientY - target.offsetHeight / 2 + 'px';
});
#target {
width: 50px;
height: 50px;
background-color: #ccc;
position: absolute;
}
<div id="target"></div>

Categories