Centering DIV Horizontally & Vertically on Page Load - javascript

How can I center a DIV both horizontally and vertically immediately when the page loads?
I am currently using the following solution:
HTML:
<div class="container">
<div class="visitorSelect">
<a href="/visitorLog/boeing">
<div class="tile double icon bg-color-blue">
<div class="tile-content">
<i class="icon-plane"></i>
</div>
<div class="brand">
<span class="name">Employee</span>
</div>
</div>
</a>
<a href="/visitorLog/guest">
<div class="tile double icon bg-color-orange">
<div class="tile-content">
<i class="icon-group"></i>
</div>
<div class="brand">
<span class="name">Guest</span>
</div>
</div>
</a>
</div> <!-- visitorSelect -->
</div> <!-- container -->
JavaScript:
<script>
$(document).ready(function()
{
$(window).resize(function()
{
$('.visitorSelect').css(
{
position: 'absolute',
left: ($(window).width() - $('.visitorSelect').outerWidth()) / 2,
top: ($(window).height() - $('.visitorSelect').outerHeight()) / 2
});
});
// call `resize` to center elements
$(window).resize();
});
</script>
When I initially load the page, the DIV to center shows up at the right of the page and slightly below the center of vertical. However, when I resize the page manually it snaps to exactly where it should.
What additional steps do I need to take to cause the centering properly place the element at the time the document loads?

Set the .visitor element to absolute positioning before you calculate the width.
By default static divs will stretch to the full width of the parent; absolute divs will not. This is messing up your first calculation.
You should probably set the position css rule outside of the resize event function, in either CSS or in the ready() function. Here's a fix with the least changes to your code:
$(document).ready(function()
{
$(window).resize(function()
{
$('.visitorSelect').css(
{
position: 'absolute'
});
$('.visitorSelect').css(
{
left: ($(window).width() - $('.visitorSelect').outerWidth()) / 2,
top: ($(window).height() - $('.visitorSelect').outerHeight()) / 2
});
});
// call `resize` to center elements
$(window).resize();
});

Unless this is some kind of modal, or something unusual, I would not do this entirely with script when CSS Margin Auto will work for this. Here is a tutorial http://demo.tutorialzine.com/2010/03/centering-div-vertically-and-horizontally/demo.html
Here is an example of the CSS:
div.container{
width:100%;
height:100%;
}
div.visitorSelect {
width:200px;
height:200px;
margin:auto;
}

You should position the div once the page loads:
<script>
$(document).ready(function()
{
$('.visitorSelect').css(
{
position: 'absolute',
left: ($(window).width() - $('.visitorSelect').outerWidth()) / 2,
top: ($(window).height() - $('.visitorSelect').outerHeight()) / 2
});
$(window).resize(function()
{
$('.visitorSelect').css(
{
position: 'absolute',
left: ($(window).width() - $('.visitorSelect').outerWidth()) / 2,
top: ($(window).height() - $('.visitorSelect').outerHeight()) / 2
});
});
// call `resize` to center elements
$(window).resize();
});
</script>

Related

Can't figure out how to scroll down/up by 50px in js when i click a button

