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

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>

Related

JavaScript not placing object in correct mouse position

I have a stormTrooper characters randomly placed around my circle called deathStar. I am trying to make my stormTroopers place in the location that my mouse clicks once they have already been clicked. But instead they are placing in random locations. I'm still having problems grasping the concept of getBoundingClientRect() and offset. I thought adding them together and subtracting from mouseClick would be the solution. I'm also open to any other advice for this project. The area I'm having problems with is the mouseDown event listener.
//Global variables
let deathStar = document.querySelector(".deathStar")
let counter = 0;
let darthVader = document.querySelector(".darthVader");
let vaderX = darthVader.offsetLeft;
let vaderY = darthVader.offsetTop;
//Death Star information
const x1 = window.scrollX + deathStar.getBoundingClientRect().left; // top left X
const y1 = window.scrollY + deathStar.getBoundingClientRect().top; // top left Y
const x2 = window.scrollY + deathStar.getBoundingClientRect().right; // bottom right X
const y2 = window.scrollY + deathStar.getBoundingClientRect().bottom; // top right Y
let midPointX = (x2 + x1) / 2;
let midPointY = (y2 + y1) / 2;
let radius = x2 - midPointX - 10;
//Create a storm trooper
function createStormTrooper(){
colorArray = ['blue', 'green', 'orange', 'yellow', 'white', 'red','purple', 'pink'];
counter++;
//create each div
let stormTrooper = document.createElement('div');
let body = document.createElement('div');
let gun = document.createElement('div');
let head = document.createElement('div');
let legSplit = document.createElement('div');
//append div to proper div
deathStar.append(stormTrooper);
stormTrooper.append(body);
body.append(gun);
body.append(head);
body.append(legSplit);
//add classes
stormTrooper.classList.add("trooper",'stormTrooperPart' + counter, "stormTrooper");
body.classList.add("trooper", 'stormTrooperPart' + counter, "body");
gun.classList.add("trooper", 'stormTrooperPart' + counter, "gun");
head.classList.add("trooper", 'stormTrooperPart' + counter, 'head');
legSplit.classList.add("trooper", 'stormTrooperPart' + counter, "legSplit");
let randomColor = Math.floor(Math.random()*8);
body.style.backgroundColor = colorArray[randomColor];
placeInsideDeathStar(stormTrooper);
}
//Places a trooper in a random spot inside the death star
function placeInsideDeathStar(stormTrooper){
let theta = Math.random() * Math.PI * 2;
let r = (Math.sqrt(Math.random()) * radius);
let yRandom = r * Math.sin(theta);
let xRandom = r * Math.cos(theta);
stormTrooper.style.transform = "translate(" + (xRandom) + "px," + (yRandom) + "px)";
}
//Create Troopers
for(let i = 0; i < 10;i++ ){
createStormTrooper();
}
let targetFound = false;
let stormTrooper;
//Storm Trooper placing and removing
document.addEventListener('mousedown', (e) => {
//variable to check if type stormtrooper
let typeTrooper = e.target.className.split(" ")[0];
//If type storm trooper of already have a target
if(typeTrooper == "trooper" || targetFound == true){
//if no stormTrooper found yet
if(targetFound == false){
stormTrooperChecker = document.querySelector("." + e.target.className.split(" ")[1]);
targetFound = true;
}
//if stormTrooper found
else{
//Distance to move stormTrooper
var xposition = (e.clientX - stormTrooperChecker.getBoundingClientRect().left + stormTrooperChecker.offsetLeft);
var yposition = (e.clientY - stormTrooperChecker.getBoundingClientRect().top + stormTrooperChecker.offsetTop);
//Move Storm Trooper
stormTrooperChecker.style.transform = "translate("+ (xposition)+ "px," + yposition + "px)";
//Check if outside of death star
if(pTheoremAB(stormTrooperChecker.offsetTop, stormTrooperChecker.offsetLeft) > pTheoremC(radius) || pTheoremAB(stormTrooperChecker.offsetTop, stormTrooperChecker.offsetLeft) < -pTheoremC(radius)){
stormTrooperChecker.classList.add("explosion")
stormTrooperChecker.innerHTML = "";
setTimeout(() => stormTrooperChecker.remove(), 1000);
}
//reset targetFound
targetFound = false;
}
//stormTrooperChecker.remove();
}
});
//P theorem
function pTheoremAB(a,b){
return ((a * a) + (b * b));
}
function pTheoremC(c){
return c * c;
}
function wDown(){
vaderY -= 2;
darthVader.style.top = vaderY + "px";
if(-pTheoremAB((vaderX - 345),(vaderY - 335)) <= -pTheoremC(radius)){
vaderY +=2
}
}
function sDown(){
vaderY += 2;
darthVader.style.top = vaderY + "px";
if(pTheoremAB((vaderX - 345),(vaderY - 335)) >= pTheoremC(radius)){
vaderY -= 2;
}
}
function aDown(){
vaderX -= 2;
darthVader.style.left = vaderX + "px";
if(-pTheoremAB((vaderX - 345),(vaderY - 335)) <= -pTheoremC(radius)){
vaderX += 2;
}
}
function dDown(){
vaderX += 2;
darthVader.style.left = vaderX + "px";
if(pTheoremAB((vaderX - 345),(vaderY - 335)) >= pTheoremC(radius)){
vaderX -= 2;
}
}
const controller = {
'w': {pressed: false},
'a': {pressed: false},
's': {pressed: false},
'd': {pressed: false},
}
document.addEventListener("keydown", (e) => {
if(controller[e.key]){
controller[e.key].pressed = true
}
if(controller['w'].pressed){
wDown();
}
if(controller['a'].pressed){
aDown();
}
if(controller['s'].pressed){
sDown();
}
if(controller['d'].pressed){
dDown();
}
})
document.addEventListener("keyup", (e) => {
if(controller[e.key]){
controller[e.key].pressed = false
}
})
body{
border: 0;
background: black;
display: flex;
align-items: center;
justify-content: center;
}
.deathStar {
position: relative;
display:flex;
height: 700px;
width: 700px;
border-radius: 50%;
background-color: darkgrey;
top: 50%;
align-items: center;
justify-content: center;
}
.hole{
display: flex;
height: 100px;
width: 50px;
border-radius: 50%;
background-color: gray;
top: 50%;
transform: translateX(-60PX);
}
.stormTrooper{
display: flex;
position: absolute;
z-index: 2;
}
.body{
display: flex;
position: relative;
height: 30px;
width: 10px;
z-index: 2;
}
.head{
display: flex;
position: absolute;
height: 7px;
width: 7px;
transform: translate(0, 1px);
background-color: black;
}
.gun{
position: absolute;
display: flex;
height: 2px;
width: 10px;
background-color: black;
transform: translate(-9px, 10px)
}
.legSplit{
position: absolute;
display: flex;
width: 1px;
height: 8px;
background-color: black;
transform: translate(4px, 22px);
}
.darthVader{
display: flex;
position: absolute;
height: 30px;
width: 10px;
z-index: 3;
background-color: black;
}
.explosion{
position: absolute;
display: flex;
height: 0px;
width: 0px;
border-radius: 50%;
background-color: red;
transform: translate(80px, 80px);
animation-duration: 1s;
animation-name: move;
}
#keyframes move {
25% {
width: 10px;
height: 10px;
}
50% {
width: 20px;
height: 20px;
}
75% {
width: 30px;
height: 30px;
}
100% {
width: 40px;
height: 40px;
}
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<link rel="stylesheet" href="style.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
</head>
<body>
<div class="deathStar" id="deathStar">
<div class="darthVader"></div>
</div>
<div class="hole"></div>
<script src="main.js"></script>
</body>
</html>
The translate positioning is relative to the Death Star element's center, so I updated that.
translate does not affect offsetTop/Left, so your "in Death Star" logic was failing. I fixed that.
Also, you do not need to adjust for the scroll position (comes into effect only when scrolled). I fixed that.
Lastly, I had to put in some code in the handler to calculate the new midpoint of the Death Star element, as you only calculated it on initialization (it should be recalcuated on every use).
//Global variables
let deathStar = document.querySelector(".deathStar")
let counter = 0;
let darthVader = document.querySelector(".darthVader");
let vaderX = darthVader.offsetLeft;
let vaderY = darthVader.offsetTop;
//Death Star information
const x1 = deathStar.getBoundingClientRect().left; // top left X
const y1 = deathStar.getBoundingClientRect().top; // top left Y
const x2 = deathStar.getBoundingClientRect().right; // bottom right X
const y2 = deathStar.getBoundingClientRect().bottom; // top right Y
let midPointX = (x2 + x1) / 2;
let midPointY = (y2 + y1) / 2;
let radius = x2 - midPointX - 10;
//Create a storm trooper
function createStormTrooper(){
colorArray = ['blue', 'green', 'orange', 'yellow', 'white', 'red','purple', 'pink'];
counter++;
//create each div
let stormTrooper = document.createElement('div');
let body = document.createElement('div');
let gun = document.createElement('div');
let head = document.createElement('div');
let legSplit = document.createElement('div');
//append div to proper div
deathStar.append(stormTrooper);
stormTrooper.append(body);
body.append(gun);
body.append(head);
body.append(legSplit);
//add classes
stormTrooper.classList.add("trooper",'stormTrooperPart' + counter, "stormTrooper");
body.classList.add("trooper", 'stormTrooperPart' + counter, "body");
gun.classList.add("trooper", 'stormTrooperPart' + counter, "gun");
head.classList.add("trooper", 'stormTrooperPart' + counter, 'head');
legSplit.classList.add("trooper", 'stormTrooperPart' + counter, "legSplit");
let randomColor = Math.floor(Math.random()*8);
body.style.backgroundColor = colorArray[randomColor];
placeInsideDeathStar(stormTrooper);
}
//Places a trooper in a random spot inside the death star
function placeInsideDeathStar(stormTrooper){
let theta = Math.random() * Math.PI * 2;
let r = (Math.sqrt(Math.random()) * radius);
let yRandom = r * Math.sin(theta);
let xRandom = r * Math.cos(theta);
stormTrooper.style.transform = "translate(" + (xRandom) + "px," + (yRandom) + "px)";
}
//Create Troopers
for(let i = 0; i < 10;i++ ){
createStormTrooper();
}
let targetFound = false;
let stormTrooper;
//Storm Trooper placing and removing
document.addEventListener('mousedown', (e) => {
//variable to check if type stormtrooper
let typeTrooper = e.target.className.split(" ")[0];
//If type storm trooper of already have a target
if(typeTrooper == "trooper" || targetFound == true){
//if no stormTrooper found yet
if(targetFound == false){
stormTrooperChecker = document.querySelector("." + e.target.className.split(" ")[1]);
targetFound = true;
}
//if stormTrooper found
else{
//Distance to move stormTrooper
const x1 = deathStar.getBoundingClientRect().left; // top left X
const y1 = deathStar.getBoundingClientRect().top; // top left Y
const x2 = deathStar.getBoundingClientRect().right; // bottom right X
const y2 = deathStar.getBoundingClientRect().bottom; // top right Y
let midPointX = (x2 + x1) / 2;
let midPointY = (y2 + y1) / 2;
var xposition = (e.clientX - midPointX);
var yposition = (e.clientY - midPointY);
//Move Storm Trooper
stormTrooperChecker.style.transform = "translate("+ (xposition)+ "px," + yposition + "px)";
//Check if outside of death star
if(pTheoremAB(yposition, xposition) > pTheoremC(radius) || pTheoremAB(yposition, xposition) < -pTheoremC(radius)){
stormTrooperChecker.classList.add("explosion")
stormTrooperChecker.innerHTML = "";
setTimeout(() => stormTrooperChecker.remove(), 1000);
}
//reset targetFound
targetFound = false;
}
//stormTrooperChecker.remove();
}
});
//P theorem
function pTheoremAB(a,b){
return ((a * a) + (b * b));
}
function pTheoremC(c){
return c * c;
}
function wDown(){
vaderY -= 2;
darthVader.style.top = vaderY + "px";
if(-pTheoremAB((vaderX - 345),(vaderY - 335)) <= -pTheoremC(radius)){
vaderY +=2
}
}
function sDown(){
vaderY += 2;
darthVader.style.top = vaderY + "px";
if(pTheoremAB((vaderX - 345),(vaderY - 335)) >= pTheoremC(radius)){
vaderY -= 2;
}
}
function aDown(){
vaderX -= 2;
darthVader.style.left = vaderX + "px";
if(-pTheoremAB((vaderX - 345),(vaderY - 335)) <= -pTheoremC(radius)){
vaderX += 2;
}
}
function dDown(){
vaderX += 2;
darthVader.style.left = vaderX + "px";
if(pTheoremAB((vaderX - 345),(vaderY - 335)) >= pTheoremC(radius)){
vaderX -= 2;
}
}
const controller = {
'w': {pressed: false},
'a': {pressed: false},
's': {pressed: false},
'd': {pressed: false},
}
document.addEventListener("keydown", (e) => {
if(controller[e.key]){
controller[e.key].pressed = true
}
if(controller['w'].pressed){
wDown();
}
if(controller['a'].pressed){
aDown();
}
if(controller['s'].pressed){
sDown();
}
if(controller['d'].pressed){
dDown();
}
})
document.addEventListener("keyup", (e) => {
if(controller[e.key]){
controller[e.key].pressed = false
}
})
body{
border: 0;
background: black;
display: flex;
align-items: center;
justify-content: center;
}
.deathStar {
position: relative;
display:flex;
height: 700px;
width: 700px;
border-radius: 50%;
background-color: darkgrey;
top: 50%;
align-items: center;
justify-content: center;
}
.hole{
display: flex;
height: 100px;
width: 50px;
border-radius: 50%;
background-color: gray;
top: 50%;
transform: translateX(-60PX);
}
.stormTrooper{
display: flex;
position: absolute;
z-index: 2;
}
.body{
display: flex;
position: relative;
height: 30px;
width: 10px;
z-index: 2;
}
.head{
display: flex;
position: absolute;
height: 7px;
width: 7px;
transform: translate(0, 1px);
background-color: black;
}
.gun{
position: absolute;
display: flex;
height: 2px;
width: 10px;
background-color: black;
transform: translate(-9px, 10px)
}
.legSplit{
position: absolute;
display: flex;
width: 1px;
height: 8px;
background-color: black;
transform: translate(4px, 22px);
}
.darthVader{
display: flex;
position: absolute;
height: 30px;
width: 10px;
z-index: 3;
background-color: black;
}
.explosion{
position: absolute;
display: flex;
height: 0px;
width: 0px;
border-radius: 50%;
background-color: red;
transform: translate(80px, 80px);
animation-duration: 1s;
animation-name: move;
}
#keyframes move {
25% {
width: 10px;
height: 10px;
}
50% {
width: 20px;
height: 20px;
}
75% {
width: 30px;
height: 30px;
}
100% {
width: 40px;
height: 40px;
}
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<link rel="stylesheet" href="style.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
</head>
<body>
<div class="deathStar" id="deathStar">
<div class="darthVader"></div>
</div>
<div class="hole"></div>
<script src="main.js"></script>
</body>
</html>

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>

