Hide scroll bar when page preloader loads - javascript

I want to hide scroll bar while preloader is loading the scroll bar will not show until unless preloader disappears which means the user can't able to scroll the page while preloader is loading here I'm using canvas as a preloader. I tried by using body overflow: hidden and some CSS also but unable to achieve the result here I used canvas effect as a preloader. Can anyone point me in the right direction what I'm doing wrong?
/* Preloader Effect */
var noise = function(){
//const noise = () => {
var canvas, ctx;
var wWidth, wHeight;
var noiseData = [];
var frame = 0;
var loopTimeout;
// Create Noise
const createNoise = function() {
const idata = ctx.createImageData(wWidth, wHeight);
const buffer32 = new Uint32Array(idata.data.buffer);
const len = buffer32.length;
for (var i = 0; i < len; i++) {
if (Math.random() < 0.5) {
buffer32[i] = 0xff000000;
}
}
noiseData.push(idata);
};
// Play Noise
const paintNoise = function() {
if (frame === 9) {
frame = 0;
} else {
frame++;
}
ctx.putImageData(noiseData[frame], 0, 0);
};
// Loop
const loop = function() {
paintNoise(frame);
loopTimeout = window.setTimeout(function() {
window.requestAnimationFrame(loop);
}, (1000 / 25));
};
// Setup
const setup = function() {
wWidth = window.innerWidth;
wHeight = window.innerHeight;
canvas.width = wWidth;
canvas.height = wHeight;
for (var i = 0; i < 10; i++) {
createNoise();
}
loop();
};
// Reset
var resizeThrottle;
const reset = function() {
window.addEventListener('resize', function() {
window.clearTimeout(resizeThrottle);
resizeThrottle = window.setTimeout(function() {
window.clearTimeout(loopTimeout);
setup();
}, 200);
}, false);
};
// Init
const init = (function() {
canvas = document.getElementById('noise');
ctx = canvas.getContext('2d');
setup();
})();
};
noise();
$(document).ready(function(){
$('body').css({
overflow: 'hidden'
});
setTimeout(function(){
$('#preloader').fadeOut('slow', function(){
$('body').css({
overflow: 'auto'
});
});
}, 5000);
});
#preloader {
position: fixed;
height: 100vh;
width: 100%;
z-index: 5000;
top: 0;
left: 0;
right: 0;
bottom: 0;
background-color: #fff;
/* change if the mask should have another color then white */
z-index: 10000;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
<div id="preloader">
<canvas id="noise" class="noise"></canvas>
</div>

Try these Codes, If it works for you. I found this on StackOverflow. Source: Disable scrolling when preload a web page
Js Code
$(window).load(function() {
$(".preloader").fadeOut(1000, function() {
$('body').removeClass('loading');
});
});
Css Code
.loading {
overflow: hidden;
height: 100vh;
}
.preloader {
background: #fff;
position: fixed;
text-align: center;
bottom: 0;
right: 0;
left: 0;
top: 0;
}
.preloader4 {
position: absolute;
margin: -17px 0 0 -17px;
left: 50%;
top: 50%;
width:35px;
height:35px;
padding: 0px;
border-radius:100%;
border:2px solid;
border-top-color:rgba(0,0,0, 0.65);
border-bottom-color:rgba(0,0,0, 0.15);
border-left-color:rgba(0,0,0, 0.65);
border-right-color:rgba(0,0,0, 0.15);
-webkit-animation: preloader4 0.8s linear infinite;
animation: preloader4 0.8s linear infinite;
}
#keyframes preloader4 {
from {transform: rotate(0deg);}
to {transform: rotate(360deg);}
}
#-webkit-keyframes preloader4 {
from {-webkit-transform: rotate(0deg);}
to {-webkit-transform: rotate(360deg);}
}
Code
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<body class="loading">
<div class="preloader">
<div class="preloader4"></div>
</div>
//Code
</body>

