modifying a sliding javascript div - javascript

I got some code off the net to make a box slide in. However it slid in from the top left and I wanted it to slide in from the bottom. I changed the css position from top:-200px to bottom:-200px and changed the part of the code that alters the position from
{
popup.style.top = (currentTop + speed) + "px";
keepMoving = true;
}
to
{
popup.style.bottom = (currentTop + speed) + "px";
keepMoving = true;
}
now it doesn't work. I cannot see what variable I should be making. Here is the full code (which works if I change them back to 'top')
<html>
<head>
<title>Moving Pop Up Samplet</title>
<style>
#popup
{
height:200px;
width:200px;
border:1px solid #000;
background:#CC9900;
position:absolute;
bottom:-200px;
left:-200px;
}
</style>
<script>
var timer = null;
var speed = 3; //1 is slow
var endTop = 0;
var endLeft = 0;
//******************************************************
// Simple little function to get Elements as an object
//******************************************************
function getEl(id)
{
var el = document.getElementById(id);
return el;
}
//******************************************************
// Function to show Elements
//******************************************************
function showEl(id)
{
getEl(id).style.display ="";
}
//******************************************************
// Function to hide Elements
//******************************************************
function hideEl(id)
{
getEl(id).style.display ="none";
}
//******************************************************
// Function to move Element
//******************************************************
function moveEl(id)
{
var popup = getEl(id);
var currentTop = parseInt(popup.offsetTop);
var currentLeft = parseInt(popup.offsetLeft);
var keepMoving = false;
//Move
if (currentTop <= endTop)
{
popup.style.bottom = (currentTop + speed) + "px";
keepMoving = true;
}
if(currentLeft <= endLeft)
{
popup.style.left = (currentLeft + speed) + "px";
keepMoving = true;
}
if (keepMoving)
{
startMove(id);
}
else
{
endMove();
}
}
//******************************************************
// Function to start the move
//******************************************************
function startMove(id)
{
timer = setTimeout("moveEl('"+id+"')", 1);
}
//******************************************************
// Function to end the move
//******************************************************
function endMove()
{
clearTimeout(timer);
}
</script>
</head>
<body onload="startMove('popup');">
<!-- POP UP DIV -->
<div id="popup">
<center><span onclick="hideEl('popup');" style="cursor:pointer;"> Close</span></center>
</div>
<!--END POP UP DIV -->
<center><span onclick="startMove('popup');" style="cursor:pointer;"> Show Pop Up</span></center>
</body>
</html>

You'll just need to rejiggle your inequalities a bit.
Given that there's no offset bottom property in javascript, it'll be easier to still work with top values, even if you want to come in from the bottom.
function moveEl(id) {
var popup = getEl(id);
var currentTop = parseInt(popup.offsetTop);
var currentLeft = parseInt(popup.offsetLeft);
var keepMoving = false;
//Move
if (currentTop >= endTop) {
popup.style.top = (currentTop - speed) + "px";
keepMoving = true;
}
if (currentLeft <= endLeft) {
popup.style.left = (currentLeft + speed) + "px";
keepMoving = true;
}
if (keepMoving) {
startMove(id);
}
else {
endMove();
}
}
Here's a working jsFiddle.
If you think about the way the function is checking to see if it's finished yet, and adding on the speed variable each time, you should be able to step through the original version compared to this and see how the logic is working.

Instead writing something from scratch consider using jQuery's slideToggle method.

Related

I give two div the same style on click of a button and they don't behave the same

