Before/After slider HTML5 starting position - javascript

I've recently came across this before/after slider on codepen.io.
But I have a question: how can I change the position where the slider starts. The slider starts int he middle, and I don't see where in this code that is set:
function trackLocation(e) {
var rect = videoContainer.getBoundingClientRect(),
position = ((e.pageX - rect.left) / videoContainer.offsetWidth)*100;
if (position <= 100) {
videoClipper.style.width = position+"%";
clippedVideo.style.width = ((100/position)*100)+"%";
clippedVideo.style.zIndex = 3;
}
}
var videoContainer = document.getElementById("video-compare-container"),
videoClipper = document.getElementById("video-clipper"),
clippedVideo = videoClipper.getElementsByTagName("video")[0];
videoContainer.addEventListener( "mousemove", trackLocation, false);
videoContainer.addEventListener("touchstart",trackLocation,false);
videoContainer.addEventListener("touchmove",trackLocation,false);

on the bottom of the css
#video-clipper video {
width: 450%;
postion: absolute;
height: 100%;
}
https://codepen.io/anon/pen/jwMwXB

Related

Making a box move smoothly and slowly to a set position in JavaScript

<html>
<div id="my_box_realtime" style="background-color: red; position: absolute; min-width: 100px; min-height: 100px"></div>
<script type="text/javascript">
var x = bottom
var y = right
var d = document.getElementById('my_box_realtime');
var position = 0;
setInterval(function() {}, 500)
position += 1;
d.style.top = position + 'px';
d.style.left = position + 'px';
function my_box_realtime() {
if (position)
}
</script>
</html>
The box needs to move smoothly and slowly to a set coordinate of bottom 0 and right 0.
Any help would be great. Very new to this and it's an assignment I have.
For your problem, we need to:
maintain top & left values separately
Check on Every Interval if the Boxes Bottom & Right have reached the Target Distance in relation to the window
Update the Top & Left Values if necessary
Finally, when the Box is at the Target Location, Clear the Interval.
var d = document.getElementById('my_box_realtime');
var x = 0; // Bottom Target in px
var y = 0; // Right Target in px
var positionTop = 0;
var positionLeft = 0;
let interval = setInterval(function() {
const {
bottom,
right
} = d.getBoundingClientRect();
const clientW = window.innerWidth;
const clientH = window.innerHeight;
if (clientH - bottom !== x) {
positionTop += 1;
d.style.top = positionTop + 'px';
}
if (clientW - right !== y) {
positionLeft += 1;
d.style.left = positionLeft + 'px';
}
if (right === clientW && bottom === clientH) {
clearInterval(interval);
}
}, 50);
<div id="my_box_realtime" style="background-color: red; position: absolute; min-width: 100px; min-height: 100px"></div>

Creating a pure javascript range slider control

I managed to create a somewhat working slider control but something feels kind of off. It doesnt quite behave as a normal control should. Sometimes while sliding it gets stuck and well, you might want to see for yourself.
How would you create the slider so that it slides smoothly without interruption or the user needing the cursor exactly on the red track?
function createRange(e) {
var range = (((e.offsetX - 0) * (255 - 0)) / (200-40 - 0)) + 0;
var rounded = Math.round(range);
return rounded;
}
function colorSlider(e) {
createRange(e)
}
var dragging = false;
document.getElementById("knob").addEventListener('mousedown', function(e) {
dragging = true;
e.target.style.pointerEvents = "none"
})
window.addEventListener('mousemove', function(e) {
if (dragging) {
if (createRange(e) <= 255) {
document.getElementById("knob").style.left = e.offsetX + "px"
}
}
})
Here is a fixed version of your slider.
var dragging = false;
var knobOffset = 0;
var track = document.getElementById('track'),
knob = document.getElementById('knob'),
trackWidth = track.offsetWidth,
trackLeft = track.offsetLeft,
trackRight = trackLeft + trackWidth,
knobWidth = knob.offsetWidth,
maxRight = trackWidth - knobWidth; // relatively to track
knob.addEventListener('mousedown', function(e) {
// knob offset relatively to track
knobOffset = e.clientX - knob.offsetLeft;
dragging = true;
});
window.addEventListener('mouseup', function(e) {
dragging = false;
})
window.addEventListener('mousemove', function(e) {
if (dragging) {
// current knob offset, relative to track
var offset = e.clientX - trackLeft - knobOffset;
if(offset < 0) {
var offset = 0;
} else if(offset > maxRight) {
var offset = maxRight;
}
knob.style.left = offset + "px"
}
});
#track {width: 200px;height: 5px; margin:100px; background: red}
#knob {height: 10px; width: 40px; background: black;position: relative; }
<div id='track'>
<div id="knob"></div>
</div>