JavaScript stop scrolling horizontally at the last div

Hi I am trying to create a carousel like object where you are able to click left and right to view between previous and next images using only HTML, CSS and JavaScript. Here is the code:
const container = document.querySelector(".container");
const lefty = document.querySelector(".lefty");
let translate = 0;
lefty.addEventListener("click", function() {
translate += 200;
container.style.transform = "translateX(" + translate + "px" + ")";
});
const righty = document.querySelector(".righty");
righty.addEventListener("click", function() {
translate -= 200;
container.style.transform = "translateX(" + translate + "px" + ")";
});
.outer {
overflow-x: hidden;
overflow-y: hidden;
}
.container {
display: flex;
transition: transform .4s ease-in;
}
.inner {
flex: 0 0 25%;
height: 100px;
margin: 10px;
}
.paddle {
position: absolute;
top: 50px;
bottom: 0;
width: 30px;
height: 20px;
}
.lefty {
left: 0;
z-index: 1;
}
.righty {
right: 0;
z-index: 1;
}
<button class="lefty paddle" id="left-button"></button>
<div class="outer" id="content">
<div class="container">
<div class="inner" style="background:red"></div>
<div class="inner" style="background:green"></div>
<div class="inner" style="background:blue"></div>
<div class="inner" style="background:yellow"></div>
<div class="inner" style="background:orange"></div>
</div>
</div>
<button class="righty paddle" id="right-button"></button>
The only issue I am having with this is that you can scroll way past the final div color block. Is it possible so that you can't scroll past the first and final div?
CodePen https://codepen.io/laurentkosc1990/pen/eYNXaxG
There are many approaches to solving this. In this example I define a max and min value that you can transform and check against that to stop the carousel. Either this can be fixed values or they can be dynamic to let you add and remove inner modules freely.
static
let minX = -400
let maxX = 0
dynamic
//number of inner classes times length, negate the visible classes
let minX = (inn.length * -200) + 600
const container = document.querySelector(".container");
const inn = document.getElementsByClassName('inner');
const lefty = document.querySelector(".lefty");
let translate = 0;
//let minX = -400
//number of inner classes times length, negate the visible classes
let minX = (inn.length * -200) + 600
let maxX = 0
lefty.addEventListener("click", function() {
if(translate >= maxX){
return;
}
translate += 200;
container.style.transform = "translateX(" + translate + "px" + ")";
});
const righty = document.querySelector(".righty");
righty.addEventListener("click", function() {
if(translate <= minX){
return;
}
translate -= 200;
container.style.transform = "translateX(" + translate + "px" + ")";
});
.outer {
overflow-x: hidden;
overflow-y: hidden;
}
.container {
display: flex;
transition: transform .4s ease-in;
}
.inner {
flex: 0 0 25%;
height: 100px;
margin:10px;
}
.paddle {
position: absolute;
top: 50px;
bottom: 0;
width: 30px;
height:20px;
}
.lefty {
left: 0;
z-index:1;
}
.righty{
right: 0;
z-index:1;
}
<button class="lefty paddle" id="left-button"></button>
<div class="outer" id="content">
<div class="container">
<div class="inner" style="background:red"></div>
<div class="inner" style="background:green"></div>
<div class="inner" style="background:blue"></div>
<div class="inner" style="background:yellow"></div>
<div class="inner" style="background:orange"></div>
</div>
</div>
<button class="righty paddle" id="right-button"></button>
maybe this will work for you
const container = document.querySelector(".container");
const visibleWidth = container.offsetWidth; // visible width of container
const fullWidth = container.scrollWidth; //width of container incliding hidden part
const innerDivWidth = document.querySelector(".inner").offsetWidth+20;// margin 10px from both sides
const lefty = document.querySelector(".lefty");
let translate = 0;
lefty.addEventListener("click", function() {
if(translate<0){
translate += innerDivWidth;
container.style.transform = "translateX(" + translate + "px" + ")";
}
});
const righty = document.querySelector(".righty");
righty.addEventListener("click", function() {
//here is my calculation, look carefully, you will get it
if((translate + fullWidth) > visibleWidth){
translate -= innerDivWidth;
container.style.transform = "translateX(" + translate + "px" + ")";
}
});
// btw translation rate should be according to inner div's width
// otherwise last div will not show properly
.outer {
overflow-x: hidden;
overflow-y: hidden;
}
.container {
display: flex;
transition: transform .4s ease-in;
}
.inner {
flex: 0 0 25%;
height: 100px;
margin: 10px;
}
.paddle {
position: absolute;
top: 50px;
bottom: 0;
width: 30px;
height: 20px;
}
.lefty {
left: 0;
z-index: 1;
}
.righty {
right: 0;
z-index: 1;
}
<button class="lefty paddle" id="left-button"></button>
<div class="outer" id="content">
<div class="container">
<div class="inner" style="background:red"></div>
<div class="inner" style="background:green"></div>
<div class="inner" style="background:blue"></div>
<div class="inner" style="background:yellow"></div>
<div class="inner" style="background:orange"></div>
</div>
</div>
<button class="righty paddle" id="right-button"></button>