I have canvas where I can upload pdf file.On click of a button I can create div with image inside that is called divMark and I can drag that div on canvas.I made zoom functionality where on click of a button I increase width and height on all four sides for 25px and also I change style left and top of divMark. Original coordinates I store in array I have xList for top coordinates and yList for left coordinates and each value in xList I increase for 12 and yList I decrease for 5 then first value form each array I gave to first div second value to second div and so on.
This is code for creating divMark and for zoom functionality:
const myImg = document.getElementById("the-canvas");
const divBtn = document.querySelector(".btn-mark");
const zoomOutBtn = document.querySelector(".zoom-out-btn");
const zoomInBtn = document.querySelector(".zoom-in-btn");
let counter = 0;
let showCounter = 1;
divBtn.addEventListener("click", createContent);
zoomInBtn.addEventListener("click", zoomIn);
zoomOutBtn.addEventListener("click", zoomOut);
function createContent() {
var divMark = document.createElement("div");
divMark.classList = `markers mark`;
divMark.id = `${counter}`;
var img = document.createElement("img");
img.classList = "comment";
img.src = "indeksiraj-1.png";
img.alt = "myimage";
var pCounter = document.createElement("p");
pCounter.classList = "p-counter";
pCounter.innerHTML = showCounter;
divMark.appendChild(pCounter);
divMark.appendChild(img);
$(marksCanvas).append(divMark);
divMarks.push(divMark);
counter++;
showCounter++;
window.onload = addListeners();
function addListeners() {
divMark.addEventListener("mousedown", mouseDown, false);
window.addEventListener("mouseup", mouseUp, false);
}
function mouseUp() {
window.removeEventListener("mousemove", divMove, true);
}
function mouseDown(e) {
window.addEventListener("mousemove", divMove, true);
}
function divMove(e) {
var xCord = e.pageX;
var yCord = e.pageY;
divMark.style.top = yCord + "px";
divMark.style.left = xCord + "px";
divMark.onclick = function () {
divContent.setAttribute("style", "visibility:visible;");
console.log(parseInt(divMark.id));
let index = parseInt(divMark.id);
xList = removeXListItem(index, xList);
xList.splice(parseInt(divMark.id), 0, xCord);
yList.splice(parseInt(divMark.id), 0, yCord);
};
}
}
function xCordPlus(num) {
return num + 22;
}
function yCordPlus(num) {
return num + -8;
}
function xCordMinus(num) {
return num - 22;
}
function yCordMinus(num) {
return num + 8;
}
function removeXListItem(index, xList) {
xList.splice(index, 1);
return xList;
}
function zoomIn() {
var currWidth = myImg.clientWidth;
if (currWidth == 1000) return false;
else {
var currWidth = myImg.clientWidth;
myImg.style.width = currWidth + 100 + "px";
}
xList = xList.map(xCordPlus);
console.log("xList is: " + xList);
yList = yList.map(yCordPlus);
$(".markers").each(function (index) {
$(this).css({ top: yList[index] + "px", left: xList[index] + "px" });
});
}
function zoomOut() {
var currWidth = myImg.clientWidth;
var currHeight = myImg.clientHeight;
if (currWidth == 800) return false;
else {
var currWidth = myImg.clientWidth;
myImg.style.width = currWidth - 100 + "px";
}
xList = xList.map(xCordMinus);
yList = yList.map(yCordMinus);
$(".markers").each(function (index) {
$(this).css({ top: yList[index] + "px", left: xList[index] + "px" });
});
}
My problem is that when I put two divMarks one on the left side of canvas other one on the right side divMark on the right side works great it moves when I click zoomInBtn how is suppose to but divMark on the right side it does not work well it moves to much on the right side it not works like divMark on the right side.
Here is all code: https://jsfiddle.net/SutonJ/thernqmv/13/
You are making the zoom-out-btn class, when hovered, not disabled and active, go down the screen by the length of 12.5% of the size of the html element's font size on line 200 of the CSS in that jsfiddle you posted.
.zoom-out-btn:not(:disabled):hover:active {
transform: scale(1.05) translateY(0.125rem);
}
You are never doing the same for zoom-in-btn. Additionally, the css is quite different for the zoom-in-btn, so you need to add a transition property to that class if you want the on-hover effect to look smooth.

How to get the second animation to start, only after the first animation has finished using Javascript callbacks?

I have two animations which both work, but I'd like to have it so the second animation starts only after the first animation has finished, I tried this with Javascript callbacks but can't seem to get it to work. I'm sure someone can show me how to do this. There must be other ways to do this too? I'd be really interested to find out what they are actually. It's amazing how many different ways there are too do things isn't it.
document.addEventListener("DOMContentLoaded", first, false);
var obj, height, goUp;
function first() {
obj = document.getElementById("thetext");
obj.style.position = "absolute";
obj.style.bottom = "10px";
height = document.body.clientHeight;
goUp = true
second();
}
function second() {
var pos = parseInt(obj.style.bottom, 10);
(goUp) ? pos++ : pos--;
obj.style.bottom = pos + "px";
if (pos < 0) {
goUp = true;
}
if (pos > height) {
goUp = false;
}
if (pos < 0) {
return;
}
setTimeout(second, 10);
}
var objz, width, goRight;
function animatefirst() {
objz = document.getElementById("tues");
objz.style.position = "absolute";
objz.style.left = "10px";
objz.style.bottom = "10px";
width = document.body.clientWidth;
goRight = true;
animatesecond();
}
function animatesecond() {
var position = parseInt(objz.style.left, 10);
(goRight) ? position++ : position--;
objz.style.left = position + "px";
if (position > width) {
goRight = false;
}
if (position < 0) {
goRight = true;
}
if (position < 0) {
return;
}
setTimeout(animatesecond, 10);
}
<body>
<p id="thetext">ANIMATION </p>
<p id="tues"> Tuesday</p>
</body>
I fixed this issue in a simple way, I just put my call to the next function just before the return; which closes the current function. So the call to the next function is not inserted until the part in the code where the first function has finished, to avoid overlapping functions. I'm surprised no one could help with this, but it must be a very busy site :)
if (pos < 0) {
nextfunction();
return;
}

