I've just created a simple animation function that moves a box from left to right. The problem is when the animation runs the box becomes a rectangle when it animates so the proportion of the box shape is gone which is not what I want, how can you retain the shape of the box through the animation. When you slow the animation down to 2 seconds the box retains its shape but when you speed up the animation then it becomes skewed. How do you prevent this from happening?
function animate(...args) {
let starttime = new Date().getTime();
let requestID;
if(args.length == 5) {
args = { el: args[0], props: args[1], duration: args[2], step: args[3], callback: args[4] };
} else {
args = { el: args[0], props: args[1], duration: args[2], callback: args[3] };
}
function moveit(args) {
var timestamp = new Date().getTime();
var runtime = timestamp - starttime;
var progress = runtime / args.duration;
progress = Math.min(progress, 1);
for(const prop in args.props) {
let dist = parseInt(args.props[prop].substring(0, args.props[prop].length - 2), 10);
args.el.style[prop] = (dist * progress).toFixed(2) + 'px';
}
if(args.step != undefined) {
args.step(progress);
}
if (runtime < args.duration){ // if duration not met yet
requestID = requestAnimationFrame(moveit.bind(new Date().getTime(), args));
} else {
args.callback();
cancelAnimationFrame(requestID);
}
}
requestAnimationFrame(moveit.bind(new Date().getTime(), args));
}
window.addEventListener('load', function(event) {
//alert('Hello World')
document.getElementById('reset')
.addEventListener('click', function(event) {
document.getElementById('box').setAttribute('style', '')
});
document.getElementById('play')
.addEventListener('click', function(event) {
animate(document.getElementById('box'), { left: '400px' }, 500, function(step) {
}, function() {
});
});
});
.box {
background: red;
width: 50px;
height: 50px;
position: relative;
top: 0;
left: 0;
}
.controls {
position: relative;
top: 20px;
}
<div id="box" class="box"></div>
<div class="controls">
<button id="reset">reset</button>
<button id="play">play</button>
</div>
Related
The following is a link which shows a nice example of playing a local video in a browser:
http://jsfiddle.net/dsbonev/cCCZ2/
<h1>HTML5 local video file player example</h1>
<div id="message"></div>
<input type="file" accept="video/*"/>
<video controls autoplay></video>
However, on top of this, I would like to allow the user to create a "trailer clip" of a particular segment of their video. In this, I would like to have some sort of adjustable playhead such as the following:
Here is a site that does this exact same thing: https://www.flexclip.com/editor/app?ratio=landscape. Any insight into how I would go about building something like this that plays the local file and allows me to select a segment of it?
There's a few different things, though the particular question seems to be how to draw a preview bar of a local video.
Local Files
From the example in your question, you can see it's not too different working with a local file than with a remote file; you can create an object URL of the local file via URL.createObjectURL and then work with it as you would a normal video link.
Drawing the Preview Bar
Drawing the preview bar should consist of seeking to the appropriate time in the video, and then drawing that frame onto a canvas. You can seek to a specific point by setting the .currentTime property of the video and waiting for the seeked event. You can then use the canvasContext.drawImage method to draw an image using the video element.
I'd also recommend using a video element that isn't attached to the DOM for this, for a better user experience that doesn't have an onscreen video jumping to different times.
It could look something like this:
function goToTime(video, time) {
return new Promise ((resolve) => {
function cb () {
video.removeEventListener('seeked', cb);
resolve();
}
video.addEventListener('seeked', cb);
video.currentTime = time;
});
}
async function drawPreviewBar(video) {
const { duration, videoWidth, videoHeight } = video;
const previewBarFrameWidth = previewBarHeight * videoWidth / videoHeight;
const previewBarFrames = previewBarWidth / previewBarFrameWidth;
for (let i = 0; i < previewBarFrames; i++) {
await goToTime(video, i * duration * previewBarFrameWidth / previewBarWidth);
previewBarContext.drawImage(video, 0, 0,
videoWidth, videoHeight,
previewBarFrameWidth * i, 0,
previewBarFrameWidth, previewBarHeight
);
}
}
Resizing / Moving the Selected Clip
If you want to create a UI to resize or move around the clip, you can use standard drag handlers.
Example
Here's a basic example:
const previewBarWidth = 600;
const previewBarHeight = 40;
const videoElement = document.getElementById('video');
const inputElement = document.getElementById('file-picker');
const invisibleVideo = document.createElement('video');
const previewBarCanvas = document.getElementById('preview-bar-canvas');
previewBarCanvas.width = previewBarWidth;
previewBarCanvas.height = previewBarHeight;
const selector = document.getElementById('selector');
const previewBarContext = previewBarCanvas.getContext('2d');
const topHandle = document.getElementById('selector-top-handle');
const leftHandle = document.getElementById('selector-left-handle');
const rightHandle = document.getElementById('selector-right-handle');
const leftMask = document.getElementById('selector-left-mask');
const rightMask = document.getElementById('selector-right-mask');
var selectorLeft = 0, selectorWidth = previewBarWidth;
var minimumPreviewBarWidth = 80; // may want to dynamically change this based on video duration
var videoLoaded = false;
function goToTime(video, time) {
return new Promise ((resolve) => {
function cb () {
video.removeEventListener('seeked', cb);
resolve();
}
video.addEventListener('seeked', cb);
video.currentTime = time;
});
}
async function drawPreviewBar(video) {
const { duration, videoWidth, videoHeight } = video;
const previewBarFrameWidth = previewBarHeight * videoWidth / videoHeight;
const previewBarFrames = previewBarWidth / previewBarFrameWidth;
for (let i = 0; i < previewBarFrames; i++) {
await goToTime(video, i * duration * previewBarFrameWidth / previewBarWidth);
previewBarContext.drawImage(video, 0, 0, videoWidth, videoHeight, previewBarFrameWidth * i, 0, previewBarFrameWidth, previewBarHeight);
}
}
function loadVideo(file) {
var src = URL.createObjectURL(file);
var loaded = new Promise(function (resolve) {
invisibleVideo.addEventListener('loadedmetadata', resolve);
}).then(function () {
videoLoaded = true;
document.body.classList.add('loaded');
return drawPreviewBar(invisibleVideo);
});
videoElement.src = src;
invisibleVideo.src = src;
return loaded;
}
function updateSelectorBar() {
selector.style.width = selectorWidth + 'px';
selector.style.left = selectorLeft + 'px';
leftMask.style.width = selectorLeft + 'px';
rightMask.style.left = (selectorLeft + selectorWidth) + 'px';
rightMask.style.width = (previewBarWidth - selectorWidth - selectorLeft) + 'px';
}
function selectorUpdated() {
if (!videoLoaded) {
return;
}
var startFraction = selectorLeft / previewBarWidth;
var durationFraction = selectorWidth / previewBarWidth;
var startTime = startFraction * invisibleVideo.duration;
var duration = durationFraction * invisibleVideo.duration;
var endTime = startTime + duration;
// do something with startTime, endTime, and duration, maybe;
videoElement.currentTime = startTime;
}
function addDragHandler (event, cb, ecb) {
var startX = event.clientX;
function dragged(e) {
cb(e.clientX - startX);
}
window.addEventListener('mousemove', dragged);
window.addEventListener('mouseup', function ended() {
window.removeEventListener('mousemove', dragged);
window.removeEventListener('mouseup', ended);
ecb();
});
}
updateSelectorBar();
topHandle.addEventListener('mousedown', function (e) {
var startLeft = selectorLeft;
addDragHandler(e, function (dx) {
selectorLeft = Math.max(0, Math.min(previewBarWidth - selectorWidth, startLeft + dx));
updateSelectorBar();
}, selectorUpdated);
});
leftHandle.addEventListener('mousedown', function (e) {
var startLeft = selectorLeft;
var startWidth = selectorWidth;
addDragHandler(e, function (dx) {
selectorLeft = Math.max(0, Math.min(selectorLeft + selectorWidth - minimumPreviewBarWidth, startLeft + dx));
selectorWidth = (startWidth + startLeft - selectorLeft);
updateSelectorBar();
}, selectorUpdated);
});
rightHandle.addEventListener('mousedown', function (e) {
var startWidth = selectorWidth;
addDragHandler(e, function (dx) {
selectorWidth = Math.max(minimumPreviewBarWidth, Math.min(previewBarWidth - selectorLeft, startWidth + dx));
updateSelectorBar();
}, selectorUpdated);
});
var pendingLoad = Promise.resolve();
inputElement.addEventListener('change', function () {
let file = inputElement.files[0];
pendingLoad = pendingLoad.then(function () {
return loadVideo(file)
});
});
#video {
width: 100%;
height: auto;
}
#preview-bar {
position: relative;
margin-top: 10px;
}
.canvas-container {
position: relative;
left: 5px;
}
#preview-bar-canvas {
position: relative;
top: 2px;
}
#selector {
position: absolute;
top: 0;
bottom: 0;
left: 0;
width: 100%;
border: 2px solid orange;
border-left-width: 5px;
border-right-width: 5px;
border-radius: 3px;
overflow: show;
opacity: 0;
transition: opacity 1s;
pointer-events: none;
}
.loaded #selector{
opacity: 1;
pointer-events: initial;
}
#selector-top-handle {
position: absolute;
top: 0;
height: 10px;
width: 100%;
max-width: 30px;
left: 50%;
transform: translate(-50%,-100%);
background: darkgreen;
border-top-left-radius: 5px;
border-top-right-radius: 5px;
cursor: move;
}
.resize-handle {
position: absolute;
top: 0;
bottom: 0;
width: 5px;
cursor: ew-resize;
background: darkgreen;
opacity: 0.75;
transition: opacity 1s;
}
.resize-handle:hover {
opacity: 1;
}
.preview-mask {
position: absolute;
background: black;
opacity: 0.6;
top: 0;
bottom: 0;
}
#selector-left-mask {
left: 0;
}
#selector-left-handle {
left: -5px;
}
#selector-right-handle {
right: -5px;
}
<input type="file" id="file-picker" />
<video id="video"></video>
<div id="preview-bar">
<div class="canvas-container">
<canvas id="preview-bar-canvas"></canvas>
<div id="selector-left-mask" class="preview-mask"></div>
<div id="selector-right-mask" class="preview-mask"></div>
</div>
<div id ="selector">
<div id="selector-top-handle"></div>
<div id="selector-left-handle" class="resize-handle"></div>
<div id="selector-right-handle" class="resize-handle"></div>
</div>
</div>
Here is some infomation I found online about this question:
(all of the lines are commented fyi)
https://gist.github.com/simonhaenisch/116010ed657f6b257246464e33719613
I want a counter animation which is triggered only when webpage reaches that certain part. For example, the js file would be this. I want the count to start only when the page reaches that certain section.
const counters = document.querySelectorAll('.counter');
const speed = 200; // The lower the slower
counters.forEach(counter => {
const updateCount = () => {
const target = +counter.getAttribute('data-target');
const count = +counter.innerText;
// Lower inc to slow and higher to slow
const inc = target / speed;
// console.log(inc);
// console.log(count);
// Check if target is reached
if (count < target) {
// Add inc to count and output in counter
counter.innerText = count + inc;
// Call function every ms
setTimeout(updateCount, 1);
} else {
counter.innerText = target;
}
};
updateCount();
});
Yo can easily do it using Jquery
$(document).ready(function() {
$(window).scroll(function() {
if ($(document).scrollTop() > 50) {
$("div").css("background-color", "#111111");
} else {
$("div").css("background-color", "transparent");
}
});
});
div {
height: 120vh;
transition-duration: 0.5s;
}
<div>
Scroll to Change Background
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.0/jquery.min.js"></script>
You can use Intersection Observer to do that
const $observeSection = document.querySelector('#second');
const options = {
root: null,
rootMargin: '0px',
threshold: 0.5
};
const observer = new IntersectionObserver(entries => {
entries.forEach(entry => {
if (entry.intersectionRatio > options.threshold) {
$observeSection.classList.add('yellow');
} else {
$observeSection.classList.remove('yellow');
}
});
}, options);
observer.observe($observeSection);
main {
display: flex;
flex-direction: column;
height: 100%;
width: 100%;
}
main section {
width: 100vw;
height: 100vh;
}
#first {
background: red;
}
#second {
background: blue;
}
#third {
background: green;
}
.yellow {
background: yellow!important;
}
<main>
<section id="first"></section>
<section id="second"></section>
<section id="third"></section>
</main>
In this example, I observe the second section, and when the scroll come to the middle of the section (threshold: 0.5), I add a class to change the color of this section.
Be careful if you need to handle legacies browsers as you can see here :
https://caniuse.com/#feat=intersectionobserver
You don't need jquery to achieve this.
Here is a VanillaJS solution:
window.onscroll = (e) => {
e.stopPropagation();
window.pageYOffset > 50 && console.log("do smh");
}
help please help, I do not understand the reason. Throws an error ReferenceError: Velocity is not defined. If I use $ (function () {}; then the error disappears, but then simply do not work. Use hammer 2.0.4 and velocity 1.2.3
// Constants
const THRESH = 0.75;
const TIMING = 250;
// When the dom is loaded, set up hammer events.
document.addEventListener('DOMContentLoaded', f => {
var lis = document.querySelectorAll('.swipe');
for (let i = 0; i < lis.length; i++) {
let hammertime = new Hammer(lis[i]);
hammertime.on('panright', e => handlePan(e));
hammertime.on('panend', e => reset(e));
}
});
// pane{right} handler
function handlePan(e, model) {
var {target: el, deltaX: dx} = e;
if (doAction(dx, el)) {
el.classList.add('action');
} else {
el.classList.remove('action');
}
Velocity(el, {
translateX: dx
}, 0);
}
// panend handler
function reset(e) {
var {target: el, deltaX: dx} = e;
// Should we remove the element?
if (doAction(dx, el)) {
Velocity(el, {
translateX: dx * 2
}, TIMING).then(() => {
return Velocity(el, {
height: 0
}, TIMING);
}).then(() => {
el.parentNode.removeChild(el);
});
} else {
Velocity(el, {
translateX: 0
}, TIMING);
}
}
// Determines if an element will be dismissed
function doAction(dx, el) {
return Math.abs(dx) >= THRESH * el.clientWidth;
}
.swipe {
position: relative;
list-style: none;
text-align: center;
background: #9e9e9e;
height: 150px;
line-height: 150px;
width: 40vw;
}
<div class="swipe">Swipe me!</div>
<!--Scripts-->
<script src="http://code.jquery.com/jquery-2.2.0.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/hammer.js/2.0.4/hammer.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/velocity/1.2.3/velocity.min.js"></script>
The velocity library reference should have been BEFORE the
jQuery reference. The way you know this is that when you run the code, with the developers tools open (F12) and you get the error, the error comes up from within the jQuery code - - so that means that jQuery can't find velocity. Then looking at the script references, you can see why...the jQuery library is running before the velocity library has been loaded.
This works:
// Constants
const THRESH = 0.75;
const TIMING = 250;
// When the dom is loaded, set up hammer events.
document.addEventListener('DOMContentLoaded', f => {
var lis = document.querySelectorAll('.swipe');
for (let i = 0; i < lis.length; i++) {
let hammertime = new Hammer(lis[i]);
hammertime.on('panright', e => handlePan(e));
hammertime.on('panend', e => reset(e));
}
});
// pane{right} handler
function handlePan(e, model) {
var {target: el, deltaX: dx} = e;
if (doAction(dx, el)) {
el.classList.add('action');
} else {
el.classList.remove('action');
}
Velocity(el, {
translateX: dx
}, 0);
}
// panend handler
function reset(e) {
var {target: el, deltaX: dx} = e;
// Should we remove the element?
if (doAction(dx, el)) {
Velocity(el, {
translateX: dx * 2
}, TIMING).then(() => {
return Velocity(el, {
height: 0
}, TIMING);
}).then(() => {
el.parentNode.removeChild(el);
});
} else {
Velocity(el, {
translateX: 0
}, TIMING);
}
}
// Determines if an element will be dismissed
function doAction(dx, el) {
return Math.abs(dx) >= THRESH * el.clientWidth;
}
.swipe {
position: relative;
list-style: none;
text-align: center;
background: #9e9e9e;
height: 150px;
line-height: 150px;
width: 40vw;
}
<!--Scripts-->
<script src="https://cdnjs.cloudflare.com/ajax/libs/velocity/1.2.3/velocity.min.js"></script>
<script src="http://code.jquery.com/jquery-2.2.0.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/hammer.js/2.0.4/hammer.min.js"></script>
<div class="swipe">Swipe me!</div>
I need my progress bar to last for exactly 20 seconds.
when it completes the bar, it still needs to be able to refresh, like it does now.
I need to be able to put the exact number of seconds in my code.
here's my code:
<div id="pbar_outerdiv">
<div id="pbar_innerdiv"></div>
<!--<div id="pbar_innertext" style="z-index: 3; position: absolute; top: 0; left: 0; width: 100%; height: 100%; color: black; font-weight: bold; text-align: center;"></div>-->
</div>
<script>
var timer = 0,
perc = 0,
timeTotal = 2500,
timeCount = 1,
cFlag;
function updateProgress(percentage) {
var x = (percentage/timeTotal)*100,
y = x.toFixed(3);
if(y === "100.000")
window.location.reload(1);
$('#pbar_innerdiv').css("width", x + "%");
//$('#pbar_innertext').text(y + "%");
}
function animateUpdate() {
if(perc < timeTotal) {
perc++;
updateProgress(perc);
timer = setTimeout(animateUpdate, timeCount);
}
}
$(document).ready(function() {
$('#pbar_outerdiv').click(function() {
if (cFlag == undefined) {
clearTimeout(timer);
perc = 0;
cFlag = true;
animateUpdate();
}
else if (!cFlag) {
cFlag = true;
animateUpdate();
}
else {
clearTimeout(timer);
cFlag = false;
}
});
$( "#pbar_outerdiv" ).trigger( "click" );
});
</script>
You're using jQuery. Instead of reinventing the wheel, you can do everything you're attempting there with just:
var duration = 20 * 1000; // = 20 seconds
$(document).ready(function() {
$outer = $("#pbar_outerdiv");
$outer.click(function() {
$('#pbar_innerdiv')
.stop()
.css({ width: 0 })
.animate({ width: "100%" }, duration, "linear", function() { window.location.reload(1); });
})
$outer.trigger("click");
});
Working demo
I am trying to develop the following carousel.
http://jsfiddle.net/2kLanjwn/2/
It should work in this way.
Clicking the button DOWN, carousel scrolls and resize always div in the center.
I am not able to apply the same logic on the reverse, so when I click button UP I need to contract the central div, and sliding up.
I kindly you what I am doing wrong and if you would be able to fix it on jsfiddle.
Also I would like to know if there is any better way to achieve that same effect or a component that can be reused.
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Scroll text box example</title>
<style>
#btn-up, #btn-down {
position: absolute;
top: 600px;
}
#btn-up {
left: 0px;
}
#btn-down {
left: 50px;
}
#btn-up, #btn-down {
width: 50px;
height: 50px;
background-color: yellow;
outline: 1px solid black;
}
#content-scroll-container {
position: absolute;
top: 0;
left: 0px;
width: 500px;
height: 250px; /* MASK HEIGHT real mask would be 200*/
overflow: hidden;
}
#content-scroll-inner {
position: absolute;
}
.cnt {
height: 100px;
width: 500px;
background-color: red;
}
.cnt:nth-child(even) {
height: 100px;
background-color: pink;
}
</style>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script>
var scroller = {
config: {
curPos: 0, // position
canExpand: false,
el: 'content-scroll-container', // visible area (container)
elInner: 'content-scroll-inner', // inner content
cntPosY: null, // content top-left corner (0 position)
cntHeight: null, // content lenght
maskHeight: null, // visible area (rest is masked out)
canMoveUp: null, // true jquery can slide up content
canMoveDown: null, // true jquery can slide down content
increment: 100, // slide of x pixel when user perfom an action
incrementOf: 0, // how much we have slided the contnt
animationSpeed: 500, // jquery animation speed, use 0 for no animation
isAnimationOn: false, // true when jquery is performing animation
},
data: '<div id="cnt-0" class="cnt">0</div><div id="cnt-1" class="cnt">1</div><div id="cnt-2" class="cnt">2</div><div id="cnt-3" class="cnt">3</div><div id="cnt-4" class="cnt">4</div><div id="cnt-5" class="cnt">5 empty</div>',
getCntPosition: function () {
// get y position of content
var elm = document.getElementById(this.config.elInner);
this.config.cntPosY = elm.offsetTop;
},
getCntSize: function () {
// get height for content
var elm = document.getElementById(this.config.elInner);
this.config.cntHeight = elm.clientHeight;
},
getMaskSize: function () {
// get height visible area
var elm = document.getElementById(this.config.el);
this.config.maskHeight = elm.clientHeight;
},
updateData: function () {
// refresh state
this.getMaskSize();
this.getCntPosition();
this.getCntSize();
this.canMoveUpCheck();
this.canMoveDownCheck();
//console.clear();
console.log(this.config);
},
canMoveUpCheck: function () {
// set flags allowing sliding up (in case we have enought content to show)
var lastScreenY = (this.config.cntHeight - this.config.maskHeight); // last screen visible
if ((this.config.incrementOf * -1) < lastScreenY)
this.config.canMoveUp = true;
else
this.config.canMoveUp = false;
},
canMoveDownCheck: function () {
// set flags allowing sliding down (in case we have enought content to show)
if (this.config.cntPosY >= 0)
this.config.canMoveDown = false; // cannot move more up if content is on start position (0 position)
else
this.config.canMoveDown = true;
},
goUp: function () {
// user want to read previose content
//this.updateData();
if (this.config.canMoveDown == true && this.config.isAnimationOn == false) {
this.moveCnt('down'); // content go down
}
},
goDown: function () { //**************************
// user want to read next content
//this.updateData();
if (this.config.canMoveUp == true && this.config.isAnimationOn == false) {
// check newPos
var newPos = this.config.curPos + 1;
if (newPos > 0) { // special case
if (this.config.canExpand == true)
this.config.increment = 150;
this.config.canExpand = true;
this.moveCnt('up');
}
}
},
moveCnt: function (direction) {
// do the actual animation
var moveOf;
this.isAnimationOn = true;
if (direction == 'up') {
this.config.curPos++;
if (this.config.cntPosY == 0) { // special case for first item
moveOf = '-=' + (this.config.increment / 2);
}
else {
moveOf = '-=' + this.config.increment;
}
var target = '#' + this.config.elInner + ':not(:animated)';
$(target).animate({ 'top': moveOf }, this.animationSpeed, this.cbEndAnimation.bind(this, direction));
} else if (direction == 'down') {
this.config.curPos++;
var distanceToFp = (this.config.increment / 2); // height to reach first page (special page)
var distanceToFp = 50;
if (this.config.cntPosY == (distanceToFp * -1)) {
moveOf = '+=' + distanceToFp;
// i need to contract only the firs tone
$('cnt-1').css({ height: '100px' }, 500, this.cbEndAnimationExpand.bind(this));
} else {
moveOf = '+=' + this.config.increment;
}
var target = '#' + this.config.elInner + ':not(:animated)';
$(target).animate({ 'top': moveOf }, this.animationSpeed, this.cbEndAnimation.bind(this));
}
//var target = '#' + this.config.elInner + ':not(:animated)';
//$(target).animate({ 'top': moveOf }, this.animationSpeed, this.cbEndAnimation.bind(this, direction));
},
cbEndAnimation: function (direction) {
// runs when animation end
this.config.isAnimationOn = false;
if (direction == 'up') {
this.config.incrementOf -= this.config.increment;
if (this.config.canExpand == true) { // expand
this.logicExpand();
} else {
// do nothing
}
}
else if (direction == 'down') {
this.config.incrementOf += this.config.increment;
}
this.updateData(); // refresh state has element has just moved
this.logicShowHideArrows();
},
logicExpand: function () {
// take contenf and expand it
var elm = document.getElementById('cnt-' + this.config.curPos);
$(elm).animate({ height: '150px' }, 500, this.cbEndAnimationExpand.bind(this));
},
cbEndAnimationExpand: function () {
console.log('end anim expand');
},
logicContract: function () {
var elm = document.getElementById('cnt-' + this.config.curPos);
$(elm).animate({ height: '-=50px' }, 500, this.cbEndAnimationContract.bind(this));
},
logicShowHideArrows: function () {
// reset first
this.hideArrow('btn-up');
this.hideArrow('btn-down');
if (this.config.canMoveUp == true)
this.showArrow('btn-down');
if (this.config.canMoveDown == true)
this.showArrow('btn-up');
},
cbEndAnimationContract: function () {
this.config.isAnimationOn = false;
this.moveCnt('down'); // content go down
},
showArrow: function (elmName) {
var elm = document.getElementById(elmName);
elm.style.display = '';
},
hideArrow: function (elmName) {
var elm = document.getElementById(elmName);
elm.style.display = 'none';
},
setEventHandler: function () {
// envet handlers for arrows
var btnUp = document.getElementById('btn-up');
btnUp.addEventListener('click', this.goUp.bind(this), false);
var btnDown = document.getElementById('btn-down');
btnDown.addEventListener('click', this.goDown.bind(this), false);
},
renderData: function () {
// render data content to slide
var elm = document.getElementById(this.config.elInner);
elm.innerHTML = this.data;
},
start: function () {
this.renderData();
this.updateData();
this.setEventHandler();
this.logicShowHideArrows(); // at start set arrows visibility
}
};
</script>
</head>
<body onload="scroller.start();">
<div id="content-scroll-container">
<div id="content-scroll-inner">
</div>
</div>
<div id="btn-up">UP</div>
<div id="btn-down">DOWN</div>
</body>
</html>
I can't find what in your code is wrong, but I made some changes to it, and it worked. Here is the code
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Scroll text box example</title>
<style>
#btn-up, #btn-down {
position: absolute;
top: 400px;
}
#btn-up {
left: 0px;
}
#btn-down {
left: 50px;
}
#btn-up, #btn-down {
width: 50px;
height: 50px;
background-color: yellow;
outline: 1px solid black;
}
#content-scroll-container {
position: absolute;
top: 0;
left: 0px;
width: 500px;
height: 250px; /* MASK HEIGHT real mask would be 200*/
overflow: hidden;
}
#content-scroll-inner {
position: absolute;
}
.cnt {
height: 100px;
width: 500px;
background-color: red;
}
.cnt:nth-child(even) {
height: 100px;
background-color: pink;
}
</style>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script>
var scroller = {
config: {
curPos: 0, // position
el: 'content-scroll-container', // visible area (container)
elInner: 'content-scroll-inner', // inner content
cntPosY: null, // content top-left corner (0 position)
cntHeight: null, // content lenght
maskHeight: null, // visible area (rest is masked out)
animationSpeed: 500, // jquery animation speed, use 0 for no animation
isAnimationOn: false, // true when jquery is performing animation
},
data: '<div id="cnt-0" class="cnt">0</div><div id="cnt-1" class="cnt">1</div><div id="cnt-2" class="cnt">2</div><div id="cnt-3" class="cnt">3</div><div id="cnt-4" class="cnt">4</div><div id="cnt-5" class="cnt">5 empty</div>',
getCntPosition: function () {
// get y position of content
var elm = document.getElementById(this.config.elInner);
this.config.cntPosY = elm.offsetTop;
},
getCntSize: function () {
// get height for content
var elm = document.getElementById(this.config.elInner);
this.config.cntHeight = elm.clientHeight;
},
getMaskSize: function () {
// get height visible area
var elm = document.getElementById(this.config.el);
this.config.maskHeight = elm.clientHeight;
},
updateData: function () {
// refresh state
this.getMaskSize();
this.getCntPosition();
this.getCntSize();
//console.clear();
console.log(this.config);
},
logicShowHideArrows: function () {
if(this.config.curPos<1) {
$('#btn-up').hide();
} else {
$('#btn-up').show();
}
if(this.config.curPos>=4) {
$('#btn-down').hide();
} else {
$('#btn-down').show();
}
},
goUp: function () {
if(this.config.curPos<4 && scroller.config.isAnimationOn ==false) {
scroller.config.isAnimationOn = true;
scroller.config.curPos++;
if(scroller.config.curPos==1) {
$('#content-scroll-inner').animate({'top':'-=50px'},500,function(){
$('#cnt-'+scroller.config.curPos).animate({'height':'+=50px'},500);
scroller.logicShowHideArrows();
scroller.config.isAnimationOn = false;
});
this.config.incrementOf-=50;
$('#btn-up').show();
}
else {
$('#content-scroll-inner').animate({'top':'-=150px'},500,function(){
$('#cnt-'+scroller.config.curPos).animate({'height':'+=50px'},500);
scroller.logicShowHideArrows();
scroller.config.isAnimationOn = false;
});
this.config.incrementOf-=150;
}
this.updateData();
}
},
goDown: function () { //**************************
// user want to read next content
//this.updateData();
if(this.config.curPos>0 && scroller.config.isAnimationOn ==false) {
scroller.config.isAnimationOn = true;
if(this.config.curPos==1) {
$('#cnt-'+scroller.config.curPos).animate({'height':'-=50px'},500,function(){
$('#content-scroll-inner').animate({'top':'+=50px'},500);
scroller.logicShowHideArrows();
scroller.config.isAnimationOn = false;
});
scroller.config.curPos--;
this.config.incrementOf+=150;
this.updateData();
}
else {
$('#cnt-'+scroller.config.curPos).animate({'height':'-=50px'},500,function(){
$('#content-scroll-inner').animate({'top':'+=150px'},500);
scroller.logicShowHideArrows();
scroller.config.isAnimationOn = false;
});
scroller.config.curPos--;
this.config.incrementOf+=150;
this.updateData();
}
}
},
setEventHandler: function () {
$('#btn-up').click(function() {
scroller.goDown();
});
$('#btn-down').click(function() {
scroller.goUp();
});
},
renderData: function () {
// render data content to slide
var elm = document.getElementById(this.config.elInner);
elm.innerHTML = this.data;
},
start: function () {
this.renderData();
this.updateData();
this.setEventHandler();
this.logicShowHideArrows();
}
};
</script>
</head>
<body onload="scroller.start();">
<div id="content-scroll-container">
<div id="content-scroll-inner">
</div>
</div>
<div id="btn-up">UP</div>
<div id="btn-down">DOWN</div>
</body>
</html>