You need to set overflow: hidden and height: 100vh both on the body and the html tags.
/* Preloader Effect */
var noise = function(){
//const noise = () => {
var canvas, ctx;
var wWidth, wHeight;
var noiseData = [];
var frame = 0;
var loopTimeout;
// Create Noise
const createNoise = function() {
const idata = ctx.createImageData(wWidth, wHeight);
const buffer32 = new Uint32Array(idata.data.buffer);
const len = buffer32.length;
for (var i = 0; i < len; i++) {
if (Math.random() < 0.5) {
buffer32[i] = 0xff000000;
}
}
noiseData.push(idata);
};
// Play Noise
const paintNoise = function() {
if (frame === 9) {
frame = 0;
} else {
frame++;
}
ctx.putImageData(noiseData[frame], 0, 0);
};
// Loop
const loop = function() {
paintNoise(frame);
loopTimeout = window.setTimeout(function() {
window.requestAnimationFrame(loop);
}, (1000 / 25));
};
// Setup
const setup = function() {
wWidth = window.innerWidth;
wHeight = window.innerHeight;
canvas.width = wWidth;
canvas.height = wHeight;
for (var i = 0; i < 10; i++) {
createNoise();
}
loop();
};
// Reset
var resizeThrottle;
const reset = function() {
window.addEventListener('resize', function() {
window.clearTimeout(resizeThrottle);
resizeThrottle = window.setTimeout(function() {
window.clearTimeout(loopTimeout);
setup();
}, 200);
}, false);
};
// Init
const init = (function() {
canvas = document.getElementById('noise');
ctx = canvas.getContext('2d');
setup();
})();
};
noise();
$(document).ready(function(){
$('body, html').css({
overflow: 'hidden',
height: '100vh'
});
setTimeout(function(){
$('#preloader').fadeOut('slow', function(){
$('body, html').css({
overflow: 'auto',
height: 'auto'
});
});
}, 5000);
});
#preloader {
position: fixed;
height: 100vh;
width: 100%;
z-index: 5000;
top: 0;
left: 0;
right: 0;
bottom: 0;
background-color: #fff;
/* change if the mask should have another color then white */
z-index: 10000;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
<div id="preloader">
<canvas id="noise" class="noise"></canvas>
</div>

Set the position of body as fixed and when the page is loaded, remove that.
document.body.style.position = "fixed";
window.addEventListener("load", () => {
document.body.style.position = "";
document.querySelector(".preloader").style.display = "none";
});

Related

Remove the ability to hold down a keyboard key

