I am trying to create a vertical slider widget in javascript. I am not looking for any plugins or libraries, I am trying to see how it can done using plain javascript . I think I got the general idea.
See here for what has been developed so far and do view source to see the code and please open the link in chrome.
http://eco-system2031.appspot.com/pages/ex5slider/verticalslider.html
Issues:
1) Sometimes the border ranges(eg: 0, 500) does not get calculated properly when I move the slider to the very top or the very bottom.
2) Sometimes the slider does not get released when I release the mouse(mouseup), the slider moves along with the mouse even after mouseup.
3) Any other things I need to make the code more robust and smooth using only javascript.
And it is done. Thank you very one for your help.
Here is the HTML
Minimum Value: <input id="minimum-value" type="text" value="0" /> <br/>
Maximum Value: <input id="maximum-value" type="text" value="500" /> <br/>
<input id="submit-value" type="submit" value="Submit" /> <br/>
Slider Value: <span id="sliderValue"></span> <br/>
<div id="slider-container">
<div id="slider-bar"></div>
<div id="slider-handle"></div>
</div>
and here is the css
#slider-container {
width: 20px;
height: 325px;
margin: 100px;
margin-top: 30px;
background: #26AFE3;
/* Safari 3-4, iOS 1-3.2, Android 1.6 */
-webkit-border-radius: 20px 20px 20px 20px;
/* Firefox 1-3.6 */
-moz-border-radius: 20px 20px 20px 20px;
/* Opera 10.5, IE 9, Safari 5, Chrome, Firefox 4, iOS 4, Android 2.1+ */
border-radius: 20px 20px 20px 20px;
}
#slider-bar {
width: 100%;
height: 100%;
background: #E6E6E6;
/* Safari 3-4. iOS 1-3.2, Android 1.6 */
-webkit-border-radius: 20px 20px 20px 20px;
/* Firefox 1-3.6 */
-moz-border-radius: 20px 20px 20px 20px;
/* Opera 10.5, IE9, Safari 5, Chromer, Firefox 4, iOS 4, Android 2.1+ */
border-radius: 20px 20px 20px 20px;
}
#slider-handle {
width: 25px;
height: 25px;
background: #7C7D82;
position: relative;
left: -2.5px;
top: -10px;
/* Safari 3-4, iOS 1-3.2, Android 1.6 */
-webkit-border-radius: 2px 20px 20px 20px;
/* Firefox 1-3.6 */
-moz-border-radius: 20px 20px 20px 20px;
/* Opera 10.5, IE 9, Safari 5, Chrome, Firefox 4, iOS 4, Android 2.1+ */
border-radius: 20px 20px 20px 20px;
}
here is the js
(function () {
// html elements
var container = document.getElementById("slider-container");
var slider = document.getElementById("slider-bar");
var handle = document.getElementById("slider-handle");
var submitVal = document.getElementById("submit-value");
// initial values
var minVal = Number( document.getElementById("minimum-value").value );
var maxVal = Number( document.getElementById("maximum-value").value );
var range = maxVal - minVal;
var isSliding = false;
// recalculate range
submitVal.onclick = function() {
minVal = Number( document.getElementById("minimum-value").value );
maxVal = Number( document.getElementById("maximum-value").value );
range = maxVal - minVal;
};
// the sliding function
var move = function(e) {
var mouseY = 0;
var containerTop = 0;
var newHeight = 0;
var containerHeight = 0;
var percentHght = 0;
var x = 0;
var y = 0;
var sliderValue = 0;
if (!e) var e = window.event;
if( e.pageY ){ // all browsers except IE before version 9
mouseY = e.pageY;
} else if ( e.clientY ) { // IE before version 9
mouseY = e.clientY;
}
containerTop = container.offsetTop;
newHeight = mouseY - containerTop;
containerHeight = container.offsetHeight;
percentHght = newHeight * 100 / containerHeight;
if( (percentHght <= 100) && (percentHght >= 0) ) {
slider.style.height = (percentHght) + '%';
y = 100 - percentHght;
x = y * range / 100;
} else if( percentHght < 0 ) {
percentHght = 0;
slider.style.height = (percentHght) + '%';
y = 100 - percentHght;
x = y * range / 100;
} else if( percentHght > 100 ) {
percentHght = 100;
slider.style.height = (percentHght) + '%';
y = 100 - percentHght;
x = y * range / 100;
}
sliderValue = Math.round(x);
document.getElementById('sliderValue').innerHTML = sliderValue + minVal;
};
// adding the slide functionality
var addSlide = function() {
isSliding = true;
if ( !window.addEventListener ){
document.attachEvent('onmousemove',move);
} else {
document.addEventListener('mousemove', move, false);
}
};
// removing the slide functionality
var cancelSlide = function() {
if( isSliding ) {
if ( window.removeEventListener ) {
document.removeEventListener('mousemove', move, false);
} else if ( window.detachEvent ) {
document.detachEvent('onmousemove', move );
}
}
};
// cancelling event bubbling
// cancelling default event action
var cancelBubble = function(e) {
var evt = e ? e:window.event;
if( evt.stopPropogation ){
evt.stopPropogation();
}
if( evt.cancelBubble != null ){
evt.cancelBubble = true;
}
if( evt.preventDefault ){
evt.preventDefault();
} else {
evt.returnValue = false;
}
};
// capture events
//capturing the mousedown on the handle
handle.onmousedown = function(e) {
addSlide();
cancelBubble(e);
}
//capture the mouseup on the handle
handle.onmouseup = function(e) {
cancelSlide();
cancelBubble(e);
}
// capture the mouse up on the slider
slider.onmouseup = function(e) {
cancelSlide();
cancelBubble(e);
}
// capture the mouse down on the slider
slider.onmousedown = function(e) {
move(e);
cancelBubble(e);
}
// capture the mouse up on the container
container.onmouseup = function(e) {
cancelSlide();
cancelBubble(e);
}
// capture the mouse down on the container
container.onmousedown = function(e) {
move(e);
cancelBubble(e);
}
// capture the mouse up on the window
document.onmouseup = function(e) {
cancelSlide();
cancelBubble(e);
}
})();
here is the jsfiddle link
http://jsfiddle.net/nPaKp/
and here is a link out side jsfiddle
http://eco-system2031.appspot.com/pages/ex5slider/verticalslider.html
By the way, add this:
slider.onmouseuout = slider.onmouseup;
sort of thing to the end of each onmouseup declaration and the problem of the slider still following the pointer if it slips off the slider handle goes away.
Great addition!
Also change this:
stopPropogation() --> stopPropagation() // spelling mistake
A better way is to avoid stopPropagation altogether as it's bad practice. Interesting article: Dangers of stopping event propagation
If you want a larger handle click area e.g. when adding touch support:
#slider-handle {
position: relative;
width: 75px;
height: 48px;
left: -32.5px;
top: -24px;
border-radius: 50% / 50%;
border: 1px solid red; /* remove after test */
cursor: grab;
}
#slider-handle:after {
content: '';
position: absolute;
width: 100%;
height: 20%;
top: 40%;
left: 0;
background: #fff;
border-radius: 50%/50%;
}
Related
Is it possible to a piece of javascript on mobile/tablet devices only? I'd like to do something a bit better than display: none and it makes sense to stop the script from running if it's not required?
Basically I have a custom cursor effect, that is only required when it follows the cursor on desktop with a mouse/trackpad.
This is the script I have:
var cursor = document.querySelector('.cursor-outer');
var cursorinner = document.querySelector('.cursor');
var a = document.querySelectorAll('a');
var moveCursor = true;
var radiusOfCursor = parseInt(getComputedStyle(cursor).getPropertyValue('width')) / 2; // radiusOfCursor = (width_of_cursor / 2).
document.addEventListener('mousemove', function (e) {
var x = e.clientX;
var y = e.clientY;
cursorinner.style.left = x + 'px';
cursorinner.style.top = y + 'px';
if (!moveCursor) return;
cursor.style.marginLeft = `calc(${e.clientX}px - ${radiusOfCursor}px)`;
cursor.style.marginTop = `calc(${e.clientY}px - ${radiusOfCursor}px)`;
moveCursor = false;
setTimeout(() => {
moveCursor = true;
}, 32) // The wait time. I chose 95 because it seems to work just fine for me.
});
/* Centre pointer after stopping */
function mouseMoveEnd() {
cursor.style.marginLeft = `calc(${cursorinner.style.left} - ${radiusOfCursor}px)`;
cursor.style.marginTop = `calc(${cursorinner.style.top} - ${radiusOfCursor}px)`;
}
var x;
document.addEventListener('mousemove', function() {
if (x) clearTimeout(x);
x = setTimeout(mouseMoveEnd, 10);
}, false);
/* End */
document.addEventListener('mousedown', function() {
cursor.classList.add('click');
cursorinner.classList.add('cursorinnerhover');
});
document.addEventListener('mouseup', function() {
cursor.classList.remove('click');
cursorinner.classList.remove('cursorinnerhover');
});
a.forEach(item => {
item.addEventListener('mouseover', () => {
cursor.classList.add('hover');
});
item.addEventListener('mouseleave', () => {
cursor.classList.remove('hover');
});
});
a.forEach((item) => {
const interaction = item.dataset.interaction;
item.addEventListener("mouseover", () => {
cursorinner.classList.add(interaction);
});
item.addEventListener("mouseleave", () => {
cursorinner.classList.remove(interaction);
});
});
* {
cursor: none;
}
.cursor-outer {
border: 2px solid black;
border-radius: 100%;
box-sizing: border-box;
height: 32px;
pointer-events: none;
position: fixed;
top: 16px;
left: 16px;
transform: translate(-50%, -50%);
transition: height .12s ease-out, margin .12s ease-out, opacity .12s ease-out, width .12s ease-out;
width: 32px;
z-index: 100;
}
.cursor {
background-color: black;
border-radius: 100%;
height: 4px;
opacity: 1;
position: fixed;
transform: translate(-50%, -50%);
pointer-events: none;
transition: height .12s, opacity .12s, width .12s;
width: 4px;
z-index: 100;
}
<div class="cursor-outer"></div>
<div class="cursor"></div>
Thanks in advance!
Option #1
You can use something similar to this to determine if a device is touch-enabled:
isTouchDevice = () => {
return ( 'ontouchstart' in window ) ||
( navigator.maxTouchPoints > 0 ) ||
( navigator.msMaxTouchPoints > 0 );
};
This is adapted from Patrick H. Lauke's Detecting touch article on Mozilla.
Then just: if (isTouchDevice()) { /* Do touch screen stuff */}
Option #2
But maybe a pure CSS approach could work better in your situation, like:
#media (hover: none) {
.cursor {
pointer-events: none;
}
}
Option #3
If you don't mind using a third-party library, then Modernizr is really great for detecting things like this in the user's environment. Specifically, Modernizr.pointerevents will confirm if touchscreen is being used.
I have a large background image and some much smaller images for the user to drag around on the background. I need this to be efficient in terms of performance, so i'm trying to avoid libraries. I'm fine with drag 'n' drop if it work's well, but im trying to get drag.
Im pretty much trying to do this. But after 8 years there must be a cleaner way to do this right?
I currently have a drag 'n' drop system that almost works, but when i drop the smaller images, they are just a little off and it's very annoying. Is there a way to fix my code, or do i need to take a whole different approach?
This is my code so far:
var draggedPoint;
function dragStart(event) {
draggedPoint = event.target; // my global var
}
function drop(event) {
event.preventDefault();
let xDiff = draggedPoint.x - event.pageX;
let yDiff = draggedPoint.y - event.pageY;
let left = draggedPoint.style.marginLeft; // get margins
let top = draggedPoint.style.marginTop;
let leftNum = Number(left.substring(0, left.length - 2)); // cut off px from the end
let topNum = Number(top.substring(0, top.length - 2));
let newLeft = leftNum - xDiff + "px" // count new margins and put px back to the end
let newTop = topNum - yDiff + "px"
draggedPoint.style.marginLeft = newLeft;
draggedPoint.style.marginTop = newTop;
}
function allowDrop(event) {
event.preventDefault();
}
let imgs = [
"https://upload.wikimedia.org/wikipedia/commons/6/67/Orange_juice_1_edit1.jpg",
"https://upload.wikimedia.org/wikipedia/commons/f/ff/Solid_blue.svg",
"https://upload.wikimedia.org/wikipedia/commons/b/b4/Litoria_infrafrenata_-_Julatten.jpg"
]
/* my smaller images: */
for (let i = 0; i < 6; i++) {
let sensor = document.createElement("img");
sensor.src = imgs[i % imgs.length];
sensor.alt = i;
sensor.draggable = true;
sensor.classList.add("sensor");
sensor.style.marginLeft = `${Math.floor(Math.random() * 900)}px`
sensor.style.marginTop = `${Math.floor(Math.random() * 500)}px`
sensor.onclick = function() {
sensorClick(logs[i].id)
};
sensor.addEventListener("dragstart", dragStart, null);
let parent = document.getElementsByClassName("map")[0];
parent.appendChild(sensor);
}
<!-- my html: -->
<style>
.map {
width: 900px;
height: 500px;
align-content: center;
margin: 150px auto 150px auto;
}
.map .base {
position: absolute;
width: inherit;
height: inherit;
}
.map .sensor {
position: absolute;
width: 50px;
height: 50px;
}
</style>
<div class="map" onDrop="drop(event)" ondragover="allowDrop(event)">
<img src='https://upload.wikimedia.org/wikipedia/commons/f/f7/Plan-Oum-el-Awamid.jpg' alt="pohja" class="base" draggable="false">
<div>
With the answers from here and some time i was able to get a smooth drag and click with pure js.
Here is a JSFiddle to see it in action.
let maxLeft;
let maxTop;
const minLeft = 0;
const minTop = 0;
let timeDelta;
let imgs = [
"https://upload.wikimedia.org/wikipedia/commons/6/67/Orange_juice_1_edit1.jpg",
"https://upload.wikimedia.org/wikipedia/commons/f/ff/Solid_blue.svg",
"https://upload.wikimedia.org/wikipedia/commons/b/b4/Litoria_infrafrenata_-_Julatten.jpg"
]
var originalX;
var originalY;
window.onload = function() {
document.onmousedown = startDrag;
document.onmouseup = stopDrag;
}
function sensorClick () {
if (Date.now() - timeDelta < 150) { // check that we didn't drag
createPopup(this);
}
}
// create a popup when we click
function createPopup(parent) {
let p = document.getElementById("popup");
if (p) {
p.parentNode.removeChild(p);
}
let popup = document.createElement("div");
popup.id = "popup";
popup.className = "popup";
popup.style.top = parent.y - 110 + "px";
popup.style.left = parent.x - 75 + "px";
let text = document.createElement("span");
text.textContent = parent.id;
popup.appendChild(text);
var map = document.getElementsByClassName("map")[0];
map.appendChild(popup);
}
// when our base is loaded
function baseOnLoad() {
var map = document.getElementsByClassName("map")[0];
let base = document.getElementsByClassName("base")[0];
maxLeft = base.width - 50;
maxTop = base.height - 50;
/* my smaller images: */
for (let i = 0; i < 6; i++) {
let sensor = document.createElement("img");
sensor.src = imgs[i % imgs.length];
sensor.alt = i;
sensor.id = i;
sensor.draggable = true;
sensor.classList.add("sensor");
sensor.classList.add("dragme");
sensor.style.left = `${Math.floor(Math.random() * 900)}px`
sensor.style.top = `${Math.floor(Math.random() * 500)}px`
sensor.onclick = sensorClick;
let parent = document.getElementsByClassName("map")[0];
parent.appendChild(sensor);
}
}
function startDrag(e) {
timeDelta = Date.now(); // get current millis
// determine event object
if (!e) var e = window.event;
// prevent default event
if(e.preventDefault) e.preventDefault();
// IE uses srcElement, others use target
targ = e.target ? e.target : e.srcElement;
originalX = targ.style.left;
originalY = targ.style.top;
// check that this is a draggable element
if (!targ.classList.contains('dragme')) return;
// calculate event X, Y coordinates
offsetX = e.clientX;
offsetY = e.clientY;
// calculate integer values for top and left properties
coordX = parseInt(targ.style.left);
coordY = parseInt(targ.style.top);
drag = true;
document.onmousemove = dragDiv; // move div element
return false; // prevent default event
}
function dragDiv(e) {
if (!drag) return;
if (!e) var e = window.event;
// move div element and check for borders
let newLeft = coordX + e.clientX - offsetX;
if (newLeft < maxLeft && newLeft > minLeft) targ.style.left = newLeft + 'px'
let newTop = coordY + e.clientY - offsetY;
if (newTop < maxTop && newTop > minTop) targ.style.top = newTop + 'px'
return false; // prevent default event
}
function stopDrag() {
if (typeof drag == "undefined") return;
if (drag) {
if (Date.now() - timeDelta > 150) { // we dragged
let p = document.getElementById("popup");
if (p) {
p.parentNode.removeChild(p);
}
} else {
targ.style.left = originalX;
targ.style.top = originalY;
}
}
drag = false;
}
.map {
width: 900px;
height: 500px;
margin: 50px
position: relative;
}
.map .base {
position: absolute;
width: inherit;
height: inherit;
}
.map .sensor {
display: inline-block;
position: absolute;
width: 50px;
height: 50px;
}
.dragme {
cursor: move;
left: 0px;
top: 0px;
}
.popup {
position: absolute;
display: inline-block;
width: 200px;
height: 100px;
background-color: #9FC990;
border-radius: 10%;
}
.popup::after {
content: "";
position: absolute;
top: 100%;
left: 50%;
margin-left: -10px;
border-width: 10px;
border-style: solid;
border-color: #9FC990 transparent transparent transparent;
}
.popup span {
width: 90%;
margin: 10px;
display: inline-block;
text-align: center;
}
<div class="map" width="950px" height="500px">
<img src='https://upload.wikimedia.org/wikipedia/commons/f/f7/Plan-Oum-el-Awamid.jpg' alt="pohja" class="base" draggable="false" onload="baseOnLoad()">
<div>
I'm using a bit of HTML & CSS on my squarespace site to create a custom follow cursor. I want to just have a floaty circle with no actual cursor displayed. I've gotten it to mostly work, but when my site scrolls the follow cursor doesn't move with the page scroll and just gets stuck at the top.
And that just caused the follow cursor to stop moving with mouse movement entirely, becoming static on the center of the page.
Injecting HTML & CSS on to squarespace site to create a custom follow cursor:
body {
background: #161616;
}
.wrap {
position: absolute;
top: 0;
left: 0;
bottom: 0;
right: 0;
overflow: hidden;
}
#ball {
width: 60px;
height: 60px;
background: none;
border: 1px solid grey;
border-radius: 50%;
position: absolute;
left: 50%;
top: 50%;
margin: -10px 0 0 -10px;
pointer-events: none;
}
<body onload="followMouse();">
<div class="wrap">
<div id="ball"></div>
</div>
<script type="text/javascript">
var $ = document.querySelector.bind(document);
var $on = document.addEventListener.bind(document);
var xmouse, ymouse;
$on('mousemove', function (e) {
xmouse = e.clientX || e.pageX;
ymouse = e.clientY || e.pageY;
});
var ball = $('#ball');
var x = void 0,
y = void 0,
dx = void 0,
dy = void 0,
tx = 0,
ty = 0,
key = -1;
var followMouse = function followMouse() {
key = requestAnimationFrame(followMouse);
if(!x || !y) {
x = xmouse;
y = ymouse;
} else {
dx = (xmouse - x) * 0.125;
dy = (ymouse - y) * 0.125;
if(Math.abs(dx) + Math.abs(dy) < 0.1) {
x = xmouse;
y = ymouse;
} else {
x += dx;
y += dy;
}
}
ball.style.left = x + 'px';
ball.style.top = y + 'px';
};
</script>
</body>
[EDIT] Great job on updating your question, the demo and the problem are very clear now. Don't worry about your demo not scrolling, I just added a bunch of divs with some height in my demo to simulate that. Here's everything you need to / should change to make it all work:
var followMouse = function followMouse() ... is very strange syntax and I'm not sure what the exact outcome will be.
Either declare the function normally function followMouse() ..., or store it in a variable using either the:
function definition var followMouse = function() ... or
arrow definition var followMouse = () => ...
To simply get it all working you just need to adjust for the current scroll amount of either the document or in my demo's case the element with class ".wrap".
This can be done using the scrollTop member of the object returned by your $() function.
I started by just adding $(".wrap").scrollTop to the ymouse variable in the mousemove listener, but while this works it needs you to move the mouse for the circle to realize it's scrolled off the page.
So instead we just add $(".wrap").scrollTop to the css that is being set to the ball in the last lines of followMouse.
I changed the overflow property from hidden to scroll since that's kind of where the problem is occuring ;)
I've also added cursor: none to your .wrap css so that you get the desired effect of no cursor but your custom one.
var $ = document.querySelector.bind(document);
var $on = document.addEventListener.bind(document);
var followMouse = function() {
key = requestAnimationFrame(followMouse);
if (!x || !y) {
x = xmouse;
y = ymouse;
} else {
dx = (xmouse - x) * 0.125;
dy = (ymouse - y) * 0.125;
if (Math.abs(dx) + Math.abs(dy) < 0.1) {
x = xmouse;
y = ymouse;
} else {
x += dx;
y += dy;
}
}
ball.style.left = x + 'px';
ball.style.top = $(".wrap").scrollTop + y + 'px';
};
var xmouse, ymouse;
var ball = $('#ball');
var x = void 0,
y = void 0,
dx = void 0,
dy = void 0,
tx = 0,
ty = 0,
key = -1;
$on('mousemove', function(e) {
xmouse = e.clientX || e.pageX;
ymouse = e.clientY || e.pageY;
});
body {
background: #161616;
}
.wrap {
position: absolute;
top: 0;
left: 0;
bottom: 0;
right: 0;
overflow: scroll;
cursor: none;
}
#ball {
width: 60px;
height: 60px;
background: none;
border: 1px solid grey;
border-radius: 50%;
position: absolute;
left: 50%;
top: 50%;
margin: -10px 0 0 -10px;
pointer-events: none;
}
.makeOverflow {
width: 100px;
height: 300px;
}
<body onload="followMouse();">
<div class="wrap">
<div id="ball"></div>
<div class="makeOverflow"> </div>
<div class="makeOverflow"> </div>
<div class="makeOverflow"> </div>
<div class="makeOverflow"> </div>
</div>
</body>
This will probably be fixed by changing the #ball CSS from being absolutely positioned to a fixed position, then it should scroll down the page with your original js
Why I cannot get value inside the loop
Can use javascript only
Pause text for 2000ms on hover
reverse work on hover but should pause it first and then reverse the sequence until mouse out.
loop on reading text from textarea "input"
find this line in javascript to control delay
if(document.getElementById('flag2').value == "0"){
/*
1 : center
2 - 4 : center 2
5 - 7 : center 3
8 - 10 : center 4
11 - 13 : center 5
14 - 16 : center 6
17 - 19 : center 7
*/
stopNow= false;
function Loop(txt, wpm) {
txt = txt.replace(/\n/g, ' ');
var a = txt.split(' '),
n = a.length,
i = 0,
b = document.getElementById('bw'),
tw = document.getElementById('tw'),
tx = {
L: document.getElementById('txt_L'),
C: document.getElementById('txt_C'),
R: document.getElementById('txt_R')
}
;
function width(w) {
tw.textContent = w;
return tw.offsetWidth;
}
function middle(w) {
var x = 0;
var n = w.length,
// Center char calculation. 1=1, 2-4=2, 5-7=3, ...
c = ~~((n + 1) / 3) + 1,
z = {};
if (!n)
return;
z.a = width(w.substr(0, c - 1));
z.b = width(w.substr(0, c));
z.c = (z.b - z.a) / 2;
b.style.paddingLeft = ~~(110 - (z.a + z.c)) + 'px';
tx.L.textContent = w.substr(0, c - 1);
tx.C.textContent = w.substr(c - 1, 1);
tx.R.textContent = w.substr(c);
}
function word() {
if(stopNow){
middle(a[i])
if (--i === n)
i = 0;
return 0;
}
else{
middle(a[i])
if (++i === n)
i = 0;
return 0;
}
}
this.whiteout = function(w) {
if (w) {
tx.L.style.color = '#fff';
tx.R.style.color = '#fff';
} else {
tx.L.style.color = '#080';
tx.R.style.color = '#000';
}
};
wpm = wpm || 200;
var __time = 2000;
//can not get changes value here
if(document.getElementById('flag2').value == "0"){
__time = (60/wpm) * 1000;}
document.getElementById('flag1').innerHTML += document.getElementById('flag2').innerHTML ;
var tt = setInterval(function (){
document.getElementById('flag1').innerHTML = word();
}, __time);
}
var txt = document.getElementById('input').value;
var ww = new Loop(txt, 250);
document.getElementById('bw').addEventListener('change', function() {
ww.whiteout(this.checked);
});
document.getElementById('txtHolder').addEventListener('mouseover', function () {
stopNow = true;
document.getElementById('flag2').innerHTML = "1";
});
document.getElementById('txtHolder').addEventListener('mouseout', function () {
stopNow = false;
document.getElementById('flag2').innerHTML = "0";
});
* {
padding: 0;
margin:0;
}
.hide {
display: none;
}
#tw {
position: absolute;
visibility: hidden;
white-space: nowrap;
}
#tw,
#txt_L,
#txt_C,
#txt_R
{
font: bold 18px Arial;
line-height: 1;
}
#txt_L { color: #000; }
#txt_C { color: #f00; }
#txt_R { color: #000; }
#wrap {
position: relative;
width: 220px;
height: 50px;
border-top: 1px solid #000;
border-bottom: 1px solid #000;
}
#b1 {
width: 110px;
height: 50px;
border-right: 1px solid #000;
float:left;
}
#bw {
position: absolute;
width: 220px;
top: 10px;
background: #fff;
padding: 5px 0;
line-height: 1;
vertical-align: middle;
}
<!--
EXTRA POINTS---------
Pause text for 2000ms on hover and reverse the sequence until mouse out.
-->
<div id="flag1">
</div>
<div id="flag2">
</div>
<div id="txtHolder">
<span id="tw"></span>
<div id="wrap">
<div id="b1"></div>
<div id="bw"><span id="txt_L"> </span><span id="txt_C"></span><span id="txt_R"></span></div>
</div>
</div>
<textarea id="input" class="hide">
Oh, hey there, TIDWRTWHUFOO fans. Thinking about going for a little dip this summer? How about you go for a swim with a one-ton crab that will smash you under its massive legs? Sound fun? Definitely!
Crabster is a wild crab-like robot designed to explore the deepest oceans without smashing itself into a squashed tin can. It has massive legs, a large body, and lots of cameras so it can find you even if you’re the dude from The Big Blue and can dive really deep. There’s no escaping our future robotic-aquatic overlords
</textarea>
I have tried to create single scroll and move to next section, I have using javascript, It is not working fine, The window top distance not giving properly, I need to div fullscreen moved to next screen, Please without jquery, Please help
if (window.addEventListener) {window.addEventListener('DOMMouseScroll', wheel, false);
window.onmousewheel = document.onmousewheel = wheel;}
function wheel(event) {
var delta = 0;
if (event.wheelDelta) delta = (event.wheelDelta)/120 ;
else if (event.detail) delta = -(event.detail)/3;
handle(delta);
if (event.preventDefault) event.preventDefault();
event.returnValue = false;
}
function handle(sentido) {
var inicial = document.body.scrollTop;
var time = 500;
var distance = 900;
animate({
delay: 0,
duration: time,
delta: function(p) {return p;},
step: function(delta) {
window.scrollTo(0, inicial-distance*delta*sentido);
}
});
}
function animate(opts) {
var start = new Date();
var id = setInterval(function() {
var timePassed = new Date() - start;
var progress = (timePassed / opts.duration);
if (progress > 1) {progress = 1;}
var delta = opts.delta(progress);
opts.step(delta);
if (progress == 1) {clearInterval(id);}}, opts.delay || 10);
}
body{
width: 100%;
height: 100%;
margin:0;
padding:0;
}
.wrapper{
width: 100%;
height: 100%;
position: absolute;
}
section{
width: 100%;
height: 100%;
}
.pg1{
background: green;
}
.pg2{
background: blue;
}
.pg3{
background: yellow;
}
<div class="wrapper" id="myDiv">
<section class="pg1" id="sec1"></section>
<section class="pg2"></section>
<section class="pg3"></section>
</div>
Return the height of the element and store it in distance variable, instead of giving it a static 900.
From this:
var distance = 900;
To this:
var distance = document.getElementById('sec1').clientHeight;