jQuery window in/out of view handler

I want to stop the animation on an HTML page once it is out of view
I tried to use
$(window).focus(function () {
// start animation
}).blur(function () {
// stop animation
});
but this code also stops the animation if it is the background of another window.
Is there an handler for window in/out of view in JS or jQuery?
i.e. something like:
$(window).windowInView(function () {
// start animation
}).windowOutView(function () {
// stop animation
});
There's two ways:
window.requestAnimationFrame()
example taken/modified from linked page
<div id="rec" style="width: 5px; height: 5px; background: black;"></div>
var start = null;
var left=false;
var element = document.getElementById('rec');
element.style.position = 'absolute';
function step(timestamp) {
if (!start) start = timestamp;
if(!left){
var progress = timestamp - start;
element.style.left = Math.min(progress / 10, 600) + 'px';
if (progress < 6000) {
window.requestAnimationFrame(step);
}else{
start = timestamp;
left = true;
window.requestAnimationFrame(step);
}
}else{
var progress = (start+6000)-timestamp;
element.style.left = Math.max(progress / 10, 0) + 'px';
if (progress > 0) {
window.requestAnimationFrame(step);
}else{
start = timestamp;
left=false;
window.requestAnimationFrame(step);
}
}
}
or Page Visibility API
document.addEventListener("visibilitychange", function(){
if (document.hidden) {
console.log('hidden');
}else{
console.log('visible');
}}, false);

Javascript - setInterval() still running after clearInterval() called

I'm making a game with Javascript. I have functions for moving left, right, gravity and down. The gravity function makes the player's location go to the bottom of the screen once it goes off the platform (div). When the gravity() function is called when you are moving right (OnButtonDownr()) it stops the move up from working. What I mean is that when I go right and off the platform and then try to go up it doesn't work but I can go up before I go off the platform. When I try to go up (and it doesn't work) it has a weird effect which looks like its position is being set to 0 but moving up at the same time. My code:
HTML (index.htm):
<html>
<head><link rel='stylesheet' href='style.css'></head>
<body>
<div id='level' class='level'>
<div class='start_platform' id='plat1'></div>
<div class='platform' style='
'></div>
</div>
<img id='player' src='img/player.png' style='height:64px;'></img>
<div class='buttons'>
<button id='moveleft' onmousedown="OnButtonDownl (this)" onmouseup="OnButtonUpl (this)"><--</button>
<button id='moveup' onmousedown="OnButtonDownu (this)" onmouseup="OnButtonUpu (this)">^</button>
<button id='moveright' onmousedown="OnButtonDownr (this)" onmouseup="OnButtonUpr (this)">--></button>
</div>
</body>
<script type='text/javascript' src='scripts/move.js'></script>
<script type='text/javascript' src='scripts/gravity.js'></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
</html>
JS (move.js):
//move left
var elem = document.getElementById("player");
function OnButtonDownl (button) {
var posl = parseInt(document.getElementById("player").style.left, 10) || 0;
window.idl = setInterval(framel, 5);
function framel() {
posl--;
elem.style.left = posl + 'px';
gravityCheck();
}}
function OnButtonUpl (button) {
clearInterval(idl);
}
//move right
var elem = document.getElementById("player");
function OnButtonDownr (button) {
var posr = parseInt(document.getElementById("player").style.left, 10) || 0;
window.idr = setInterval(framer, 5);
function framer() {
posr++;
elem.style.left = posr + 'px';
gravityCheck();
}}
function OnButtonUpr (button) {
clearInterval(idr);
}
//move up
var elem = document.getElementById("player");
function OnButtonDownu () {
var posu = parseInt(document.getElementById("player").style.bottom, 10) || 0;
window.idu = setInterval(frameu, 5);
elem.style.bottom = 0;
function frameu() {
gravity = false;
posu++;
elem.style.bottom = posu + 'px';
}}
function OnButtonUpu (button) {
clearInterval(idu);
}
JS (gravity.js):
var gravity = true;
function gravityCheck() {
var player = parseInt(document.getElementById("player").style.left, 10) || 0;
var plat1 = parseInt(document.getElementById("plat1").style.left, 10) || 0;
var width = player - plat1;
var elem = document.getElementById("player");
var pos = parseInt(document.getElementById("player").style.bottom, 10) || 0;
window.id = setInterval(frame, 5);
function frame() {
if(width > 100 && width < 164) {
if(gravity = true) {
pos--;
elem.style.bottom = pos + 'px';
if(elem.style.bottom = 0) {
clear();
}
}
}
}
function clear() {
clearInterval(id);
}}
How do I fix this. Thanks in advance.
You may not be clearing properly. Before setting interval clear any previously set one.
if(window.idl) clearInterval(window.idl);
window.idl = setInterval(framel, 5);