This is the code I have currently. What I want to do, is when I click a button - Move up- I want the text in area3 to move up by 50px. But right now its moving all the way back up to the top. This is for a h/w assignment and we're doing pretty basic js/jquery if that needs to be said? :) Any help will be appreciated! Thanks!
$("#moveUp").click(function(event){
event.preventDefault();
var scrollPos = $(".area").scrollTop();
var newPos = scrollPos - 50;
$(".area3").scrollTop(newPos);
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="area3">
blah blah
</div>
<div class="area4">
<button id="moveUp">Move Up</button>
</div>
If I'm not wrong, I think this could help you:
$("#moveup").click(function(){
$(".area3").css({"margin-top":"-=50px"});
});
$("#moveUp").click(function(event){
window.scrollTo(0, window.scrollY - 50)
})
window.scrollTo(x, y) is a method which will scroll the screen to given coordinates where x is horizontal and y vertical. The top left corner of the screen is 0, 0. Than window.scrollY gets the current vertical position of the screen, you just need to subtract 50 to scroll 50px up from your current position
if you want just the text in area3 to move you should use some css to correctly implement this behavior with jQuery, using animate() to add some ease with smooth animation to the text.
$("#moveUp").click(function(event){
event.preventDefault();
$('.area3').animate({
position: 'absolute',
bottom: +50
}, 'slow');
})
.area3 {
position: relative;
height: 200px;
}
.area3 span {
position: absolute;
bottom: 50px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="area3">
<span>blah blah</span>
</div>
<div class="area4">
<button id="moveUp">Move Up</button>
</div>
but if you want the whole window to scroll you can do that as following we using the same approach with different selectors body and html
$("#moveUp").click(function(event){
event.preventDefault();
$('body, html').animate({
scrollTop: -50
}, 500);
})
body, html {
height: 1000px
}
.area3 {
margin-top: 100px
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="area3">
<span>blah blah</span>
</div>
<div class="area4">
<button id="moveUp">Move Up</button>
</div>
if you wanna to do it with window interface you can occur that by changing the above code to
$("#moveUp").click(function(event){
event.preventDefault();
window.scrollTo(0, -50);
})
with this approach using window you can make it moving smoothly like we did above you can't use jQuery animate() API javascript gonna raise an error don't do that.

Repositioning element on scroll with jQuery

I am trying to reposition an element on scroll using jQuery scroll event and just adjusting margin-top property.Element is inside bootstrap nav so its showed along all other elements inside nav on desktop and for mobiles its just fixed positioned in upper left corner.element contains two flag links for different page languages.
My code is:
Html:
<div class="navbar yamm navbar-default">
<div class="flags">
<img src="UK_flag.png" alt="English">
<img src="DK_flag.png" alt="Danish">
</div>
<div class="navbar-header">
....
js:
var scrollingDiv = $(".flags").offset().top - $(window).scrollTop();
$(window).scroll(function(){
if(scrollingDiv > 100) {
$(".flags").css("margin-top", "24px");
}
if(scrollingDiv == 92) {
$(".flags").css("margin-top", "10px");
}
console.log(scrollingDiv);
});
console log displays always 92 as its position.One note page contains 1 more navigation which is above bootstrap nav so I need this margin-top fix for that.Whan nav goes down it reposition itself nicely,but whan it comes back it keeps margin-top property at 10px and flags jump out of aligment.
Thanks for all future ansers :)
Put var scrollingDiv = $(".flags").offset().top - $(window).scrollTop(); this inside you're $(window).scroll(function(){});
When you declare it like its current state. The scrollingDiv will keep 92px because it only sets it on page load.
If inside the scroll() function, it will update the value when the user is scrolling.
Small Demo (I dont know you're actual layout)
$(window).scroll(function(){
var scrollingDiv = $(".flags").offset().top - $(window).scrollTop();
if(scrollingDiv > 100) {
$(".flags").css("margin-top", "24px");
}
if(scrollingDiv >= 92 && scrollingDiv < 100) {
$(".flags").css("margin-top", "10px");
}
console.log(scrollingDiv);
});
.scroll-container {
height: 2000px;
overflow: auto;
}
.scroll-container .flags {
position: relative;
top: 120px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="scroll-container">
<div class="flags">
<img src="UK_flag.png" alt="English">
<img src="DK_flag.png" alt="Danish">
</div>
</div>

Sticky header after some scrolling?

okay here's an example of what i am trying to ask,
the nav bar of usatoday.
I'm using bootstrap affix. here's my code
<div class="header">
<div class="header-1">
<h1>this is some logo</h1>
</div>
<div class="header-2">
<h3>this is some heading</h3>
</div>
</div>
<div class="content" style="height:2500px;">
</div>
<div class="footer">
this is a footer
</div>
JavaScript
$('.header-2').affix({
});
how can I make the div header-2 to be fixed on the top, (when there is some scrolling and the div header-2 just reach the top position) as of the site I've mentioned earlier?
I would love to see the header-1 and header-2, but some scrolling should hide header-1 and stick header-2 to the top most.
thanks
See this Jsfiddle
you can check the position of the slider and add class accordingly
$(window).scroll(function () {
if( $(window).scrollTop() > $('#header-2').offset().top && !($('#header-2').hasClass('posi'))){
$('#header-2').addClass('posi');
} else if ($(window).scrollTop() == 0){
$('#header-2').removeClass('posi');
}
});
use jquery look at this example
http://jsfiddle.net/5n5MA/2/
var fixmeTop = $('.fixme').offset().top; // Get initial position
$(window).scroll(function() { // Assign scroll event listener
var currentScroll = $(window).scrollTop(); // Get current position
if (currentScroll >= fixmeTop) { // Make it fixed if you've scrolled to it
$('.fixme').css({
position: 'fixed',
top: '0',
left: '0'
});
} else { // Make it static if you scroll above
$('.fixme').css({
position: 'static'
});
}
});
Bootstrapped answer using Bootstrap.affix()
$('.header-2').affix({
offset: {
top: function () {
return (this.top = $(".header-2").offset().top);
}
}
});
This also needs CSS for the fixed positioning (see the Docs).
The affix plugin toggles between three classes, each representing a
particular state: .affix, .affix-top, and .affix-bottom. You must
provide the styles for these classes yourself (independent of this
plugin) to handle the actual positions.
.header-2.affix {
top: 0;
}
Working example at Bootply: http://www.bootply.com/S03RlcT0z0
<style>
.header {
top: 0%;
left: 0%;
width: 100%;
position:fixed;
}
</style>
I'm sorry didnt look at your problem carefully.
This may helps you Issue with Fixed Header and Bootstrap Affix / Scrollspy - Not jumping to correct location

jquery animate a div to the center

html:
<div id="container">
<div id="header">
<div id="animate">
cartagena
</div>
</div>
what I want to do is to move the "animated" div to the center using Jquery.
my current js:
$(document).ready(function() {
$("#animate").animate({left: "+=512"}, 2000);
});
and now I'd like to make it to the center instead of just 512 px to the right.
I am assuming that the position of #animate is absolute. To center the element in its parent element just add the half of its parent's width minus the half of its own width to left:
$("#animate").animate({
left: $("#animate").parent().width() / 2 - $("#animate").width() / 2
}, 2000);
I created a demo using jsFiddle.
You can use it this way to center it to the screen,
Jquery
$(document).ready(function() {
$("#animate").animate({left: $(window).width() / 2}, 2000);
});
css
<style type="text/css">
div
{
height: 50px; width: 50px; background-color: Red;position:absolute; top:0; left:0;
}
</style>
html
<div id="container">
<div id="header">
<div id="animate">
cartagena
</div>
</div>
</div>
Asuming you want to center to window, use this code:
$("#myJQUIDialog").parent().position({
my: "center",
at: "center",
of: window,
using: function (pos, ext) {
$(this).animate({ top: pos.top }, 600);
}
});
This center the dialog, and animate at the same time, resulting in a smooth centering
Here it is other example, maybe it should be useful.
I am using 'scroll' to make the effects.
Hope it could help or be useful :)...
<http://jsfiddle.net/p609dm7y/2/>

lightbox top margin chaging after once scrolling down and again up

I'm using a lightbox to display comments with photo. The problem is that when I scroll down to see the lightbox, and scroll back to the top, the top margin changes even after specifying the top.
My jQuery code to specify top and left is :
jQuery.fn.center = function() {
this.css("position","fixed");
var top = "20px";
left = ( $(window).width() - this.width() ) / 2+$(window).scrollLeft()+"px";
this.animate({top: top, left: left});
return this;
}
$('#tp-lightboxactitem').center();
Here is the HTML for the lightbox div:
<div class="dark-lightbox lightboxitem tp-lightboxactitem-loaded" id="tp-lightboxactitem" style="display: block; top: 20px; left: 314.5px; position: fixed; margin-top: 30px;">
<div>
<center>
<img src="uploads/_DSC9322_watcopy_bor_5_$1$uh2.fw5.$uFln.yw5QjSgVKjmhD8.jpg?id=3&amp‌​;pic=113" class="tp-mainimage" id="plzxc">
</center>
</div>
<div class="dark-lightbox infofield">
<div class="dark-lightbox title"></div>
<div class="dark-lightbox pageofformat">( 1 / 5 )</div>
<div class="dark-lightbox description" id="dark-lightbox description">
How it appears before scrolling
![How it appears before scrolling][1]
How it appears after scrolling down and then up again
![How it appears after scrolling down and then up again][2]
Got this fixed by doing small changes
here is the code hope it helps some one in need
cssAnimate({'left':($(window).width()/2 - thisw/2)+'px', 'top':'20px' },{duration:300,queue:false});
Try using something like this. Hope it resolves it.
$("#YourDivID").animate({"marginTop": ($(window).scrollTop() + 30) + "px"}, "slow" );

Categories