I am trying to make a slider from div to div but the position of the div is always wrong I don't seem to manage to code it right to fix it in the right position, I have tried floats, inline everything but nothing seems to work. so the parent class is "products" the ensemble class is "product" and each div is "product-1, product-2 etc."
Here is the whole wesite from a to z.
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html"; charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>Paritrāṇa Sari collection</title>
<script
src="jquery-3.5.1.min.js"
integrity="sha256-H+K7U5CnXl1h5ywQfKtSj8PCmoN9aaq30gDh27Xc0jk="
crossorigin="anonymous"></script>
<!-- <script src="function.js"></script> -->
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/gsap/1.20.3/TweenMax.min.js"></script>
<script src="https://code.jquery.com/jquery-3.5.1.min.js" integrity="sha256-9/aliU8dGd2tb6OSsuzixeV4y/faTqgFtohetphbbj0=" crossorigin="anonymous"></script>
<link rel="stylesheet" href="normalize.css">
<style type="text/css">
* {
margin: 0;
overflow: hidden;
-webkit-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
-o-user-select: none;
user-select: none;
font-family: sans-serif;
box-sizing: border-box;
}
/*:root {
cursor: url(model.png), auto;
}*/
/*html {zoom: 160%;}*/
body {
background-color: #e4e0dd;
}
.wrapper {
margin: 0;
padding: 0;
display: inline-block;
}
#c {
display: block;
margin: 20px auto 0;
}
#info {
position: absolute;
left: -1px;
top: -1px;
width: auto;
max-width: 420px;
height: auto;
background: #f8f8f8;
border-bottom-right-radius: 10px;
border:1px solid #ccc;
}
#top {
/*background: #fff;*/
width: 100%;
height: auto;
position: relative;
/* border-bottom: 1px solid #eee;*/
}
p {
font-family: Arial, sans-serif;
color: #666;
text-align: justify;
font-size: 16px;
margin: 0px 16px;
}
.center {
text-align: center;
}
#net {
text-align:center;
white-space:nowrap;
font-size:19px;
background:rgba(0,0,0,0.1);
padding:8px 12px;
border-radius:8px;
display:block;
color:#888;
}
.bull {
opacity: 0.3;
margin: 0 6px;
font-size: 14px;
}
.row {
display: flex;
flex-direction: row;
flex-wrap: wrap;
border-bottom: 1px solid black;
}
.column {
flex-basis: 100%;
border-right: 1px solid black;
padding-left: 5px;
}
.row_1 {
display: flex;
flex-direction: row;
flex-wrap: wrap;
}
.column_1 {
flex-basis: 100%;
}
#media screen and (min-width: 800px) {
.column {
flex: 1;
}
.column_1 {
flex: 1;
}
}
#media screen and (min-width: 800px) {
._25 {
flex: 1.5;
}
._55 {
flex: 7.5;
}
._20 {
flex: 2;
}
}
a:link {
text-decoration: none;
}
a:visited {
text-decoration: none;
color: black;
}
a:hover {
text-decoration: none;
color: white;
background: black;}
a:active {
text-decoration: none;
color: white;
background: black;
}
img {
text-align: center;
justify-content: center;
object-position: center;
top: 0;
left: 0;
width: 50%;
height: auto;
z-index: 1000;
}
.signupsubmit {
transform: rotateY(50deg) rotateX(50deg);
-webkit-transform: rotateY(50deg) rotateX(50deg);
transition: 1s;
}
.signupsubmit:hover {
-webkit-transform: rotateY(0deg) rotateX(0deg);
transform: rotateY(0deg) rotateX(0deg);
}
/*.active {
zoom: 160%;
}*/
body .cursor {
pointer-events: none;
}
body .cursor__ball {
position: fixed;
top: 0;
left: 0;
mix-blend-mode: difference;
z-index: 1000;
}
body .cursor__ball circle {
fill: #f7f8fa;
}
section {float: left;}
::selection {
background-color: rgba(0, 0, 0, 0.25);
color: white;
}
::-moz-selection {
background-color: rgba(0, 0, 0, 0.25);
color: white;
}
ol, ul {
list-style: none;
}
a {
text-decoration: none;
color: black;
}
a :hover {
z-index: 10000000;
}
.hidden {
/* display: none; */
opacity: 0;
}
/* */
.container {
position: absolute;
/* top: 50%;
left: 50%;
transform: translate(-50%, -50%);*/
/* width: 200vh;
height: 100vh;*/
/* background-color: aqua;*/
*/
overflow: hidden;
}
.products {
position: relative;
display: inline-block;
/* width: 1000%;
height: 100%;
left: 0%;
/* background-color: blueviolet;*/*/
transition: left .5s ease-in-out;
}
.product {
/* width: 70vh;
height: 100%;*/
float: left;
display: inline-block;
}
.product-1 {
/* background-color: beige;*/
}
.product-2 {
background-color: red;
}
.product-3 {
background-color: slategray;
}
.product-4 {
background-color: burlywood;
}
.buttonLeft, .buttonRight {
height: 100%;
width: 20%;
position: absolute;
background-color: red;
transition: opacity .5s ease-in-out;
top: 50px;
cursor: pointer;
z-index: 1;
}
.buttonLeft:hover, .buttonRight:hover {
opacity: 0.2;
}
.buttonLeft {
left: 0px;
cursor: w-resize;
}
.buttonRight {
right: 0px;
cursor: e-resize;
}
</style>
<script>
function imageZoom(imgID, resultID) {
var img, lens, result, cx, cy;
img = document.getElementById(imgID);
result = document.getElementById(resultID);
/*create lens:*/
lens = document.createElement("DIV");
lens.setAttribute("class", "img-zoom-lens");
/*insert lens:*/
img.parentElement.insertBefore(lens, img);
/*calculate the ratio between result DIV and lens:*/
cx = result.offsetWidth / lens.offsetWidth;
cy = result.offsetHeight / lens.offsetHeight;
/*set background properties for the result DIV:*/
result.style.backgroundImage = "url('" + img.src + "')";
result.style.backgroundSize = (img.width * cx) + "px " + (img.height * cy) + "px";
/*execute a function when someone moves the cursor over the image, or the lens:*/
lens.addEventListener("mousemove", moveLens);
img.addEventListener("mousemove", moveLens);
/*and also for touch screens:*/
lens.addEventListener("touchmove", moveLens);
img.addEventListener("touchmove", moveLens);
function moveLens(e) {
var pos, x, y;
/*prevent any other actions that may occur when moving over the image:*/
e.preventDefault();
/*get the cursor's x and y positions:*/
pos = getCursorPos(e);
/*calculate the position of the lens:*/
x = pos.x - (lens.offsetWidth / 2);
y = pos.y - (lens.offsetHeight / 2);
/*prevent the lens from being positioned outside the image:*/
if (x > img.width - lens.offsetWidth) {x = img.width - lens.offsetWidth;}
if (x < 0) {x = 0;}
if (y > img.height - lens.offsetHeight) {y = img.height - lens.offsetHeight;}
if (y < 0) {y = 0;}
/*set the position of the lens:*/
lens.style.left = x + "px";
lens.style.top = y + "px";
/*display what the lens "sees":*/
result.style.backgroundPosition = "-" + (x * cx) + "px -" + (y * cy) + "px";
}
function getCursorPos(e) {
var a, x = 0, y = 0;
e = e || window.event;
/*get the x and y positions of the image:*/
a = img.getBoundingClientRect();
/*calculate the cursor's x and y coordinates, relative to the image:*/
x = e.pageX - a.left;
y = e.pageY - a.top;
/*consider any page scrolling:*/
x = x - window.pageXOffset;
y = y - window.pageYOffset;
return {x : x, y : y};
}
}
</script>
</head>
<body>
<!-- cursor -->
<div class="cursor">
<div class="cursor__ball cursor__ball--big">
<svg height="60" width="60">
<circle cx="15" cy="15" r="16" stroke-width="0"></circle>
</svg>
</div>
<!-- small ball cursor -->
<div class="cursor__ball cursor__ball--small">
<svg height="10" width="10">
<circle cx="5" cy="5" r="4" stroke-width="0"></circle>
</svg>
</div>
</div>
<!-- cursor end -->
<!-- navigation -->
<nav>
<div class="row" style="background-color:white;">
<div class="column">
Paritrāṇa Sari collection
</div>
<div class="column">
Concept
</div>
<div class="column">
Process
</div>
</div>
<div class="row" style="background-color:white;">
<div class="column">
Red sari N°1
</div>
<div class="column">
Orange sari N°2
</div>
<div class="column">
Saffron sari N°3
</div>
<div class="column">
Yellow sari N°4
</div>
<div class="column">
Turmeric sari N°5
</div>
<div class="column">
Green sari N°6
</div>
<div class="column">
Blue sari N°7
</div>
<div class="column">
Pink sari N°8
</div>
<div class="column">
Black sari N°9
</div>
<div class="column">
White sariN°10
</div>
<div class="column">
Violet sari N°11
</div>
</div>
</nav>
<!-- navigation end -->
<!-- wrapper slider -->
<section class="container">
<div class="products">
<div class="wrapper product product-1">
<img src="./img.png" style="margin-top: -2000px; position: absolute;" />
<canvas
width="1900"
height="300"
style="margin-top: -2000px; position: absolute;"
></canvas>
<div class="row_1">
<!-- <div style="overflow:auto"> -->
<div class="column _25" style="overflow-y: auto;">
Project photoshoot
<div id="img1" class="signupsubmit" style="width:100%;">
<img src="model.png" />
</div>
<div id="img1" class="signupsubmit" style="width:100%;">
<img src="model.png" />
</div>
<div id="img1" class="signupsubmit" style="width:100%;">
<img src="model.png" />
</div>
<div class="signupsubmit" style="width:100%;">
<img src="model.png" />
</div>
<div class="signupsubmit" style="width:100%;">
<img src="model.png" />
</div>
</div>
<div class="column _55">
<canvas id="c" width="800" height="376"> </canvas>
<div class="row_1">
<div class="column_1">
<div id="top">
<a id="close" href="">Reset tissue —</a>
</div>
</div>
<div class="column_1">
<div>
<p>This project is based on the red celebratory color………</p>
</div>
</div>
<div class="column_1">
<div style="background-color:red;height: 50px;width: 50px;"></div>
</div>
</div>
<div
class="column _20 signupsubmit"
style="border-top: 1px solid black;border-right: 0px;"
>
Red is a celebratory color. It commemorates a couple’s union. It
symbolizes love, sensuality, and passion. That’s why it features
prominently in auspicious occasions, such as weddings, festivals, and
births. As red also signifies chastity, it is the color of choice for
brides. After the wedding ceremony, the bride adopts a red spot on the
forehead called “bindi,” which cements her marital status. When she
dies, her family wraps her in red fabric for cremation. As red also
depicts dominance, it empowers the saree wearer and draws attention
toward her. It’s no surprise that extroverts and A-type personalities
prefer red. Pairing a red saree with a gold top amplifies the look. To
tone it down, use a silver blouse instead. Accessorize with silver or
gold jewelry. Red is associated with Durga, a Hindu goddess with a red
tongue, red eyes, and a blazing image. That’s why devotees use it
extensively in prayer rituals. Worshippers throw red powder on
deities’ statues during prayer ceremonies and phallic symbols because
red is the color of Kshatriya, the warrior caste. Designers dress
charitable, brave, and protective deities in red. Red also symbolizes
fertility and prosperity because it is the color of the clay that
produces spices and harvests, which in turn, improve lives.
</div>
</div>
</div>
</div>
<div class="wrapper product product-2" style="float: left;display: inline;clear: both;top: 0;position: absolute;">
<img src="./img2.png" style="margin-top: -2000px; position: absolute;" />
<canvas
width="1900"
height="300"
style="margin-top: -2000px; position: absolute;"
></canvas>
<div class="row_1">
<!-- <div style="overflow:auto"> -->
<div class="column _25" style="overflow-y: auto;">
Project photoshoot
<div id="img1" class="signupsubmit" style="width:100%;">
<img src="model.png" />
</div>
<div id="img1" class="signupsubmit" style="width:100%;">
<img src="model.png" />
</div>
<div id="img1" class="signupsubmit" style="width:100%;">
<img src="model.png" />
</div>
<div class="signupsubmit" style="width:100%;">
<img src="model.png" />
</div>
<div class="signupsubmit" style="width:100%;">
<img src="model.png" />
</div>
</div>
<div class="column _55">
<canvas id="c" width="800" height="376"> </canvas>
<div class="row_1">
<div class="column_1">
<div id="top">
<a id="close" href="">Reset tissue —</a>
</div>
</div>
<div class="column_1">
<div>
<p>This project is based on the red celebratory color………</p>
</div>
</div>
<div class="column_1">
<div style="background-color:red;height: 50px;width: 50px;"></div>
</div>
</div>
<div
class="column _20 signupsubmit"
style="border-top: 1px solid black;border-right: 0px;"
>
Orange attracts attention and energy like the color red, except it’s more sedate. It signifies freshness and brightness. Not all skin tones can carry this color, but for those whose complexions can pull it off in their clothing, it helps put them in a sunny disposition.
According to CNN’s Colorscope report, a series exploring color perception across cultures, many Eastern religions consider orange a sacred color. In Hinduism, orange represents fire and virtuosity. That’s why their monks wear orange robes. Buddhist ones too.
</div>
</div>
</div>
</div>
</div>
<div class="hidden buttonLeft"></div>
<div class="hidden buttonRight"></div>
</section>
<!-- wrapper slider end -->
<!-- footer -->
<footer
style="position: fixed;bottom: 0;width: 100%;background-color: white;border-top:1px solid black;"
>
<div class="row">
<div class="column">©Copyright Angelo Barbattini</div>
<div class="column">ECAL 2022</div>
</div>
</footer>
<!-- footer end -->
<script type="text/javascript">
window.onload = function() {
}
var offsetProducts = 0;
var numberProducts = 2; //nombre de project -1, car on commence à compter à partir de 0
$(document).ready(function() {
console.log("ready!");
// $(".buttonLeft").on("click", function() {
// console.log(offsetProducts);
// if (offsetProducts > numberProducts * -100) offsetProducts = offsetProducts - 100;
// $(".products").css("left", offsetProducts + "%");
// });
// $(".buttonRight").on("click", function() {
// console.log("right Click");
// if (offsetProducts < 0) offsetProducts = offsetProducts + 100;
// $(".products").css("left", offsetProducts + "%");
// });
$(".buttonLeft").on("click", function() {
console.log(offsetProducts);
if (offsetProducts < 0) offsetProducts = offsetProducts + 100;
$(".products").css("left", offsetProducts + "%");
});
$(".buttonRight").on("click", function() {
console.log("right Click");
if (offsetProducts > numberProducts * -100) offsetProducts = offsetProducts - 100;
$(".products").css("left", offsetProducts + "%");
});
});
</script>
<script type="text/javascript">
const mycanvas = document.querySelector('canvas');
const mycontext = mycanvas.getContext('2d');
// settings
var physics_accuracy = 20,
mouse_influence = 10,
mouse_cut = 6,
gravity = 1200,
cloth_height = 40,
cloth_width = 120,
start_y = 10,
spacing = 7,
tear_distance = 60;
window.requestAnimFrame =
window.requestAnimationFrame ||
window.webkitRequestAnimationFrame ||
window.mozRequestAnimationFrame ||
window.oRequestAnimationFrame ||
window.msRequestAnimationFrame ||
function(callback) {
window.setTimeout(callback, 1000 / 60);
};
var canvas,
ctx,
cloth,
boundsx,
boundsy,
mouse = {
down: false,
button: 1,
x: 0,
y: 0,
px: 0,
py: 0
};
window.onload = function() {
// ADDED TO BRING IN THE IMAGE
mycontext.clearRect(0, 0, mycanvas.width, mycanvas.height);
mycontext.drawImage(document.querySelector('img'), 0, 0, 1180, 376);
canvas = document.getElementById('c');
ctx = canvas.getContext('2d');
canvas.width = canvas.clientWidth;
canvas.height = 376;
canvas.onmousedown = function(e) {
mouse.button = e.which;
mouse.px = mouse.x;
mouse.py = mouse.y;
var rect = canvas.getBoundingClientRect();
mouse.x = e.clientX - rect.left,
mouse.y = e.clientY - rect.top,
mouse.down = true;
e.preventDefault();
};
canvas.onmouseup = function(e) {
mouse.down = false;
e.preventDefault();
};
canvas.onmousemove = function(e) {
mouse.px = mouse.x;
mouse.py = mouse.y;
var rect = canvas.getBoundingClientRect();
mouse.x = e.clientX - rect.left,
mouse.y = e.clientY - rect.top,
e.preventDefault();
};
canvas.oncontextmenu = function(e) {
e.preventDefault();
};
boundsx = canvas.width - 1;
boundsy = canvas.height - 1;
ctx.strokeStyle = 'rgba(222,222,222,0.6)';
ctx.strokeStyle = 'magenta';
cloth = new Cloth();
update();
};
var Point = function(x, y) {
this.x = x;
this.y = y;
this.px = x;
this.py = y;
this.vx = 0;
this.vy = 0;
this.pin_x = null;
this.pin_y = null;
this.constraints = [];
//added - remember where this point was originally so we can get the right bit of the img
this.origx = x;
this.origy = y;
};
Point.prototype.update = function(delta) {
if (mouse.down) {
var diff_x = this.x - mouse.x,
diff_y = this.y - mouse.y,
dist = Math.sqrt(diff_x * diff_x + diff_y * diff_y);
if (mouse.button == 1) {
if (dist < mouse_influence) {
this.px = this.x - (mouse.x - mouse.px) * 1.8;
this.py = this.y - (mouse.y - mouse.py) * 1.8;
}
} else if (dist < mouse_cut) this.constraints = [];
}
this.add_force(0, gravity);
delta *= delta;
nx = this.x + ((this.x - this.px) * .99) + ((this.vx / 2) * delta);
ny = this.y + ((this.y - this.py) * .99) + ((this.vy / 2) * delta);
this.px = this.x;
this.py = this.y;
this.x = nx;
this.y = ny;
this.vy = this.vx = 0
};
Point.prototype.draw = function() {
if (this.constraints.length <= 0) return;
var i = this.constraints.length;
while (i--) this.constraints[i].draw();
};
Point.prototype.resolve_constraints = function() {
if (this.pin_x != null && this.pin_y != null) {
this.x = this.pin_x;
this.y = this.pin_y;
return;
}
var i = this.constraints.length;
while (i--) this.constraints[i].resolve();
this.x > boundsx ? this.x = 2 * boundsx - this.x : 1 > this.x && (this.x = 2 - this.x);
this.y < 1 ? this.y = 2 - this.y : this.y > boundsy && (this.y = 2 * boundsy - this.y);
};
Point.prototype.attach = function(point) {
this.constraints.push(
new Constraint(this, point)
);
};
Point.prototype.remove_constraint = function(lnk) {
var i = this.constraints.length;
while (i--)
if (this.constraints[i] == lnk) this.constraints.splice(i, 1);
};
Point.prototype.add_force = function(x, y) {
this.vx += x;
this.vy += y;
};
Point.prototype.pin = function(pinx, piny) {
this.pin_x = pinx;
this.pin_y = piny;
};
var Constraint = function(p1, p2) {
this.p1 = p1;
this.p2 = p2;
this.length = spacing;
};
Constraint.prototype.resolve = function() {
var diff_x = this.p1.x - this.p2.x,
diff_y = this.p1.y - this.p2.y,
dist = Math.sqrt(diff_x * diff_x + diff_y * diff_y),
diff = (this.length - dist) / dist;
if (dist > tear_distance) this.p1.remove_constraint(this);
var px = diff_x * diff * 0.7;
var py = diff_y * diff * 0.5;
this.p1.x += px;
this.p1.y += py;
this.p2.x -= px;
this.p2.y -= py;
};
let num = 0;
Constraint.prototype.draw = function() {
ctx.drawImage(mycanvas, this.p1.origx, this.p1.origy, spacing, spacing, this.p1.x, this.p1.y, spacing + 1, spacing + 1);
};
var Cloth = function() {
this.points = [];
var start_x = canvas.width / 2 - cloth_width * spacing / 2;
// alert(start_x);
for (var y = 0; y <= cloth_height; y++) {
for (var x = 0; x <= cloth_width; x++) {
var p = new Point(start_x + x * spacing, start_y + y * spacing);
x != 0 && p.attach(this.points[this.points.length - 1]);
y == 0 && p.pin(p.x, p.y);
y != 0 && p.attach(this.points[x + (y - 1) * (cloth_width + 1)])
this.points.push(p);
}
}
};
Cloth.prototype.update = function() {
var i = physics_accuracy;
while (i--) {
var p = this.points.length;
while (p--) this.points[p].resolve_constraints();
}
i = this.points.length;
while (i--) this.points[i].update(.016);
};
Cloth.prototype.draw = function() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.beginPath();
var i = cloth.points.length;
while (i--) cloth.points[i].draw();
ctx.stroke();
};
function update() {
cloth.update();
cloth.draw();
requestAnimFrame(update);
}
</script>
<script>
imageZoom("myimage", "myresult");
</script>
<!-- <script type="text/javascript"> document.body.onclick = function () {document.body.style.zoom="150%"}</script>
--> <script type="text/javascript"> $('#myButton').click(function() { document.body.style.zoom="160%" });</script>
<script type="text/javascript">$(function(){
$('h3').click(function(){
$('h3.active').removeClass('active');
$(this).addClass('active');
});
});</script>
<script type="text/javascript">const $bigBall = document.querySelector(".cursor__ball--big");
const $smallBall = document.querySelector(".cursor__ball--small");
const $hoverables = document.querySelectorAll(".hoverable");
// Listeners
document.body.addEventListener("mousemove", onMouseMove);
for (let i = 0; i < $hoverables.length; i++) {
$hoverables[i].addEventListener("mouseenter", onMouseHover);
$hoverables[i].addEventListener("mouseleave", onMouseHoverOut);
}
// Move the cursor
function onMouseMove(e) {
TweenMax.to($bigBall, 0.4, {
x: e.pageX - 15,
y: e.pageY - 15
});
TweenMax.to($smallBall, 0.1, {
x: e.pageX - 5,
y: e.pageY - 7
});
}
// Hover an element
function onMouseHover() {
TweenMax.to($bigBall, 0.3, {
scale: 4
});
}
function onMouseHoverOut() {
TweenMax.to($bigBall, 0.3, {
scale: 1
});
}</script>
<script>
// Get the img object using its Id
img = document.getElementById("img1");
// Function to increase image size
function enlargeImg() {
// Set image size to 1.5 times original
img.style.transform = "scale(1.5)";
// Animation effect
img.style.transition = "transform 0.25s ease";
}
// Function to reset image size
function resetImg() {
// Set image size to original
img.style.transform = "scale(1)";
img.style.transition = "transform 0.25s ease";
}
</script>
</script>
</body>
</html>```
Try to set the div style to display flex like this:
div {
display: flex;
flex: 1
///
}
I'm trying to offset the element containing the image which has 21 frames. 0 - 21. I've placed 21 vertical columns over the image to visualize which frame should be present when the user's cursor is within the column lines. So each time your cursor moves into a different column of the grid, it should display a new frame. I need help figuring out whey the last frame (20) only shows when the user's cursor is on the very last pixel to the far right of the frame?
All the work is done in the javascript. I've commented each step and print to the console useful information regarding the math.
https://jsfiddle.net/JokerMartini/2e9awc4u/67/
window.onload = function() {
console.log('go')
$("#viewport").mousemove(function(e) {
// step 0: value to offset each frame (without scale)
const frameWidth = 320
// step 1: get the current mouse position in relation to the current element
const x = e.offsetX
// step 3: get width of viewable content, subtract 1 pixel starts at 0px
const viewWidth = $("#viewport").width() - 1
// step 4: find the % of the current position (in decimals 0-1.0)
const percent = x / viewWidth
// step 5: find the frame by the current percentage
const filmstripWidth = $("#filmstrip").width()
const frameByPercent = Math.round((filmstripWidth - frameWidth) * percent)
// step 6: find the nearest multiplier to frameWidth to offset
const offset = Math.floor(frameByPercent / frameWidth) * frameWidth
// const offset = -frameByPercent // smooth
// step 7: set that as the current position in negative (for offset reasons)
$("#filmstrip").css('transform', 'translate(' + -offset + 'px)')
console.log(
'CURSOR:', x,
'VIEW:', viewWidth,
'PERCENT:', percent,
'IMAGE WIDTH:', filmstripWidth,
frameByPercent
)
});
};
html {
height: 100%;
width: 100%;
}
#filmstrip {
will-change: transform;
pointer-events:none;
}
#margin-center {
background: grey;
padding: 30px
}
#viewport {
height: 180px;
width: 320px;
background: #FFFFAA;
display: block;
margin: auto;
position: relative;
overflow: hidden; /* Comment for debugging */
}
#guides {
position: absolute;
top: 0;
left: 0;
pointer-events:none;
}
#content {
display: inline-block;
font-size: 0;
height: auto;
max-width: 400px;
width: 100%;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="content">
<div id="margin-center">
<div id='viewport'>
<img id='filmstrip' src="https://i.ibb.co/7XDpcnd/timer.jpg" width="auto" height="180">
<svg id="guides" width="320px" height="180px">
<defs>
<pattern id="grid" width="15.238" height="180" patternUnits="userSpaceOnUse">
<path d="M 16 0 L 0 0 0 180" fill="none" stroke="black" stroke-width="1" />
</pattern>
</defs>
<rect width="100%" height="100%" fill="url(#grid)" />
</svg>
</div>
</div>
</div>
Your results are offset by 1 because you deducted one full frameWidth.
Added code to cap percent at 0.999, to prevent it jumping to 22nd frame. mousemove positions will sometimes be at end position or greater.
window.onload = function() {
console.log('go')
$("#viewport").mousemove(function(e) {
// step 0: value to offset each frame (without scale)
const frameWidth = 320
// step 1: get the current mouse position in relation to the current element
const x = e.offsetX
// step 3: get width of viewable content, subtract 1 pixel starts at 0px
const viewWidth = $("#viewport").width() - 1
// step 4: find the % of the current position (in decimals 0-1.0)
const percent = x / viewWidth
// step 5: find the frame by the current percentage
const filmstripWidth = $("#filmstrip").width()
const frameByPercent = Math.round((filmstripWidth) * Math.min(percent,0.999))
// step 6: find the nearest multiplier to frameWidth to offset
const offset = Math.floor(frameByPercent / frameWidth) * frameWidth
// const offset = -frameByPercent // smooth
// step 7: set that as the current position in negative (for offset reasons)
$("#filmstrip").css('transform', 'translate(' + -offset + 'px)')
console.log(
'CURSOR:', x,
'VIEW:', viewWidth,
'PERCENT:', percent,
'IMAGE WIDTH:', filmstripWidth,
frameByPercent
)
});
};
html {
height: 100%;
width: 100%;
}
#filmstrip {
will-change: transform;
pointer-events:none;
}
#margin-center {
background: grey;
padding: 30px
}
#viewport {
height: 180px;
width: 320px;
background: #FFFFAA;
display: block;
margin: auto;
position: relative;
overflow: hidden; /* Comment for debugging */
}
#guides {
position: absolute;
top: 0;
left: 0;
pointer-events:none;
}
#content {
display: inline-block;
font-size: 0;
height: auto;
max-width: 400px;
width: 100%;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="content">
<div id="margin-center">
<div id='viewport'>
<img id='filmstrip' src="https://i.ibb.co/7XDpcnd/timer.jpg" width="auto" height="180">
<svg id="guides" width="320px" height="180px">
<defs>
<pattern id="grid" width="15.238" height="180" patternUnits="userSpaceOnUse">
<path d="M 16 0 L 0 0 0 180" fill="none" stroke="black" stroke-width="1" />
</pattern>
</defs>
<rect width="100%" height="100%" fill="url(#grid)" />
</svg>
</div>
</div>
</div>
I am trying to zoom into those objects using a slider. Unfortunately, the bigger the distance from the nearest to deepest object, the faster the slide happens. How can control this behaviour so that the slide appears smooth?
What I tried: debouncing the handler and giving the circles a transition.
Here is a snippet:
const input = document.querySelector("input");
const circles = document.querySelectorAll(".circle");
let firstDepth = 9300;
let secondDepth = 100;
let thirdDepth = 2;
const initialSize = 0.0001;
circles[0].style.transform = "scale(" + (firstDepth * initialSize) + ")";
circles[1].style.transform = "scale(" + (secondDepth * initialSize) + ")";
circles[2].style.transform = "scale(" + (thirdDepth * initialSize) + ")";
input.addEventListener("input", function() {
//console.log(1)
circles[0].style.transform = "scale(" + firstDepth * input.value + ")";
circles[1].style.transform = "scale(" + secondDepth * input.value + ")";
circles[2].style.transform = "scale(" + thirdDepth * input.value + ")";
})
.circle {
width: 100px;
height: 100px;
position: absolute;
left: 0;
right: 0;
bottom: 0;
top: 0;
margin: auto;
border-radius: 100%;
}
.first:nth-of-type(1) {
border: 2px solid red;
}
.second:nth-of-type(2) {
border: 2px solid orange;
}
.third:nth-of-type(3) {
border: 2px solid green;
}
<input type="range" value="0.0001" step="any" min="0.0001" max="1">
<div class="circle first"></div>
<div class="circle second"></div>
<div class="circle third"></div>
You would want an effect where an increase of the slide value with d would multiply the scale with some m, so that if you slide with 2d, you get a relative scaling with m2.
So, ... you need a transformation of input.value where that value appears in an exponent. In other words: the scale should increase exponentially in terms of the value of the slider.
Given that you want to see the first circle completely when the slider is at the left (scaling with initialSize) and the third circle completely when the slider is at the right, you can derive the following formula for that transformation:
initialSize * (firstDepth / thirdDepth) ** (input.value - initialSize);
Here is the code adapted to that:
const input = document.querySelector("input");
const circles = document.querySelectorAll(".circle");
let firstDepth = 9300;
let secondDepth = 100;
let thirdDepth = 2;
const initialSize = 0.0001;
circles[0].style.transform = "scale(" + (firstDepth * initialSize) + ")";
circles[1].style.transform = "scale(" + (secondDepth * initialSize) + ")";
circles[2].style.transform = "scale(" + (thirdDepth * initialSize) + ")";
input.addEventListener("input", function() {
let coeff = initialSize * (firstDepth / thirdDepth) ** (input.value - initialSize);
circles[0].style.transform = "scale(" + firstDepth * coeff + ")";
circles[1].style.transform = "scale(" + secondDepth * coeff + ")";
circles[2].style.transform = "scale(" + thirdDepth * coeff + ")";
})
.circle {
width: 100px;
height: 100px;
position: absolute;
left: 0;
right: 0;
bottom: 0;
top: 0;
margin: auto;
border-radius: 100%;
}
.first:nth-of-type(1) {
border: 2px solid red;
}
.second:nth-of-type(2) {
border: 2px solid orange;
}
.third:nth-of-type(3) {
border: 2px solid green;
}
<input type="range" value="0.0001" step="any" min="0.0001" max="1">
<div class="circle first"></div>
<div class="circle second"></div>
<div class="circle third"></div>
My code is forking this pen, I also include my code in the stack snippet under this post.
what I want to achieve are:
When the cursor is not inside the body, the eyeball would move randomly ( achieved ).
When the cursor enters the body, the eyeball follows the cursor ( achieved ).
When the cursor leaves the body, the eyeball starts moving randomly again ( not achieved ).
I called the function which is used to move the eyeball randomly in on("mouseleave") event, and it does move to a random position but it will immediately go back to the last cursor position, rather than staying at the new position. Can anyone point me to the right direction to fix the problem?
Thanks!
var
mouseOvering = false,
pupil = $("#pupil"),
eyeball = $("#iris"),
eyeposx = 40,
eyeposy = 20,
r = $(pupil).width()/2,
center = {
x: $(eyeball).width()/2 - r,
y: $(eyeball).height()/2 - r
},
distanceThreshold = $(eyeball).width()/2 - r,
mouseX = 0,
mouseY = 0;
$("body").ready( function(){
if ( !mouseOvering ) {
moveRandomly();
}
});
$("body").on('mouseleave', function(){
mouseOvering = false;
moveRandomly();
console.log("mouseleave");
});
$("body").on('mousemove', function(e){
mouseOvering = true;
console.log("mouseovering");
followCursor(e);
});
function moveRandomly() {
var loop = setInterval(function(){
var xp = Math.floor(Math.random()*80);
var yp = Math.floor(Math.random()*80);
pupil.animate({left:xp, top:yp});
}, 3500);
}
function followCursor(e) {
var d = {
x: e.pageX - r - eyeposx - center.x,
y: e.pageY - r - eyeposy - center.y
};
var distance = Math.sqrt(d.x*d.x + d.y*d.y);
if (distance < distanceThreshold) {
mouseX = e.pageX - eyeposx - r;
mouseY = e.pageY - eyeposy - r;
} else {
mouseX = d.x / distance * distanceThreshold + center.x;
mouseY = d.y / distance * distanceThreshold + center.y;
}
var xp = 0, yp = 0;
var loop = setInterval(function(){
// change 1 to alter damping/momentum - higher is slower
xp += (mouseX - xp) / 1;
yp += (mouseY - yp) / 1;
pupil.css({left:xp, top:yp});
}, 2);
}
body {
background-color: #D1D3CF;
}
#container {
display: inline;
height: 400px;
width: 400px;
}
#eyeball {
background: radial-gradient(circle at 100px 100px, #EEEEEE, #000);
height: 300px;
width: 300px;
border-radius: 100%;
position: relative;
}
#iris {
top: 10%;
left: 10%;
background: radial-gradient(circle at 100px 100px, #4DC9EF, #000);
height: 80%;
width: 80%;
border-radius: 100%;
position: absolute;
}
#pupil {
top: 10%;
left: 10%;
background: radial-gradient(circle at 100px 100px, #000000, #000);
height: 55%;
width: 55%;
border-radius: 100%;
position: absolute;
}
#keyframes move {
50% {
transform: translate(-50px, 50px);
}
}
#keyframes move2 {
50% {
transform: translate(-20px, 20px);
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<link rel="stylesheet" href="style.css">
</head>
<body>
<div id="container">
<div id="eyeball">
<div id="iris">
<div id="pupil"></div>
</div>
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="script.js"></script>
</body>
</html>
With Javascript you can only track where the cursor is on the webpage. If you shift your cursor outside the body, it's not possible for your code to know where the cursor is.
This is the reason the eye tracking your cursor stops moving when you move your cursor outside the window.
The problem is that once the followcursor function was started it kept on moving back to the last known mouse position, even after the mouse had left the body. I just put a check on your mouseOvering variable inside your followcursor function:
var
mouseOvering = false,
pupil = $("#pupil"),
eyeball = $("#iris"),
eyeposx = 40,
eyeposy = 20,
r = $(pupil).width()/2,
center = {
x: $(eyeball).width()/2 - r,
y: $(eyeball).height()/2 - r
},
distanceThreshold = $(eyeball).width()/2 - r,
mouseX = 0,
mouseY = 0;
$("body").ready( function(){
if ( !mouseOvering ) {
moveRandomly();
}
});
$("body").on('mouseleave', function(){
mouseOvering = false;
console.log("mouseleave");
});
$("body").on('mousemove', function(e){
mouseOvering = true;
console.log("mouseovering");
followCursor(e);
});
function moveRandomly() {
var loop = setInterval(function(){
var xp = Math.floor(Math.random()*80);
var yp = Math.floor(Math.random()*80);
if (!mouseOvering) {
pupil.animate({left:xp, top:yp});
}
}, 3500);
}
function followCursor(e) {
var d = {
x: e.pageX - r - eyeposx - center.x,
y: e.pageY - r - eyeposy - center.y
};
var distance = Math.sqrt(d.x*d.x + d.y*d.y);
if (distance < distanceThreshold) {
mouseX = e.pageX - eyeposx - r;
mouseY = e.pageY - eyeposy - r;
} else {
mouseX = d.x / distance * distanceThreshold + center.x;
mouseY = d.y / distance * distanceThreshold + center.y;
}
var xp = 0, yp = 0;
var loop = setInterval(function(){
// change 1 to alter damping/momentum - higher is slower
xp += (mouseX - xp) / 1;
yp += (mouseY - yp) / 1;
if (mouseOvering) {
pupil.css({left:xp, top:yp});
}
}, 2);
}
body {
background-color: #D1D3CF;
}
#container {
display: inline;
height: 400px;
width: 400px;
}
#eyeball {
background: radial-gradient(circle at 100px 100px, #EEEEEE, #000);
height: 300px;
width: 300px;
border-radius: 100%;
position: relative;
}
#iris {
top: 10%;
left: 10%;
background: radial-gradient(circle at 100px 100px, #4DC9EF, #000);
height: 80%;
width: 80%;
border-radius: 100%;
position: absolute;
}
#pupil {
top: 10%;
left: 10%;
background: radial-gradient(circle at 100px 100px, #000000, #000);
height: 55%;
width: 55%;
border-radius: 100%;
position: absolute;
}
#keyframes move {
50% {
transform: translate(-50px, 50px);
}
}
#keyframes move2 {
50% {
transform: translate(-20px, 20px);
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<link rel="stylesheet" href="style.css">
</head>
<body>
<div id="container">
<div id="eyeball">
<div id="iris">
<div id="pupil"></div>
</div>
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="script.js"></script>
</body>
</html>
These are my javascript, css, and html files for simple web page for dragging an element and putting it into the container(div) :
var xContainer;
var yContainer
var insideFirst = false;
$(window).load(
function() {
xContainer = $("#center").offset().left;
yContainer = $("#center").offset().top;
console.log("ready");
$("#center").on("click", function(event) {
console.log(event);
});
$("#center").droppable();
$("#firstID").draggable({
cursor : 'move',
revert: "invalid"
});
$("#firstID").mousedown(function() {
isDragging = false;
}).mousemove(
function() {
isDragging = true;
var x = $("#firstID").offset().left;
var y = $("#firstID").offset().top;
xContainer = $("#center").offset().left;
yContainer = $("#center").offset().top;
var xPosition = (x - xContainer).toFixed(2);
var yPosition = (y - yContainer).toFixed(2);
console.log("center:" + xContainer);
console.log("x:" + x);
console.log("difference: "+(x-xContainer));
/*
* if (x < 750 && y < 750) {
* $("#firstID").css('background','#ffffff') }
*/
if (xPosition >= 0.0 && yPosition >= 0.0
&& xPosition <= 500.0 && yPosition <= 200.0) {
$("#xPosition").val("x:" + xPosition);
$("#yPosition").val("y:" + yPosition);
$("#firstID").css('background', '#e4e4e4')
$('#firstID').draggable({containment : [xContainer,yContainer,xContainer+500,yContainer+200.0] });
} else {
//$("#xPosition").val("GO IN!!!");
//$("#yPosition").val("GO IN!!!");
$("#firstID").css('background', '#d1f1fc')
}
}).mouseup(function() {
var wasDragging = isDragging;
isDragging = false;
if (!wasDragging) {
console.log("clicked");
}
});
$("#secondID").draggable({
cursor : 'move'
});
$("#secondID").mousedown(function() {
isDragging = false;
}).mousemove(function() {
isDragging = true;
var x = $("#secondID").offset().left;
var y = $("#secondID").offset().top;
// $("#text-x").val ("x:"+x);
// $("#text-y").val ("y:"+y);
}).mouseup(function() {
var wasDragging = isDragging;
isDragging = false;
if (!wasDragging) {
console.log("clicked");
}
});
$("#secondID").dblclick(function() {
rotation += 90;
$(this).rotate(rotation);
});
});
jQuery.fn.rotate = function(degrees) {
$(this).css({
'-webkit-transform' : 'rotate(' + degrees + 'deg)',
'-moz-transform' : 'rotate(' + degrees + 'deg)',
'-ms-transform' : 'rotate(' + degrees + 'deg)',
'transform' : 'rotate(' + degrees + 'deg)'
});
return $(this);
};
var rotation = 0;
var isDragging = false;
body {
height: 100%;
background-color: #e4e4e4;
}
#firstID {
width: 100px;
height: 100px;
margin: 0 auto;
border-style: groove;
background-color: #d1f1fc;
color: black;
position: relative;
text-align: center;
z-index: 99;
}
#secondID {
width: 100px;
height: 50px;
margin: 0 auto;
color: black;
border-style: groove;
position: relative;
background-color: #d1f1fc;
text-align: center;
z-index: 99;
}
#center {
width: 600px;
height: 300px;
position: relative;
margin: 0 auto;
border-style: groove;
background-color: #c0c0c0;
}
/* If in mobile screen with maximum width 479px. The iPhone screen resolution is 320x480 px (except iPhone4, 640x960) */
#media only screen and (max-width: 479px) {
#center{
width: 50%;
height : 50%;
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script src="http://code.jquery.com/ui/1.9.2/jquery-ui.js"></script>
<html>
<head>
<link rel="stylesheet" type="text/css" href="drag.css">
</head>
<body>
<input type="text" id="xPosition" value="x:0">
<input type="text" id="yPosition" value="y:0">
<div id="firstID" >MJ</div>
<div id="secondID" >MJ</div>
<div id="center">
</div>
</body>
</html>
The code is not finished, so the logic works with only a square, not rectangle.
What i need is to drag square element into the container on the page and make it stay inside it, with no possibility to leave it. That works fine in Mozilla, but in Chrome, i have problems with dragging the square after entering container. When i click on it and try to drag it, it moves far to the right side of the page. Why is that happening only in Chrome?