How to get this type of effect using javascript html and css?

Actually I am trying to make this type of effect using javascript, need some help how to implement it.
View Images from here:-
https://ibb.co/2c9y9jV
https://ibb.co/Jpqk3xr
My code:
function move(e) {
console.log("mouse location:", e.clientX, e.clientY);
let x = e.clientX - 520;
let y = e.clientY - 210;
let ele = document.getElementsByClassName('after')[0];
ele.style.transform = "translate3d(" + x + "px," + y + "px,0px)"
}
var temp = false;
function toggle() {
temp = !temp;
if (temp) {
let ele = document.getElementsByClassName('after')[0];
ele.style.display = 'block';
} else {
let ele = document.getElementsByClassName('after')[0];
ele.style.display = 'none';
}
}
img {
z-index: 100;
}
.after {
position: absolute;
left: 0;
bottom: 0;
border-radius: 50%;
width: 20%;
height: 20%;
display: block;
background: white
}
.image-container {
margin: 0 auto;
position: relative;
overflow: hidden;
width: max-content;
height: max-content;
}
<button onclick="toggle()">Toggle</button>
<div class="image-container">
<img onmousemove="move(event)" src="http://lorempixel.com/300/200" />
<div class="after">
</div>
</div>
I couldn't be able to make effect like image