jQuery: change class after conditional is met

I created this site where you have multiple sliders moving vertically using this example on stackoverflow > here < along with this fiddle.
The site when loaded has an overflow: hidden on the body and position fixed on my main content div(div class="content-fs row"). The idea is that when you first arrive on the page, you scroll through each slide and once you hit the last one, the position changes on the main content div(div class="content-fs row") from fixed to static and the overflow: hidden is removed from the body. I'm having trouble writing the conditional statement that says "if its the last slider, change the position." The jquery below is the code i'm using for the site along with the conditional statement that doesn't work.
Any pointers/advice would be greatly appreciated!
jquery:
function scrollLax(){
/*
initialize
*/
var scrollDown = false;
var scrollUp = false;
var scroll = 0;
var $view = $('#portfolio');
var t = 0;
var h = $view.height() - 250;
$view.find('.portfolio-sliders').each(function() {
var $moving = $(this);
// position the next moving correctly
if($moving.hasClass('from-bottom')) {
$moving.css('top', h); // subtract t so that a portion of the other slider is showing
}
// make sure moving is visible
$moving.css('z-index', 10);
});
var $moving = $view.find('.portfolio-sliders:first-child');
$moving.css('z-index', 10);
/*
event handlers
*/
var mousew = function(e) {
var d = 0;
if(!e) e = event;
if (e.wheelDelta) {
d = -e.wheelDelta/3;
} else if (e.detail) {
d = e.detail/120;
}
parallaxScroll(d);
}
if (window.addEventListener) {
window.addEventListener('DOMMouseScroll', mousew, false);
}
window.onmousewheel = document.onmousewheel = mousew;
/*
parallax loop display loop
*/
window.setInterval(function() {
if(scrollDown)
parallaxScroll(4);
else if(scrollUp)
parallaxScroll(-4);
}, 50);
function parallaxScroll(scroll) {
// current moving object
var ml = $moving.position().left;
var mt = $moving.position().top;
var mw = $moving.width();
var mh = $moving.height();
// calc velocity
var fromBottom = false;
var vLeft = 0;
var vTop = 0;
if($moving.hasClass('from-bottom')) {
vTop = -scroll;
fromBottom = true;
}
// calc new position
var newLeft = ml + vLeft;
var newTop = mt + vTop;
// check bounds
var finished = false;
if(fromBottom && (newTop < t || newTop > h)) {
finished = true;
newTop = (scroll > 0 ? t : t + h);
}
// set new position
$moving.css('left', newLeft);
$moving.css('top', newTop);
// if finished change moving object
if(finished) {
// get the next moving
if(scroll > 0) {
$moving = $moving.next('.portfolio-sliders');
if($moving.length == 0)
$moving = $view.find('.portfolio-sliders:last');
//this is where I am trying to add the if conditional statement.
if ('.portfolio-sliders:last')
$('.content-fs.row').css({'position': 'static'});
if('.portfolio-sliders:last' && (mt == 0))
$('html, body').removeClass('overflow');
} else {
$moving = $moving.prev('.portfolio-sliders');
if($moving.length == 0)
$moving = $view.find('.portfolio-sliders:first-child');
//reverse the logic and if last slide change position
if('.portfolio-sliders:first-child')
$('.content-fs.row').css({'position': 'fixed'});
}
}
// for debug
//$('#direction').text(scroll + "/" + t + " " + ml + "/" + mt + " " + finished + " " + $moving.text());
}
}
Your code as it is simply asks whether .portfolio-sliders:last exists. Seems you should be doing:
if ($moving == $('.portfolio-sliders:last') )
or something along those lines, instead checking whether the active slide is the last.

Categories

Resources