Animating the centering of a div - javascript

How do I animate this movement so when I call the function later the item will animate? I usually use $(this).animate but not sure how to wrap this in it, since I'm calculating its position. Thanks.
jQuery.fn.center = function ()
{
this.css("position","absolute");
this.css("top", Math.max(0, (($(window).height() - $(this).outerHeight()) / 2) +
$(window).scrollTop()) + "px");
this.css("left", Math.max(0, (($(window).width() - $(this).outerWidth()) / 2) +
$(window).scrollLeft()) + "px");
return this;
}

Instead of using this.css you can use this.animate as you mentioned.
Example
this.animate({
top : Math.max(0, (($(window).height() - $(this).outerHeight()) / 2) +
$(window).scrollTop()) + "px"
},800,function(){ });
Demo

To animate, you'll need to use animate on the left/top values, but first set the position to absolute using css().
// can't easily animate change of css "position"
// so we just set it directly
elt.css('position', 'absolute');
// animate the position
elt.animate({
left: x,
top: y
});
I created a fiddle for this, here: http://jsfiddle.net/lingo/CkRUd/2/
In the fiddle I've also tidied some things up to make sure the plugin is more robust.

Related

Height 100vh - height of other element in JavaScript

I have this code:
document.querySelector('.saved').style.height = '100vh' - document.querySelector('.header').offsetHeight + 'px';
I want to make the div.saved have height 100vh - height of div.header. The code on top doesn't work. What do I do?
you can use build-in css function calc
document.querySelector('.saved').style.height = 'calc(100vh - ' + document.querySelector('.header').offsetHeight + 'px)';
You are missing a calculate call in CSS. Your code does not make the browser aware of the fact that it has to calculate the height of the element.
Something like
document.querySelector('.saved').style.height = 'calc(100vh - ' + document.querySelector('.header').offsetHeight + 'px)';
should work.

Javascript drag from mouse position?

I have a script which allows a user to drag a div around the screen on iOS, and as it is now, when you start to drag a div, it makes the dragable point the center. Is it possible to make this point wherever the user touches?
The code looks like this:
xPos = drag.offsetWidth / 2;
yPos = drag.offsetHeight / 2;
drag.addEventListener("touchmove", function() {
event.preventDefault();
$(this).css({
"left" : event.targetTouches[0].pageX - xPos + "px",
"top" : event.targetTouches[0].pageY - yPos + "px",
"z-index" : "1000"
});
$("div").not(this).css("z-index", "1");
$("div[id]").each(function() {
var id = $(this).attr("id");
localStorage.setItem(id + "-z","1");
});
});
Is there anyway I can make it so that the offset is however far away the user's finger is away from the box's edge?
I thought the following might work but it doesn't seem to, all it does is cause it to jitter:
$(this).css({
"left" : event.targetTouches[0].pageX - parseInt($(this).css("left"), 10) + "px",
"top" : event.targetTouches[0].pageY - parseInt($(this).css("top"), 10) + "px",
});
Figured it out. After testing, the following only produced the number of pixels from the left or top of the parent.
event.targetTouches[0].pageX - $(this).offset().left
The trick was to subtract that FROM event.targetTouches[0].pageX, which is the number of pixels that the finger is from the edge of the screen.
So, the completed code would look like this:
drag.addEventListener("touchstart", function() {
left = event.targetTouches[0].pageX - $(this).offset().left;
top = event.targetTouches[0].pageY - $(this).offset().top;
});
drag.addEventListener("touchmove", function() {
$(this).css({
"left" : event.targetTouches[0].pageX - left + "px",
"top" : event.targetTouches[0].pageY - top + "px",
});
});

Determining the distance between the top of the page and the bottom of a div

Using jQuery, how do I determine the height/distance between the very top of the browser window to the bottom of a div, such as a header. I'm using the following code:
$(window).resize(function() {
$totalHeight = $(window).height();
$headerHeight = $('header').height();
$('#portfolio-info').css('height',($totalHeight - $headerHeight - 105) + 'px');
});
And I want to make sure that $headerHeight isn't always the same value, as you scroll away from the header it should decrease all the way down to zero.
Thanks!
This should work out for you.
$(window).resize(function() {
var top = $(this).scrollTop(),
bottomDiv = $('div').offset().top + $('div')[0].offsetHeight,
distance = Math.max(0, (top - bottomDiv) * -1);
});

Trying to make a div appear in the centre of a scrollable page - bug in my code?