mousemove parallax only move slightly instead of mouse position

I'm wanting the plane and rocket to only move approx 5% from their original place when the mouse hits the hero-panel area.
this current code makes both images follow and offset where the mouse position is.
Please assist.
$(document).ready(function () {
$('#hero-panel').mousemove(function (e) {
parallax(e, document.getElementById('plane'), 1);
parallax(e, document.getElementById('rocket'), 2);
});
});
function parallax(e, target, layer) {
var layer_coeff = 10 / layer;
var x = ($(window).width() - target.offsetWidth) / 4 - (e.pageX - ($(window).width() / 4)) / layer_coeff;
var y = ($(window).height() - target.offsetHeight) / 4 - (e.pageY - ($(window).height() / 4)) / layer_coeff;
$(target).offset({ top: y ,left : x });
};
https://jsfiddle.net/jc0807/c5yke2on/
Thanks
Ok, I think I understand what you're looking for:
fiddle
$(document).ready(function () {
var plane = document.getElementById('plane');
var rocket = document.getElementById('rocket');
plane.homePos = { x: plane.offsetLeft, y: plane.offsetTop };
rocket.homePos = { x: rocket.offsetLeft, y: rocket.offsetTop };
$('#hero-panel').mousemove(function (e) {
parallax(e, document.getElementById('plane'), 10);
parallax(e, document.getElementById('rocket'), 20);
});
});
function parallax(e, target, layer) {
var x = target.homePos.x - (e.pageX - target.homePos.x) / layer;
var y = target.homePos.y - (e.pageY - target.homePos.y) / layer;
$(target).offset({ top: y ,left : x });
};
What we're doing here is recording the starting position of the plane and the rocket as a new property 'homePos' on the plane and rocket objects. This makes it easy to apply the parallax effect as an offset from the original positions based on the mouse distance from the object homePos.
If you modify the layer value passed to parallax, the amount of movement will change (we're dividing the mouse offset from the middle of the object's starting position by it, to calculate the new object offset amount).
I guess my question is somehow related to the one above and I didn't want to create a duplicate.
I am using the code bellow to "navigate" into an image on mousemove. The problem is that I cannot manage to make the image fill all the viewable screen area. I've added a red background to the container to show what I mean. The desired result would be to no red background visible.
HTML
<div class="m-scene" id="main">
<div class="scene_element">
<img class="body" src="http://www.planwallpaper.com/static/images/nature-background-images2.jpg" />
</div>
</div>
JS
$(document).ready(function() {
$('img.body').mousemove(function(e) {
parallax(e, this, 1);
});
});
function parallax(e, target, layer) {
var layer_coeff = 20 / layer;
var x = ($(window).width() - target.offsetWidth) / 2 - (e.pageX - ($(window).width() / 2)) / layer_coeff;
var y = ($(window).height() - target.offsetHeight) / 2 - (e.pageY - ($(window).height() / 2)) / layer_coeff;
$(target).offset({
top: y,
left: x
});
};
CSS
.m-scene {
background-color: red;
overflow: hidden;
width: 100%;
}
.scene_element {
margin-left: auto;
margin-right: auto;
overflow: hidden;
}
.scene_element img {
width: 100%;
height: auto;
margin-left: auto;
margin-right: auto;
}
My jsFiddle is: fiddle
Thank you!