I have a small page. Circles appear here, when you click on them they disappear.
I added here the possibility that in addition to clicking on the LMB, you can also click on a keyboard key, in my case it is "A".
But I noticed the problem that if you hold down the "A" button, then drive in circles, then the need for clicks disappears, and this is the main goal.
Can I somehow disable the ability to hold this button so that only clicking on it works?
I tried pasting this code, but all animations stopped working for me.
var down = false;
document.addEventListener('keydown', function () {
if(down) return;
down = true;
// your magic code here
}, false);
document.addEventListener('keyup', function () {
down = false;
}, false);
Get error:
"message": "Uncaught ReferenceError: mouseOverHandler is not defined"
//create circle
var clickEl = document.getElementById("clicks");
var spawnRadius = document.getElementById("spawnRadius");
var spawnArea = spawnRadius.getBoundingClientRect();
const circleSize = 95; // Including borders
function createDiv(id, color) {
let div = document.createElement('div');
div.setAttribute('class', id);
if (color === undefined) {
let colors = ['#ebc6df', '#ebc6c9', '#e1c6eb', '#c6c9eb', '#c6e8eb', '#e373fb', '#f787e6', '#cb87f7', '#87a9f7', '#87f7ee'];
randomColor = colors[Math.floor(Math.random() * colors.length)];
div.style.borderColor = randomColor;
}
else {
div.style.borderColor = color;
}
// Randomly position circle within spawn area
div.style.top = `${Math.floor(Math.random() * (spawnArea.height - circleSize))}px`;
div.style.left = `${Math.floor(Math.random() * (spawnArea.width - circleSize))}px`;
div.classList.add("circle", "animation");
// Add click handler
let clicked = false;
div.addEventListener('mouseover', mouseOverHandler );
div.addEventListener('mouseout', mouseOutHandler );
div.addEventListener('click', (event) => {
if (clicked) { return; } // Only allow one click per circle
clicked = true;
div.style.animation = 'Animation 200ms linear forwards';
setTimeout(() => { spawnRadius.removeChild(div); }, 220);
});
spawnRadius.appendChild(div);
}
let i = 0;
const rate = 1000;
setInterval(() => {
i += 1;
createDiv(`circle${i}`);
}, rate);
let focusedEl = null;
const keyDownHandler = (evt) => {
if(evt.keyCode === 65 && focusedEl) focusedEl.click();
}
const mouseOutHandler = (evt) => focusedEl = null;
const mouseOverHandler = (evt) => focusedEl = evt.currentTarget;
document.addEventListener('keydown', keyDownHandler );
window.focus();
html, body {
width: 100%;
height: 100%;
margin: 0;
background: #0f0f0f;
}
.circle {
width: 80px;
height: 80px;
border-radius: 80px;
background-color: #0f0f0f;
border: 3px solid #000;
position: absolute;
}
#spawnRadius {
top: 55%;
height: 250px;
width: 500px;
left: 50%;
white-space: nowrap;
position: absolute;
transform: translate(-50%, -50%);
background: #0f0f0f;
border: 2px solid #ebc6df;
}
#keyframes Animation {
0% {
transform: scale(1);
opacity: 1;
}
50% {
transform: scale(.8);
}
100% {
transform: scale(1);
opacity: 0;
}
}
<html>
<body>
<div id="spawnRadius"></div>
</body>
</html>
You can check the repeat property of the event, which
… is true if the given key is being held down such that it is automatically repeating.
(but notice the compatibility notes on auto-repeat handling)
const keyDownHandler = (evt) => {
if (!evt.repeat && evt.keyCode === 65) {
// ^^^^^^^^^^^
focusedEl?.click();
}
}
//create circle
var clickEl = document.getElementById("clicks");
var spawnRadius = document.getElementById("spawnRadius");
var spawnArea = spawnRadius.getBoundingClientRect();
const circleSize = 95; // Including borders
function createDiv(id, color) {
let div = document.createElement('div');
div.setAttribute('class', id);
if (color === undefined) {
let colors = ['#ebc6df', '#ebc6c9', '#e1c6eb', '#c6c9eb', '#c6e8eb', '#e373fb', '#f787e6', '#cb87f7', '#87a9f7', '#87f7ee'];
randomColor = colors[Math.floor(Math.random() * colors.length)];
div.style.borderColor = randomColor;
}
else {
div.style.borderColor = color;
}
// Randomly position circle within spawn area
div.style.top = `${Math.floor(Math.random() * (spawnArea.height - circleSize))}px`;
div.style.left = `${Math.floor(Math.random() * (spawnArea.width - circleSize))}px`;
div.classList.add("circle", "animation");
// Add click handler
let clicked = false;
div.addEventListener('mouseover', mouseOverHandler );
div.addEventListener('mouseout', mouseOutHandler );
div.addEventListener('click', (event) => {
if (clicked) { return; } // Only allow one click per circle
clicked = true;
div.style.animation = 'Animation 200ms linear forwards';
setTimeout(() => { spawnRadius.removeChild(div); }, 220);
});
spawnRadius.appendChild(div);
}
let i = 0;
const rate = 1000;
setInterval(() => {
i += 1;
createDiv(`circle${i}`);
}, rate);
let focusedEl = null;
const mouseOutHandler = (evt) => focusedEl = null;
const mouseOverHandler = (evt) => focusedEl = evt.currentTarget;
document.addEventListener('keydown', keyDownHandler );
window.focus();
html, body {
width: 100%;
height: 100%;
margin: 0;
background: #0f0f0f;
}
.circle {
width: 80px;
height: 80px;
border-radius: 80px;
background-color: #0f0f0f;
border: 3px solid #000;
position: absolute;
}
#spawnRadius {
top: 55%;
height: 250px;
width: 500px;
left: 50%;
white-space: nowrap;
position: absolute;
transform: translate(-50%, -50%);
background: #0f0f0f;
border: 2px solid #ebc6df;
}
#keyframes Animation {
0% {
transform: scale(1);
opacity: 1;
}
50% {
transform: scale(.8);
}
100% {
transform: scale(1);
opacity: 0;
}
}
<html>
<body>
<div id="spawnRadius"></div>
</body>
</html>