Html5 resizing object by dragging

I need to resize notes in my little application, but I don't know how. They have to be resized by dragging their bottom right corner and it must be done in pure java script.
Div with "+" adds new note and empty div is something like counter of all notes.
Code:
document.addEventListener("onload", Load());
var index = 0;
var cnt = 0;
var x = 0;
var y = 0;
var xx = 0;
var yy = 0;
var clicked = false;
var dragged = false;
var counter = 0;
var numberOfPapers = 0;
var state = 0;
function Load(){
var adder = document.querySelector("#add");
adder.setAttribute("onclick", "addClick()");
}
function addClick(){
cnt++;
numberOfPapers++;
document.querySelector("#counter").innerHTML = "Przebieg = " + cnt + "<br>" + "Liczba kartek = " + numberOfPapers;
var paper = document.createElement("div");
var paperX = document.createElement("div");
var paperR = document.createElement("div");
var paperS = document.createElement("div");
//papierek xD
paper.setAttribute("class", "paper");
paper.setAttribute("onmousedown", "movePaper(this,event)");
paper.setAttribute("onmouseup", "stop(this)");
paper.setAttribute("onmouseleave", "stop(this)");
paper.setAttribute("id", "id_" + cnt);
paper.style.top = "100px";
paper.style.left = "100px";
paper.style.zIndex = cnt;
//niszczyciel papierków
paperX.setAttribute("class", "deleter");
paperX.setAttribute("onclick", "deletePaper(this)");
//zmieniacz rozmiarów
paperR.setAttribute("class", "resizer");
paperR.ondragstart = function(e){
e.preventDefault();
};
paperR.setAttribute("onmousedown", "resize(this,event)");
//edytor tekstu tini emce
paperS.setAttribute("class", "txtEditor");
paperS.setAttribute("onclick", "editTxt()");
paper.appendChild(paperX);
paper.appendChild(paperR);
paper.appendChild(paperS);
document.body.appendChild(paper);
}
function stop(e){
e.setAttribute("onmousemove", null);
state = 1;
}
function resize(e,event){
state = 2;
}
function deletePaper(e){
e.parentElement.id = "del";
var del = document.querySelector("#del");
del.parentNode.removeChild(del);
numberOfPapers--;
document.querySelector("#counter").innerHTML = "Przebieg = " + cnt + "<br>" + "Liczba kartek = " + numberOfPapers;
}
function movePaper(e, event){
index++;
e.style.zIndex = index;
x = event.clientX;
y = event.clientY;
xx = e.style.left;
yy = e.style.top;
xx = xx.slice(0,xx.search("px"));
yy = yy.slice(0,yy.search("px"));
x = x - xx;
y = y - yy;
e.setAttribute("onmousemove","moreMove(this,event)");
}
function moreMove(e,event){
e.style.top = event.clientY - y + "px";
e.style.left = event.clientX - x + "px";
}
body{
margin: 0;
padding: 0;
}
#add{
position: absolute;
width: 45px;
height: 35px;
top: 25px;
right: 25px;
background-color: #F5574E;
text-align:center;
padding-top:10px;
border: solid black 1px;
}
#counter{
position: absolute;
width: 200px;
height: 45px;
top: 25px;
right: 80px;
background-color: #F5574E;
text-align:center;
border: solid black 1px;
}
.paper{
position: absolute;
width: 100px;
height: 100px;
top: 25px;
left: 25px;
background-color: #E3D67F;
border: solid black 1px;
-webkit-touch-callout: none;
-webkit-user-select: none;
-khtml-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
}
.deleter{
position: absolute;
width: 10px;
height: 10px;
top: 0px;
right: 0px;
background-color: red;
}
.resizer{
position: absolute;
width: 10px;
height: 10px;
bottom: 0px;
right: 0px;
background-color: green;
}
.txtEditor{
position: absolute;
width: 10px;
height: 10px;
top: 10px;
right: 0px;
background-color: yellow;
}
<body>
<div id="add">+
</div>
<div id="counter">
</div>
</body>
You can simply take replicate your move functions and instead of targeting top and left you target width and height of the parent node. Like this:
function resize(e, event) {
event.stopPropagation();//this to prevent move behavior to be triggered when clicking resize handle
state = 2;
index++;
e.style.zIndex = index;
x = event.clientX;
y = event.clientY;
xx = e.parentNode.style.width;
yy = e.parentNode.style.height;
xx = xx.slice(0, xx.search("px"));
yy = yy.slice(0, yy.search("px"));
x = x - xx;
y = y - yy;
e.setAttribute("onmousemove", "resizeMove(this,event)");
}
function resizeMove(e, event) {
console.log('resixe')
e.parentNode.style.height = event.clientY - y + "px";
e.parentNode.style.width = event.clientX - x + "px";
}
You'll have to declare width and height of your parentNode for it to work, you can add it to your paper section.
paper.style.width = "100px";
paper.style.height = "100px";

Categories