How to calculate anchor point, when changing transformX value on touchmove event?

I'm creating a slider that displays a panoramic image by moving it horizontally inside a container.
Features or Intention (it's under development):
By default the animation happens automatically, changing the transformX value, in each step;
the user's able to touch the element and drag it left or right;
when touchend event's triggered, the slider resumes the animation from the user's dragged x position;
The problem is that when a user touch the element and starts dragging, the input value on transformX makes the element jumpy, apparently because the anchor point is different every time the user touches the draggable element.
What I'd like to know is, how to calculate the anchor point or position, where the user is dragging from? Or what's the best practice to always calculate from the same point, to avoid having this jumps.
I've done quite a lot of research at the moment without success. You can find a live example in the following link (http://jsbin.com/quhabi/1/edit). Please turn on the touch emulator on your brower because at the moment I'm not yet supporting mouse dragging.
You can also have a look into the code below (depends on jQuery):
sass:
html {
width: 100%;
height: 100%;
body {
width: 100%;
height: 100%;
background-color: #999;
.panorama {
width: 80%;
height: 80%;
margin: 0 auto;
overflow: hidden;
img {
height: 100%;
position: relative;
transition: opacity 0.6s ease;
transform-origin:left top;
}
}
}
}
html:
<div class="panorama">
<img src="images/panorama.jpg" alt="">
</div>
Javascript:
/*globals $, window */
'use strict';
$('document').ready(function () {
var panorama = {
// properties
$panorama: $('.panorama'),
$moveElement: $('.panorama img'),
timestart: 0,
seconds: 12,
msTotal: 0,
direction: -1,
positionX: 0,
percentage: 0,
animationFrameID: false,
myRequestAnimationFrame: (function () {
return function (callback) {
return window.setTimeout(callback, 1000 / 60);
};
})(),
touchPlayTimeout: 3000,
moveTimeoutID: null,
rightBoundary: null,
// methods
step: function (timestart) {
var self = this,
timestamp,
positionX;
timestamp = Date.now();
self.progress = timestamp - timestart;
self.percentage = (self.progress * (100 / self.msTotal));
positionX = self.direction * self.percentage;
positionX = self.positionBounderies(positionX);
positionX += '%';
self.position(positionX);
if (self.progress < self.msTotal) {
timestamp += 10;
self.animationFrameID = self.myRequestAnimationFrame(function () {
self.step.call(self, timestart);
});
}
},
positionBounderies: function (positionX) {
// move the next line to init method, after image preload done!
this.rightBoundary = 100 - (100 * (this.$panorama.width() / this.$moveElement.width()));
positionX = positionX > 0 ? 0 : positionX;
positionX = (positionX < 0 && Math.abs(positionX) > this.rightBoundary) ? this.direction * this.rightBoundary : positionX;
return positionX;
},
progressByPercentage: function (percentage) {
return percentage * (this.msTotal / 100);
},
dragIt: function (touchX) {
var positionX,
percentage = (this.progress * (100 / this.msTotal));
positionX = this.direction * percentage;
positionX = positionX + (touchX / 100);
positionX = this.positionBounderies(positionX);
positionX += '%';
// update percentage
this.percentage = Math.abs(parseFloat(positionX));
this.position(positionX);
},
position: function (posX) {
this.$moveElement.css('transform', 'translateX(' + posX + ')');
},
init: function () {
var self = this;
// set initial values
this.msTotal = this.seconds * 1000;
// set listeners
this.$moveElement.on('touchstart mousedown', function (e) {
// on mousedown prevent browser default `img` drag
e.preventDefault();
clearTimeout(self.animationFrameID);
clearTimeout(self.moveTimeoutID);
});
this.$moveElement.on('touchend mouseup', function (e) {
// on mousedown prevent browser default `img` drag
e.preventDefault();
// calculate where to play from using current progress
var playFrom = null;
self.progress = self.progressByPercentage(self.percentage);
self.moveTimeoutID = setTimeout(function () {
clearTimeout(self.moveTimeoutID);
playFrom = Date.now();
playFrom = playFrom - self.progress;
self.step(playFrom);
}, self.touchPlayTimeout);
});
this.$moveElement.on('touchmove', function (e) {
console.log(e);
var touch = e.originalEvent.touches[0],
touchPosition = touch.pageX - self.$panorama.width();
self.dragIt(touchPosition);
});
this.step(Date.now());
}
};
panorama.init();
});
I found that my problem is related with how I'm calculating the drag distance. The code above clearly shows that I'm using solely the position of pageX to calculate the transformX, which is absolutely wrong. The correct way is to store the start point from where the drag is happening from and the current dragging x value should be used to calculate the distance.
For example,
this.$moveElement.on('touchstart mousedown', function (e) {
var touch = e.originalEvent.touches[0];
self.touchDistance.start = touch.pageX;
});
this.$moveElement.on('touchmove', function (e) {
var touch = e.originalEvent.touches[0],
distance = 0;
self.touchDistance.end = touch.pageX;
distance = self.touchDistance.end - self.touchDistance.start;
self.dragIt(distance);
});
With this, I've got a working solution, as we can see here http://jsbin.com/quhabi/2/edit
Thanks for looking, hope this is useful for someone else in the future!

Before / After Javascript issue

I am working on the currently codepen to display a hair treatment results
CODEPEN
But as soon as I add it to my website, it does not work.
I made a fiddle, and seems like the following class is breaking the code (on the fiddle works fine but does not follow the mouse pointer on the movement).
.wrapper_estudio {
width: 965px;
margin: 81px auto 0px auto;
padding-top: 100px;
}
EDIT
More especifically, the margin: 81px auto 0px auto; or the width: 965px; value.
DEMO (NOT JSFIDDLE) -> Check out this Demo to see what is exactly going on. Open console and uncheck the margin (or the width) on the div wrapper_estudio. Why does it work when margin is not set?
DEMO (JS FIDDLE)
$(function(){
var isDragging = false,
slide = $('.slide'),
controls = $('.controls');
$(".container").mousedown(function() {
$('.container').mousemove(function(e) {
var elemOffset = $(this).offset(),
relX = (e.pageX / $(this).width()) * 100;
console.log(relX);
if(relX < 98){
slide.css('width',relX + '%');
controls.css('left',relX - 3 + '%');
}
isDragging = true;
$(window).unbind("mousemove");
});
})
.mouseup(function() {
var wasDragging = isDragging;
isDragging = false;
$('.container').unbind("mousemove");
});
$('.container').mouseleave(function(){
isDragging = false;
$(this).unbind("mousemove");
});
});
Your problem lies in relX = (e.pageX / $(this).width()) * 100; where e.pageX gets the x position of the mouse relative to the left edge of the document as stated in the documentation.
Now when you add the margins with css the .container acquires an offset from the left side resulting in something like in this fiddle and the slider won't work correctly as happens in your website or in the fiddle you gave.
To solve this you need to modify the x coordinate like this:
relX = ((e.pageX-elemOffset.left) / $(this).width()) * 100;
What this does is subtracting the left offset of the image container from the distance from the left edge of the document thus returning the relative position of the mouse in the element.
So your final code should look like this:
$(function(){
var isDragging = false,
slide = $('.slide'),
controls = $('.controls');
$(".container").mousedown(function() {
$('.container').mousemove(function(e) {
var elemOffset = $(this).offset(),
relX = ((e.pageX-elemOffset.left) / $(this).width()) * 100;
console.log(relX);
if(relX < 98){
slide.css('width',relX + '%');
controls.css('left',relX - 3 + '%');
}
isDragging = true;
$(window).unbind("mousemove");
});
})
.mouseup(function() {
var wasDragging = isDragging;
isDragging = false;
$('.container').unbind("mousemove");
});
$('.container').mouseleave(function(){
isDragging = false;
$(this).unbind("mousemove");
});
});
And here is the working fiddle

Categories