extract a number from a property value - javascript

I am trying to create an animation, when a button is pressed, the div have to move to left 300 px by changing the left-margin,and stop.
I get the left margin value, but when I try to extract 300 px from it, it says that the var moveto is not a number, and current_left_margin`s value is 0px, how can I get this value to be a number, without the px?
here is my full code:
function get_vars() {
elem = document.getElementById('front-slide');
}
window.onload = get_vars;
function vb_anim() {
var interval = setInterval(anim, 10);
var elemstyle = window.getComputedStyle(elem);
var elemvidth = elemstyle.width;
var current_left_margin = elemstyle.getPropertyValue('margin-left');
var moveto = current_left_margin - 300;
console.log('current_left_margin= ' + current_left_margin );
console.log('moveto= ' + moveto );
var pos = 0;
function anim() {
if (pos == moveto) {
clearInterval(interval);
} else {
pos--;
elem.style.marginLeft = pos + 'px';
}
}
}

This should do:
var current_left_margin = parseInt(elemstyle.getPropertyValue('margin-left'));
If not, then:
var current_left_margin = parseInt(elemstyle.getPropertyValue('margin-left').replace('px', ''));

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.

javascript, offsetTop, offsetBottom

I have a paragraph tag in my html id is move, I am trying to move the p tag to slowing fall down while on page load. but my code is not working.......
var speed = 12;
var direction = 1;
var getParagraph = document.getElementById("move");
getParagraph.onmouseover = moving;
function moving() {
var bo = getParagraph.offsetHeight;
var boTop = getParagraph.offsetTop;
var boBottom = boTop + bo;
// When right side of the box goes too far - change direction:
if (boBottom > document.body.offsetHeight) {
direction = -1;
}
// When left side of the box goes too far - change direction:
if (boTop < 0) {
direction = 1;
}
// Recalculate position:
getParagraph.style.Top = (boTop + speed * direction)
}
This is your code with minor changes, and it "works":
JS:
var speed = 12;
var direction = 1;
var getParagraph = document.getElementById("move");
document.getElementById("move").addEventListener("mouseover", moving);
//getParagraph.onmouseover = moving;
function moving() {
console.log("Moving??");
var bo = document.getElementById("move").offsetHeight;
var boTop = document.getElementById("move").offsetTop;
var boBottom = boTop + bo;
// When right side of the box goes too far - change direction:
if (boBottom > document.body.offsetHeight) {
direction = -1;
}
// When left side of the box goes too far - change direction:
if (boTop < 0) {
direction = 1;
}
// Recalculate position:
document.getElementById("move").style.marginTop = (boTop + speed * direction) + "px";
speed++;
}
CSS:
#move {
display : block ;
position : absolute ;
}
Hope it helps.

Javascript help, Trying to animate two different sprites at same time

I need some javascript help. I am trying to set up two sprite animations with different frame rates in two separate div.
Here is a fiddle I started and i am very much stuck.
How do I combine the two div IDs into one statement? OR Should I be using ClassName in the statement to run on both divs?
http://jsfiddle.net/akwilinski/3t7d6qbL/1/
<div id="animate" class="animation"></div>
<div id="animate2" class="animation2"></div>
onload = function startAnimation() {
var frameHeight = 400;
var frames = 27;
var frame = 0;
var div = document.getElementById("animate");
setInterval(function () {
var frameOffset = (++frame % frames) * -frameHeight;
div.style.backgroundPosition = "0px " + frameOffset + "px";
}, 100);
}
Thank you for any assistance!
Simplest way to do this using the method you have already started using is to define 2 new variables, 1 for the second div and one for the second frame count. Then you can just add the call to your function.
Updated js:
onload = function startAnimation() {
var frameHeight = 400;
var frames = 27;
var frame = 0;
var div = document.getElementById("animate");
var div2 = document.getElementById("animate2");
setInterval(function () {
var frameOffset = (++frame % frames) * -frameHeight;
var frameOffset2 = (++frame % frames) * -frameHeight - 10;
div.style.backgroundPosition = "0px " + frameOffset + "px";
div2.style.backgroundPosition = "0px " + frameOffset + "px";
}, 100);
}
Fiddle
http://jsfiddle.net/f4v1vy7x/5/
I made a Can object to store the configuration for each can (so you can have different frameHeights, frames and frameRates.
I used window.requestAnimationFrame because it's far more efficient than setInterval. On each available frame I check whether it's time to animate based on each Can's set frame rate:
var Can = function( selector, frameHeight, frames, frameRate )
{
this.domCan = document.getElementById( selector );
this.frameHeight = frameHeight;
this.frames = frames;
this.frameRate = frameRate;
this.frame = 0;
};
onload = function startAnimation() {
var can1 = new Can( 'animate', 400, 27, 20 );
var can2 = new Can( 'animate2', 400, 27, 100 );
var cans = [ can1, can2 ];
window.requestAnimationFrame( function() {
can1.start = can2.start = new Date();
animate( cans );
} );
};
var animate = function( cans ) {
for( var i = 0; i < cans.length; i++ ) {
var now = new Date();
var can = cans[i];
if( now - can.start >= 1000 / can.frameRate ) {
can.start = now;
var frameOffset = (++can.frame % can.frames) * -can.frameHeight;
can.domCan.style.backgroundPosition = "0px " + frameOffset + "px";
}
}
window.requestAnimationFrame( function() {
animate( cans );
} );
}
You could do something like this:
var div = document.getElementById("animate");
var div2 = document.getElementById("animate2");
function anim(div) {
setInterval(function () {
var frameOffset = (++frame % frames) * -frameHeight;
div.style.backgroundPosition = "0px " + frameOffset + "px";
}, 100);
}
anim(div);
anim(div2);
You could then pass in additional parameters like frameHeight, frame, and frames to further customize each animation.

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.

Event on margin change

I have an element with animated top margin. I need to detect if it isn't too close from the border, and if it is, scroll parent div to lower position, to prevent animated element from hiding. Here is an example:
http://jsfiddle.net/zYYBR/5/
This green box shouldn't be below the red line after clicking the "down" button.
Do you mean this?
var new_margin;
var step = 75;
var limit = $("#max")[0].offsetTop;
$('#down').click(function() {
var goStep = step;
var elHeight = $("#animated")[0].offsetTop + $("#animated")[0].offsetHeight;
if((elHeight + step) > limit)
{
goStep = limit - elHeight;
}
new_margin = goStep + parseInt($('#animated').css('margin-top'));
$("#animated").animate({marginTop: new_margin}, 1000);
});
http://jsfiddle.net/zYYBR/8/
EDIT: Or maybe something like that (of course you can improve the calculation, because currently it's very buggy with scroll):
var new_margin;
var step = 75;
$('#down').click(function () {
scroll(1000);
});
var scrollTimer = null;
$("#container").bind("scroll", function () {
clearTimeout(scrollTimer);
scrollTimer = setTimeout(function () { scroll(1); }, 10);
});
function scroll(speed) {
var scrollStep, animationStep = step;
var currentBoxBottom = $("#animated")[0].offsetTop + $("#animated")[0].offsetHeight;
var nextCurrentBoxBottom = currentBoxBottom + step;
var limit = $("#max")[0].offsetTop + $("#container")[0].scrollTop;
if (nextCurrentBoxBottom > limit) {
if (limit >= $("#container")[0].scrollTop) {
scrollStep = $("#container")[0].scrollTop + nextCurrentBoxBottom - limit;
}
else {
scrollStep = $("#container")[0].scrollTop - nextCurrentBoxBottom - limit;
animationStep = nextCurrentBoxBottom - limit;
}
$("#container")[0].scrollTop = scrollStep;
}
new_margin = animationStep + parseInt($('#animated').css('margin-top'));
$("#animated").animate({ marginTop: new_margin }, speed);
}
http://jsfiddle.net/zYYBR/13/
Do you mean something like this?
I have the same visual result as Alex Dn did, but I added a little extra direction to what I think you're talking about. If it's what you're looking for I'll make updates:
var new_margin;
var step = 75;
var limit = $("#max")[0].offsetTop;
$('#down2').click(function() {
var anim = $("#animated");
var hrOff = $("#max").offset();
var thOff = anim.offset();
new_margin = Math.min(hrOff.top - thOff.top - anim.height(), 75);
console.log(new_margin, hrOff.top, thOff.top);
var st = 0;
if (new_margin < 75) {
st = 75 - new_margin;
//have container scroll by this much?
}
anim.animate({
marginTop: "+=" + new_margin
}, 1000);
});​
​
http://jsfiddle.net/zYYBR/10/

Categories

Resources