Add a video control on top of a local html video

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

Collision detection using pure jQuery is not giving desired output

I am trying to develop a very simple game where the ship (red box) will move left-right when user clicks on playground.
There are some moving walls (black boxes) as obstacles that the ship should avoid colliding with.
If any collision happens, the walls will stop moving and a text will be printed out in console.
I have succeeded to get this as close as I can. But its working sometime, not always. You can see it in the code below, try to collide with wall. Sometime it will stop them and print text, sometime it will just ignore the collision as if nothing happens.
I have no clue why this is happening.
Here is the code.
$('document').ready(function() {
var $totalHeight = $('.inner').height(); //of walls
var $maxHeight = Math.ceil(Math.ceil($totalHeight / 3) - (Math.ceil($totalHeight / 3) * 30) / 100); //30% of total wall height
$('.wall').each(function(i, obj) {
$(this).height($maxHeight);
$('.wall.four').css({
'height': $wallGap
});
})
var $wallGap = Math.ceil($totalHeight / 3) - $maxHeight;
var $wallOneTop = 0;
var $wallTwoTop = $maxHeight + $wallGap;
var $wallThreeTop = ($maxHeight * 2) + ($wallGap * 2);
var $wallFourTop = -$('.wall.four').height() - $wallGap;
$('.wall.one').css({
'top': $wallOneTop
});
$('.wall.two').css({
'top': $wallTwoTop
});
$('.wall.three').css({
'top': $wallThreeTop
});
$('.wall.four').css({
'top': $wallFourTop
});
function moveWall(wallObj) {
var $currentTop = wallObj.position().top;
var $limitTop = $('.inner').height();
if ($currentTop >= $limitTop) {
var $rand = Math.floor(Math.random() * ($maxHeight - $wallGap + 1) + $wallGap);
wallObj.height($rand);
var $top = -(wallObj.height());
} else {
var $top = (wallObj.position().top) + 5;
}
var $collide = checkCollision(wallObj);
wallObj.css({
'top': $top
});
return $collide;
}
var $wallTimer = setInterval(function() {
$('.wall').each(function(i, obj) {
var $status = moveWall($(this));
if ($status == true) {
clearInterval($wallTimer);
}
})
}, 40);
function checkCollision(wallObj) {
var $ship = $('.ship');
var $shipWidth = $ship.width();
var $shipHeight = $ship.height();
var $shipLeft = $ship.position().left;
var $shipRight = $shipLeft + $shipWidth;
var $shipTop = $ship.position().top;
var $shipBottom = $shipTop + $shipHeight;
var $wall = wallObj;
var $wallWidth = wallObj.width();
var $wallHeight = wallObj.height();
var $wallLeft = wallObj.position().left;
var $wallRight = $wallLeft + $wallWidth;
var $wallTop = wallObj.position().top;
var $wallBottom = $wallTop + $wallHeight;
if (
$shipLeft >= $wallRight ||
$shipRight <= $wallLeft ||
$shipTop >= $wallBottom ||
$shipBottom <= $wallTop
) {
return false;
} else {
console.log("dhumm!");
return true;
}
}
$('.outer .inner').click(function() {
var $ship;
$ship = $('.ship');
$shipLeft = $ship.position().left;
$shipRight = $shipLeft + $ship.width();
$inner = $('.inner');
$innerLeft = $inner.position().left;
$innerRight = $innerLeft + $inner.width();
if (($shipLeft < $inner.width() - $ship.width())) {
$ship.animate({
"left": $inner.width() - $ship.width()
}, 500, "linear");
} else if (($shipRight >= $inner.width())) {
$ship.animate({
"left": '0'
}, 500, "linear");
}
});
});
.outer {
background: #fff;
border: 20px solid #efefef;
width: 400px;
height: 600px;
display: inline-block;
position: fixed;
top: 0;
bottom: 0;
left: 0;
right: 0;
margin: auto;
overflow: hidden;
}
.outer .inner {
background: #fff;
height: 100%;
width: 100%;
margin: auto;
position: relative;
overflow: hidden;
}
.outer .inner .wall {
width: 5px;
position: absolute;
left: 50%;
transform: translateX(-50%);
background: #000;
}
.outer .inner .ship {
width: 15px;
height: 15px;
background: red;
position: absolute;
top: 50%;
transform: translateY(-50%);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="outer">
<div class="inner">
<div class="wall one"></div>
<div class="wall two"></div>
<div class="wall three"></div>
<div class="wall four"></div>
<div class="ship"></div>
</div>
</div>
As freefomn-m already said.
Check for collision in the animation cycle of the ship, not the walls.
For this I use the second type of parameters for jQuery's .animate method
.animate( properties, options )
I use the "progress" option to check the collision in every movement cycle of the ship.
console.clear();
$('document').ready(function() {
var collided = false;
var collidedWith = null;
var $ship = $('.ship');
var $walls = $('.wall')
var $totalHeight = $('.inner').height(); //of walls
var $maxHeight = Math.ceil(Math.ceil($totalHeight / 3) - (Math.ceil($totalHeight / 3) * 30) / 100); //30% of total wall height
$('.wall').each(function(i, obj) {
$(this).height($maxHeight);
$('.wall.four').css({
'height': $wallGap
});
})
var $wallGap = Math.ceil($totalHeight / 3) - $maxHeight;
var $wallOneTop = 0;
var $wallTwoTop = $maxHeight + $wallGap;
var $wallThreeTop = ($maxHeight * 2) + ($wallGap * 2);
var $wallFourTop = -$('.wall.four').height() - $wallGap;
$('.wall.one').css({
'top': $wallOneTop
});
$('.wall.two').css({
'top': $wallTwoTop
});
$('.wall.three').css({
'top': $wallThreeTop
});
$('.wall.four').css({
'top': $wallFourTop
});
function moveWall(wallObj) {
var $currentTop = wallObj.position().top;
var $limitTop = $('.inner').height();
if ($currentTop >= $limitTop) {
var $rand = Math.floor(Math.random() * ($maxHeight - $wallGap + 1) + $wallGap);
wallObj.height($rand);
var $top = -(wallObj.height());
} else {
var $top = (wallObj.position().top) + 5;
}
// var $collide = checkCollision(wallObj);
wallObj.css({
'top': $top
});
// return $collide;
}
var $wallTimer = setInterval(function() {
$walls.each(function(i, obj) {
moveWall($(this));
if (collided) {
clearInterval($wallTimer);
}
})
}, 40);
function checkCollision() {
var $shipWidth = $ship.width();
var $shipHeight = $ship.height();
var $shipLeft = $ship.position().left;
var $shipRight = $shipLeft + $shipWidth;
var $shipTop = $ship.position().top;
var $shipBottom = $shipTop + $shipHeight;
$('.wall').each(function(i) {
var $wall = $(this);
var $wallWidth = $wall.width();
var $wallHeight = $wall.height();
var $wallLeft = $wall.position().left;
var $wallRight = $wallLeft + $wallWidth;
var $wallTop = $wall.position().top;
var $wallBottom = $wallTop + $wallHeight;
if (
$shipLeft < $wallRight &&
$shipRight > $wallLeft &&
$shipTop < $wallBottom &&
$shipBottom > $wallTop
) {
console.log("dhumm!");
collided = true;
collidedWith = $wall
$wall.addClass('crashed')
$ship.addClass('crashed')
$ship.stop();
return false;
}
})
}
$('.outer .inner').click(function() {
var $ship;
$ship = $('.ship');
$shipLeft = $ship.position().left;
$shipRight = $shipLeft + $ship.width();
$inner = $('.inner');
$innerLeft = $inner.position().left;
$innerRight = $innerLeft + $inner.width();
if (($shipLeft < $inner.width() - $ship.width())) {
$ship.animate({
"left": $inner.width() - $ship.width()
}, {
"duration": 500,
"easing": "linear",
"progress": checkCollision,
});
} else if (($shipRight >= $inner.width())) {
$ship.animate({
"left": '0'
}, {
"duration": 500,
"easing": "linear",
"progress": checkCollision,
});
}
});
});
.outer {
background: #fff;
border: 20px solid #efefef;
width: 400px;
height: 600px;
display: inline-block;
position: fixed;
top: 0;
bottom: 0;
left: 0;
right: 0;
margin: auto;
overflow: hidden;
}
.outer .inner {
background: #fff;
height: 100%;
width: 100%;
margin: auto;
position: relative;
overflow: hidden;
}
.outer .inner .wall {
width: 5px;
position: absolute;
left: 50%;
transform: translateX(-50%);
background: #000;
}
.outer .inner .wall.crashed {
background: red;
}
.outer .inner .ship {
width: 15px;
height: 15px;
background: orange;
position: absolute;
top: 50%;
transform: translateY(-50%);
}
.outer .inner .ship.crashed {
background: red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="outer">
<div class="inner">
<div class="wall one"></div>
<div class="wall two"></div>
<div class="wall three"></div>
<div class="wall four"></div>
<div class="ship"></div>
</div>
</div>
As a recommendation how I would do this from scratch.
Use an update cycle that is called by either setInterval or setTimeout, or even better with requestAnimationFrame. The updatecycle would be responsible for the time progress and orchestrate the different objects. The structure would be like this.
jQuery(function($) { // same as $('document').ready()
var ship = ...;
var boundaries = ...;
var walls = ...;
var clickEvents = [];
document.addEventListener('click', function(e) {clickEvents.push(e)})
var handleEvents = function() {}
var setupWalls = function () {}
var setupShip= function () {}
var moveWalls = function () {}
var moveShip = function () {}
var checkCollision() {}
var setup = function() {
setupWalls();
setupShip();
// set the initial positions of the ships and the walls
}
var update = function() {
handleEvents();
moveWalls();
moveShips();
var collided = checkCollision();
if (!collided) {
setTimeout(update, 30);
}
}
setup();
update();
})

Javascript slideshow white screen

Hi i'm building a javascript slider for my portfolio with Javascript. The slides work properly but when i add a fading transition i keep getting a white flash between the 2 slides. Anyone knows how to create a smooth fade between them?
Here's my working fiddle: https://jsfiddle.net/t9ezr8wr/2/
My javascript:
$(function () {
var theInterval; // Slide speed
var images = new Array();
var counter = 1;
var defaultSettings = {
"sliderContainer": "#slider" // SliderContainer
, "pauseWithMouse": true // Turn on/off pause with mouse
, "sliderSpeed": 3000 // Slide speed
, "transitionSpeed": 200 // transition speed
};
// intialize slider
// if myImages exists then
images = myImages;
if (images.length > 0) {
$(defaultSettings.sliderContainer).append('<img id="sliderImg" width="900" src="' + images[0] + '" />');
startSlide(images);
}
function cycleImages(images) {
if (counter >= images.length) {
counter = 0;
}
console.log(counter);
document.getElementById("sliderImg").src = images[counter];
counter++;
var images = $('#sliderImg')
var now = images.filter(':visible')
var next = now.next().length ? now.next() : images.first()
var speed = defaultSettings.transitionSpeed; //Transition speed
now.fadeOut(speed);
next.fadeIn(speed);
}
function startSlide() {
console.log('start');
theInterval = setInterval(function () {
cycleImages(images);
}, defaultSettings.sliderSpeed);
// Set interval time
};
var stopSlide = function () { // Stop slides on hover
console.log('stop');
if (defaultSettings.pauseWithMouse) {
clearInterval(theInterval);
}
};
$('#sliderImg').on('mouseover', function () { // Stop slides on mouseover
stopSlide();
});
$('#sliderImg').on('mouseout', function () { // Continue with slides on mouseout
startSlide();
});
});
what u wanted couldn't be achieved with one image ,so i used two image to achieve the desired effect.
JS:
$(function () {
var theInterval; // Slide speed
var images = new Array();
var counter = 1;
var defaultSettings = {
"sliderContainer": "#slider" // SliderContainer
, "pauseWithMouse": true // Turn on/off pause with mouse
, "sliderSpeed": 3000 // Slide speed
, "transitionSpeed": 600 // transition speed
};
// intialize slider
// if myImages exists then
images = myImages;
if (images.length > 0) {
$(defaultSettings.sliderContainer).append('<img id="sliderImg" width="900" style="display:block" src="' + images[0] + '" />');
$(defaultSettings.sliderContainer).append('<img id="sliderImg2" width="900" style="display:none" src="' + images[1] + '" />');
startSlide(images);
}
function cycleImages(images) {
if (counter >= images.length) {
counter = 0;
}
console.log(counter);
document.getElementById("sliderImg").src = images[counter];
counter++;
document.getElementById("sliderImg2").src = images[counter >= images.length ? 0 : counter];
var images = $('#sliderImg')
var now = $("#sliderImg")
var next = $("#sliderImg2")
var speed = defaultSettings.transitionSpeed; //Transition speed
now.fadeOut(speed);
next.fadeIn(speed,function(){
document.getElementById("sliderImg").src = document.getElementById("sliderImg2").src;
$("#sliderImg").css('display','block');
$("#sliderImg2").css('display','none');
});
}
function startSlide() {
console.log('start');
theInterval = setInterval(function () {
cycleImages(images);
}, defaultSettings.sliderSpeed);
// Set interval time
};
var stopSlide = function () { // Stop slides on hover
console.log('stop');
if (defaultSettings.pauseWithMouse) {
clearInterval(theInterval);
}
};
$('#sliderImg').on('mouseover', function () { // Stop slides on mouseover
stopSlide();
});
$('#sliderImg').on('mouseout', function () { // Continue with slides on mouseout
startSlide();
});
});
CSS:
body{
margin: 0;
}
main {
max-width: 100%;
height: 737px;
margin: auto;
font-family: arial;
position: relative;
color: white;
}
#slider {
width: 100%;
height: 100%;
overflow: hidden;
position: relative;
}
#slider img {display:none; position: absolute; top: 0; left: 0;}
#slider img:first-child {display:block;}
#slider img:nth-child(2) {display:none;}
The flash effect it's because your next picture is already visible before the call of fadeIn() function, you fix it with add next.hide() just before now.fadeOut().
$(function () {
var theInterval; // Slide speed
var images = new Array();
var counter = 1;
var defaultSettings = {
"sliderContainer": "#slider" // SliderContainer
, "pauseWithMouse": true // Turn on/off pause with mouse
, "sliderSpeed": 3000 // Slide speed
, "transitionSpeed": 800 // transition speed
};
// intialize slider
// if myImages exists then
images = myImages;
if (images.length > 0) {
$(defaultSettings.sliderContainer).append('<img id="sliderImg" width="900" src="' + images[0] + '" />');
startSlide(images);
}
function cycleImages(images) {
if (counter >= images.length) {
counter = 0;
}
console.log(counter);
document.getElementById("sliderImg").src = images[counter];
counter++;
var images = $('#sliderImg')
var now = images.filter(':visible')
var next = now.next().length ? now.next() : images.first()
var speed = defaultSettings.transitionSpeed; //Transition speed
next.hide();
now.fadeOut(speed);
next.fadeIn(speed);
}
function startSlide() {
console.log('start');
theInterval = setInterval(function () {
cycleImages(images);
}, defaultSettings.sliderSpeed);
// Set interval time
};
var stopSlide = function () { // Stop slides on hover
console.log('stop');
if (defaultSettings.pauseWithMouse) {
clearInterval(theInterval);
}
};
$('#sliderImg').on('mouseover', function () { // Stop slides on mouseover
stopSlide();
});
$('#sliderImg').on('mouseout', function () { // Continue with slides on mouseout
startSlide();
});
});
body{
margin: 0;
}
main {
max-width: 100%;
height: 737px;
margin: auto;
font-family: arial;
position: relative;
color: white;
}
#slider {
width: 100%;
height: 100%;
overflow: hidden;
position: relative;
}
#slider img {display:none; position: absolute; top: 0; left: 0;}
#slider img:first-child {display:block;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script>
var myImages = ["https://s4.postimg.org/45u9pqnml/slide1.jpg", "https://s11.postimg.org/f3qwh4syb/slide2.jpg", "https://s24.postimg.org/b365xoq7p/slide3.jpg"];
</script>
<main>
<div id="slider">
</div>
</main>
try to change transitionspeed to 0