Just as a preface to make sure I am clear, I don't want the div to appear dead centre in the middle of the page, I want it in the middle of the viewable window. So if you imagine a long page and the user has scrolled down to near the bottom and clicks the button the div will appear in the centre of the screen near the bottom of the page.
here is my code, which doesn't work in chrome:
function centerdiv() {
var scrolledX, scrolledY;
scrolledX = document.body.scrollLeft;
scrolledY = document.body.scrolltop;
var centerX, centerY;
centerX = document.body.clientWidth;
centerY = document.body.clientHeight;
var leftoffset = scrolledX + (centerX - 100) / 2;
var topoffset = scrolledY + (centerY - 100) / 2;
$('.current div[name="popup"]').css({'top' : topoffset + 'px', 'left':
leftoffset + 'px'});}
$(function() {
$("html").ajaxStart(function() {
centerdiv();
$(".current div[name=popup]").show();
});
$("html").ajaxComplete(function() {
$(".current div[name=popup]").hide();
});
});
Note, this is for an iphone mobile website and the ajaxstart function attaching to the html is crucial as it doesn't work on the iphone any other way on my website.
You forget to set position to absolute, or fixed
$('.current div[name="popup"]').css({'top' : topoffset + 'px', 'left':
leftoffset + 'px', 'position':'absolute' });}
Here is my solution that works fine:
var winH = $(window).height();
var winW = $(window).width();
$(this).css('top', winH/2 - $(this).height()/2);
$(this).css('left', winW/2 - $(this).width()/2);
$(this).show();
$(this) must refer to the DIV element you want to show in the center.
wh = $(window).height();
dh = $("#div").height();
$("#div").css("top",(wh - dh)/ 2 + $(window).scrollTop() + 'px');
Edit:
Not the same for width, it's actually:
ww = $(width).width();
dw = $("#div").width();
$("#div").css("left",(ww - dw)/ 2 + 'px');
But it really depends if you have a fixed viewport or not, there are many ways to center it...
Good Luck!
If you don't have horizontal scrolling you can do it partially with straight CSS
div{
left: 50%;
margin-left: -[box_width / 2]px;
}

Moving a picture around slowly

I have a picture of an Air balloon. I need it to fly around my page randomly (it is kind of small). I need it only to fly in the top half of my page. I found the following code:
$("#Friends").animate({
top: "-=30px",
}, duration );
But I'm not sure how I could loop it and have it go both on the x axis and the y axis. Thanks if you can! I do have jQuery enabled :)
How about something like this.... LIVE FIDDLE
HTML
<img src="http://www.birdsnways.com/imgs/blbd48rt.gif" id="picture" />
CSS
#picture{
position:absolute;
}
JS
doNextPoint();
function doNextPoint(){
var maxX = $(window).width() - $('#picture').width();
var newX = rand(0, maxX);
var maxY = ($(window).height()/2) - $('#picture').height();
var newY = rand(0, maxY);
var speed = rand (1000, 3000);
$('#picture').animate({
'top': newY + 'px',
'left': newX + 'px'
}, speed, function(){
doNextPoint();
});
}
function rand (min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
CSS
#friends { position: absolute; }
Markup
<img src="http://jsfiddle.net/img/logo.png"
id="friends"/>
JS
function moveit() {
var newTop = Math.floor(Math.random()*350);
var newLeft = Math.floor(Math.random()*1024);
var newDuration = Math.floor(Math.random()*5000);
$('#friends').animate({
top: newTop,
left: newLeft,
}, newDuration, function() {
moveit();
});
}
$(document).ready(function() {
moveit();
});
Live demo:
http://jsfiddle.net/W69s6/embedded/result/
More updated Live Demo: http://jsfiddle.net/9cN4C/
(old demo is obsolete and has a broken link, however the code is still correct so it is left for reference, not for demonstration)
You can stick that code into a named function, and then add that function as the callback parameter for the animation, so it will call itself again after it finishes.
var flying;
flying = function() {
$("#Friends").animate({
top: "-=30px", // you'll need to change this
},
duration,
flying
);
}
flying();
As is, it will just keep flying upward because the animation is always set to go up by 30 px. You'll have to change the flying function to randomize the motions a bit. For more realism, save the previous movement, and just change it by a little (small acceleration) so it doesn't have very jerky motions.
To loop it: use SetTimeout: https://developer.mozilla.org/en/window.setTimeout
For the x-axis, use the CSS property left: (top: will get you y-axis)

Categories