How do I create png button animation with javascript?

I'm a graphic designer in Portugal, used to work with code everyday, like css, html and a bit javascript and php. I am currently developing an interactive logo button, but it has to be PNG to look the way I want. This is the javascript code on html (image is hosted in my website):
I want to create a mouseclick start and stop on last/first frame, not a infinite loop like this, and reversed animation after click to open/close. Basically, the lock and unlock of the padlock.
The point of this animation is to open a menu nav-bar under the logo. Can you help me?
My code:
var cSpeed = 5;
var cWidth = 200;
var cHeight = 145;
var cTotalFrames = 7;
var cFrameWidth = 200;
var cImageSrc = 'https://www.studiogo.net/sprites.png';
var cImageTimeout = false;
var cIndex = 0;
var cXpos = 0;
var SECONDS_BETWEEN_FRAMES = 0;
function startAnimation() {
document.getElementById('loaderImage').style.backgroundImage = 'url(' + cImageSrc + ')';
document.getElementById('loaderImage').style.width = cWidth + 'px';
document.getElementById('loaderImage').style.height = cHeight + 'px';
//FPS = Math.round(100/(maxSpeed+2-speed));
FPS = Math.round(100 / cSpeed);
SECONDS_BETWEEN_FRAMES = 1 / FPS;
setTimeout('continueAnimation()', SECONDS_BETWEEN_FRAMES / 1000);
}
function continueAnimation() {
cXpos += cFrameWidth;
//increase the index so we know which frame of our animation we are currently on
cIndex += 1;
//if our cIndex is higher than our total number of frames, we're at the end and should restart
if (cIndex >= cTotalFrames) {
cXpos = 0;
cIndex = 0;
}
document.getElementById('loaderImage').style.backgroundPosition = (-cXpos) + 'px 0';
setTimeout('continueAnimation()', SECONDS_BETWEEN_FRAMES * 1000);
}
function imageLoader(s, fun) //Pre-loads the sprites image
{
clearTimeout(cImageTimeout);
cImageTimeout = 0;
genImage = new Image();
genImage.onload = function() {
cImageTimeout = setTimeout(fun, 0)
};
genImage.onerror = new Function('alert(\'Could not load the image\')');
genImage.src = s;
}
//The following code starts the animation
new imageLoader(cImageSrc, 'startAnimation()');
<div id="loaderImage"></div>
Please, see if this is what you want.
$(document).ready(function () {
$(".lock").click(function () {
var $self = $(this);
if ($self.hasClass("closed")) {
$self.removeClass("close");
setTimeout(function () {
$self.addClass("open").removeClass("closed");
}, 100);
} else {
$self.removeClass("open");
setTimeout(function () {
$self.addClass("close").addClass("closed");
}, 100);
}
});
});
div.lock {
background-image: url('https://www.studiogo.net/sprites.png');
width: 200px;
height: 145px;
background-position: 0 center;
background-repeat: no-repeat;
}
div.closed {
background-position: -1200px center;
}
div.close {
animation: close-animation 300ms steps(6, start); // 1200px / 200px = 6
}
div.open {
animation: close-animation 300ms steps(6, end); // 1200px / 200px = 6
animation-fill-mode: backwards;
animation-direction: reverse;
}
#keyframes close-animation {
from {
background-position: 0 center;
}
to {
background-position: -1200px center;
}
}
<div class="lock closed">
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Categories