How can I float an element on scroll, with delay? - javascript

I have the following div floating but I want as the green element inside left panel to have a delay about half second.
Does anyone any idea how can I do this?
https://jsfiddle.net/eoopvgmc/22/
This is the code which is floating the elements on scroll
$(document).ready(function() {
var offset = $('.ads').offset().top, top;
$(document).on('scroll', function() {
top = $(window).scrollTop() < offset ? '0' : $(window).scrollTop() - offset + 'px';
$('.ads').css({
'top': top
});
})
});

To make the .element independent transition, you need to move it out of the .left-zone element.
$(document).ready(function () {
var offset = $('.ads').offset().top,
top;
$(document).on('scroll', function () {
top = $(window).scrollTop() < offset ? '0' : $(window).scrollTop() - offset;
console.log(top);
$('.ads').css({
'top': top
});
$('.element').css({
'top': +top + 50
});
})
});
Working Fiddle

I managed to get something like what you describe working by adding some transition effects to the element and using a little delay, you should be able to tweak the timeout, margin-top and transition values to get exactly what you want:
$(document).ready(function() {
var offset = $('.ads').offset().top, top;
$(document).on('scroll', function() {
top = $(window).scrollTop() < offset ? '0' : $(window).scrollTop() - offset + 'px';
$('.ads .element').css({
'transition': 'none',
'margin-top': '-60px'
});
$('.ads').css({
'top': top
});
setTimeout(function() {
$('.ads .element').css({
'transition': 'margin-top 3s',
'margin-top': '0'
});
});
})
});
Fiddle: https://jsfiddle.net/yckszc16/

Since the element is absolute positioned, I took it that it does not need to be nested within the div. Therefore I changed the HTML from this:
<div class="left-zone ads">
<div class="element"></div>
</div>
to this:
<div class="left-zone ads"></div>
<div class="element"></div>
I then adjusted the css to position the element in the same place as it was, like so:
.element{
position: absolute;
top: 60px;
left: -71px;
width: 20px;
height: 30px;
background: green;
}
This allows the object to be manipulated completely seperately to the parent, which also makes it much more flexible in what you can do with it.
To get the animation going on it, I had to change a few bits of code.
Where you were setting the top variable, I removed the + 'px' at the end to allow for the setting of different values in each animation. This is required because the element must have it's top value (60px in this case) added to the animation to keep it in the correct position. I then copied the code that sets the animation going and repeated it for the 'element' div, and added the 60px to it. if that doesn't make sense then check out the code below.
$(document).on('scroll', function() {
top = $(window).scrollTop() < offset ? '0' : $(window).scrollTop() - offset;
$('.ads').css({
'top': top + 'px'
});
$('.element').css({
'top': top + 60 + 'px'
});
})
Next is to get the delay. I first tried the jquery .delay function but it didn't seem to work so I made an even simpler change, add the transition line from your 'ads' div to the 'element' div's css and change the duration to half a second longer. This achieves the required effect of it coming in afterwards! Here is the code:
.element{
position: absolute;
top: 60px;
left: -71px;
width: 20px;
height: 30px;
background: green;
transition: top 1.3s;
}
Here is a jsfiddle if you want to see it in action: https://jsfiddle.net/hdn1oyjd/
Let me know if you have any questions!

Related

Center DIV horizontal and vertical - jQuery or CSS [duplicate]

How do I go about setting a <div> in the center of the screen using jQuery?
I like adding functions to jQuery so this function would help:
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;
}
Now we can just write:
$(element).center();
Demo: Fiddle (with added parameter)
I put a jquery plugin here
VERY SHORT VERSION
$('#myDiv').css({top:'50%',left:'50%',margin:'-'+($('#myDiv').height() / 2)+'px 0 0 -'+($('#myDiv').width() / 2)+'px'});
SHORT VERSION
(function($){
$.fn.extend({
center: function () {
return this.each(function() {
var top = ($(window).height() - $(this).outerHeight()) / 2;
var left = ($(window).width() - $(this).outerWidth()) / 2;
$(this).css({position:'absolute', margin:0, top: (top > 0 ? top : 0)+'px', left: (left > 0 ? left : 0)+'px'});
});
}
});
})(jQuery);
Activated by this code :
$('#mainDiv').center();
PLUGIN VERSION
(function($){
$.fn.extend({
center: function (options) {
var options = $.extend({ // Default values
inside:window, // element, center into window
transition: 0, // millisecond, transition time
minX:0, // pixel, minimum left element value
minY:0, // pixel, minimum top element value
withScrolling:true, // booleen, take care of the scrollbar (scrollTop)
vertical:true, // booleen, center vertical
horizontal:true // booleen, center horizontal
}, options);
return this.each(function() {
var props = {position:'absolute'};
if (options.vertical) {
var top = ($(options.inside).height() - $(this).outerHeight()) / 2;
if (options.withScrolling) top += $(options.inside).scrollTop() || 0;
top = (top > options.minY ? top : options.minY);
$.extend(props, {top: top+'px'});
}
if (options.horizontal) {
var left = ($(options.inside).width() - $(this).outerWidth()) / 2;
if (options.withScrolling) left += $(options.inside).scrollLeft() || 0;
left = (left > options.minX ? left : options.minX);
$.extend(props, {left: left+'px'});
}
if (options.transition > 0) $(this).animate(props, options.transition);
else $(this).css(props);
return $(this);
});
}
});
})(jQuery);
Activated by this code :
$(document).ready(function(){
$('#mainDiv').center();
$(window).bind('resize', function() {
$('#mainDiv').center({transition:300});
});
);
is that right ?
UPDATE :
From CSS-Tricks
.center {
position: absolute;
left: 50%;
top: 50%;
transform: translate(-50%, -50%); /* Yep! */
width: 48%;
height: 59%;
}
I would recommend jQueryUI Position utility
$('your-selector').position({
of: $(window)
});
which gives you much more possibilities than only centering ...
Here's my go at it. I ended up using it for my Lightbox clone. The main advantage of this solution is that the element will stay centered automatically even if the window is resized making it ideal for this sort of usage.
$.fn.center = function() {
this.css({
'position': 'fixed',
'left': '50%',
'top': '50%'
});
this.css({
'margin-left': -this.outerWidth() / 2 + 'px',
'margin-top': -this.outerHeight() / 2 + 'px'
});
return this;
}
You can use CSS alone to center like so:
Working Example
.center{
position: absolute;
height: 50px;
width: 50px;
background:red;
top:calc(50% - 50px/2); /* height divided by 2*/
left:calc(50% - 50px/2); /* width divided by 2*/
}
<div class="center"></div>
calc() allows you to do basic calculations in css.
MDN Documentation for calc()
Browser support table
I'm expanding upon the great answer given by #TonyL. I'm adding Math.abs() to wrap the values, and also I take into account that jQuery might be in "no conflict" mode, like for instance in WordPress.
I recommend that you wrap the top and left values with Math.abs() as I have done below. If the window is too small, and your modal dialog has a close box at the top, this will prevent the problem of not seeing the close box. Tony's function would have had potentially negative values. A good example on how you end up with negative values is if you have a large centered dialog but the end user has installed several toolbars and/or increased his default font -- in such a case, the close box on a modal dialog (if at the top) might not be visible and clickable.
The other thing I do is speed this up a bit by caching the $(window) object so that I reduce extra DOM traversals, and I use a cluster CSS.
jQuery.fn.center = function ($) {
var w = $(window);
this.css({
'position':'absolute',
'top':Math.abs(((w.height() - this.outerHeight()) / 2) + w.scrollTop()),
'left':Math.abs(((w.width() - this.outerWidth()) / 2) + w.scrollLeft())
});
return this;
}
To use, you would do something like:
jQuery(document).ready(function($){
$('#myelem').center();
});
I would use the jQuery UI position function.
See working demo.
<div id="test" style="position:absolute;background-color:blue;color:white">
test div to center in window
</div>
If i have a div with id "test" to center then the following script would center the div in the window on document ready. (the default values for "my" and "at" in the position options are "center")
<script type="text/javascript">
$(function(){
$("#test").position({
of: $(window)
});
};
</script>
I would like to correct one issue.
this.css("top", ( $(window).height() - this.height() ) / 2+$(window).scrollTop() + "px");
Above code won't work in cases when this.height (lets assume that user resizes the screen and content is dynamic) and scrollTop() = 0, example:
window.height is 600
this.height is 650
600 - 650 = -50
-50 / 2 = -25
Now the box is centered -25 offscreen.
This is untested, but something like this should work.
var myElement = $('#myElement');
myElement.css({
position: 'absolute',
left: '50%',
'margin-left': 0 - (myElement.width() / 2)
});
I dont think having an absolute position would be best if you want an element always centered in the middle of the page. You probably want a fixed element. I found another jquery centering plugin that used fixed positioning. It is called fixed center.
Edit:
If the question taught me anything, it's this: don't change something that already works :)
I'm providing an (almost) verbatim copy of how this was handled on http://www.jakpsatweb.cz/css/css-vertical-center-solution.html - it's heavily hacked for IE but provides a pure CSS way of answering the question:
.container {display:table; height:100%; position:absolute; overflow:hidden; width:100%;}
.helper {#position:absolute; #top:50%;
display:table-cell; vertical-align:middle;}
.content {#position:relative; #top:-50%;
margin:0 auto; width:200px; border:1px solid orange;}
Fiddle: http://jsfiddle.net/S9upd/4/
I've run this through browsershots and it seems fine; if for nothing else, I'll keep the original below so that margin percentage handling as dictated by CSS spec sees the light of day.
Original:
Looks like I'm late to the party!
There are some comments above that suggest this is a CSS question - separation of concerns and all. Let me preface this by saying that CSS really shot itself in the foot on this one. I mean, how easy would it be to do this:
.container {
position:absolute;
left: 50%;
top: 50%;
overflow:visible;
}
.content {
position:relative;
margin:-50% 50% 50% -50%;
}
Right? Container's top left corner would be in the center of the screen, and with negative margins the content will magically reappear in the absolute center of the page! http://jsfiddle.net/rJPPc/
Wrong! Horizontal positioning is OK, but vertically... Oh, I see. Apparently in css, when setting top margins in %, the value is calculated as a percentage always relative to the width of the containing block. Like apples and oranges! If you don't trust me or Mozilla doco, have a play with the fiddle above by adjusting content width and be amazed.
Now, with CSS being my bread and butter, I was not about to give up. At the same time, I prefer things easy, so I've borrowed the findings of a Czech CSS guru and made it into a working fiddle. Long story short, we create a table in which vertical-align is set to middle:
<table class="super-centered"><tr><td>
<div class="content">
<p>I am centered like a boss!</p>
</div>
</td></tr></table>
And than the content's position is fine-tuned with good old margin:0 auto;:
.super-centered {position:absolute; width:100%;height:100%;vertical-align:middle;}
.content {margin:0 auto;width:200px;}​
Working fiddle as promised: http://jsfiddle.net/teDQ2/
The transition component of this function worked really poorly for me in Chrome (didn't test elsewhere). I would resize the window a bunch and my element would sort of scoot around slowly, trying to catch up.
So the following function comments that part out. In addition, I added parameters for passing in optional x & y booleans, if you want to center vertically but not horizontally, for example:
// Center an element on the screen
(function($){
$.fn.extend({
center: function (x,y) {
// var options = $.extend({transition:300, minX:0, minY:0}, options);
return this.each(function() {
if (x == undefined) {
x = true;
}
if (y == undefined) {
y = true;
}
var $this = $(this);
var $window = $(window);
$this.css({
position: "absolute",
});
if (x) {
var left = ($window.width() - $this.outerWidth())/2+$window.scrollLeft();
$this.css('left',left)
}
if (!y == false) {
var top = ($window.height() - $this.outerHeight())/2+$window.scrollTop();
$this.css('top',top);
}
// $(this).animate({
// top: (top > options.minY ? top : options.minY)+'px',
// left: (left > options.minX ? left : options.minX)+'px'
// }, options.transition);
return $(this);
});
}
});
})(jQuery);
To center the element relative to the browser viewport (window), don't use position: absolute, the correct position value should be fixed (absolute means: "The element is positioned relative to its first positioned (not static) ancestor element").
This alternative version of the proposed center plugin uses "%" instead of "px" so when you resize the window the content is keep centered:
$.fn.center = function () {
var heightRatio = ($(window).height() != 0)
? this.outerHeight() / $(window).height() : 1;
var widthRatio = ($(window).width() != 0)
? this.outerWidth() / $(window).width() : 1;
this.css({
position: 'fixed',
margin: 0,
top: (50*(1-heightRatio)) + "%",
left: (50*(1-widthRatio)) + "%"
});
return this;
}
You need to put margin: 0 to exclude the content margins from the width/height (since we are using position fixed, having margins makes no sense).
According to the jQuery doc using .outerWidth(true) should include margins, but it didn't work as expected when I tried in Chrome.
The 50*(1-ratio) comes from:
Window Width: W = 100%
Element Width (in %): w = 100 * elementWidthInPixels/windowWidthInPixels
Them to calcule the centered left:
left = W/2 - w/2 = 50 - 50 * elementWidthInPixels/windowWidthInPixels =
= 50 * (1-elementWidthInPixels/windowWidthInPixels)
This is great. I added a callback function
center: function (options, callback) {
if (options.transition > 0) {
$(this).animate(props, options.transition, callback);
} else {
$(this).css(props);
if (typeof callback == 'function') { // make sure the callback is a function
callback.call(this); // brings the scope to the callback
}
}
What I have here is a "center" method that ensures the element you are attempting to center is not only of "fixed" or "absolute" positioning, but it also ensures that the element you are centering is smaller than its parent, this centers and element relative to is parent, if the elements parent is smaller than the element itself, it will pillage up the DOM to the next parent, and center it relative to that.
$.fn.center = function () {
/// <summary>Centers a Fixed or Absolute positioned element relative to its parent</summary>
var element = $(this),
elementPos = element.css('position'),
elementParent = $(element.parent()),
elementWidth = element.outerWidth(),
parentWidth = elementParent.width();
if (parentWidth <= elementWidth) {
elementParent = $(elementParent.parent());
parentWidth = elementParent.width();
}
if (elementPos === "absolute" || elementPos === "fixed") {
element.css('right', (parentWidth / 2) - elementWidth / 2 + 'px');
}
};
CSS solution
In two lines only
It centralize your inner div horizontally and vertically.
#outer{
display: flex;
}
#inner{
margin: auto;
}
for only horizontal align, change
margin: 0 auto;
and for vertical, change
margin: auto 0;
i use this:
$(function() {
$('#divId').css({
'left' : '50%',
'top' : '50%',
'position' : 'absolute',
'margin-left' : -$('#divId').outerWidth()/2,
'margin-top' : -$('#divId').outerHeight()/2
});
});
Please use this:
$(window).resize(function(){
$('.className').css({
position:'absolute',
left: ($(window).width() - $('.className').outerWidth())/2,
top: ($(window).height() - $('.className').outerHeight())/2
});
});
// To initially run the function:
$(window).resize();
you're getting that poor transition because you're adjusting the position of the element every time the document is scrolled. What you want is to use fixed positioning. I tried that fixed center plugin listed above and that seems to do solve the problem nicely. Fixed positioning allows you to center an element once, and the CSS property will take care of maintaining that position for you every time you scroll.
Here is my version. I may change it after I look at these examples.
$.fn.pixels = function(property){
return parseInt(this.css(property));
};
$.fn.center = function(){
var w = $($w);
return this.each(function(){
$(this).css("position","absolute");
$(this).css("top",((w.height() - $(this).height()) / 2) - (($(this).pixels('padding-top') + $(this).pixels('padding-bottom')) / 2) + w.scrollTop() + "px");
$(this).css("left",((w.width() - $(this).width()) / 2) - (($(this).pixels('padding-left') + $(this).pixels('padding-right')) / 2) + w.scrollLeft() + "px");
});
};
No need jquery for this
I used this to center Div element.
Css Style,
.black_overlay{
display: none;
position: absolute;
top: 0%;
left: 0%;
width: 100%;
height: 100%;
background-color: black;
z-index:1001;
-moz-opacity: 0.8;
opacity:.80;
filter: alpha(opacity=80);
}
.white_content {
display: none;
position: absolute;
top: 25%;
left: 25%;
width: 50%;
height: 50%;
padding: 16px;
border: 16px solid orange;
background-color: white;
z-index:1002;
overflow: auto;
}
Open element
$(document).ready(function(){
$(".open").click(function(e){
$(".black_overlay").fadeIn(200);
});
});
MY UPDATE TO TONY L'S ANSWER
This is the modded version of his answer that I use religiously now. I thought I would share it, as it adds slightly more functionality to it for various situations you may have, such as different types of position or only wanting horizontal/vertical centering rather than both.
center.js:
// We add a pos parameter so we can specify which position type we want
// Center it both horizontally and vertically (dead center)
jQuery.fn.center = function (pos) {
this.css("position", pos);
this.css("top", ($(window).height() / 2) - (this.outerHeight() / 2));
this.css("left", ($(window).width() / 2) - (this.outerWidth() / 2));
return this;
}
// Center it horizontally only
jQuery.fn.centerHor = function (pos) {
this.css("position", pos);
this.css("left", ($(window).width() / 2) - (this.outerWidth() / 2));
return this;
}
// Center it vertically only
jQuery.fn.centerVer = function (pos) {
this.css("position", pos);
this.css("top", ($(window).height() / 2) - (this.outerHeight() / 2));
return this;
}
In my <head>:
<script src="scripts/center.js"></script>
Examples of usage:
$("#example1").centerHor("absolute")
$("#example2").centerHor("fixed")
$("#example3").centerVer("absolute")
$("#example4").centerVer("fixed")
$("#example5").center("absolute")
$("#example6").center("fixed")
It works with any positioning type, and can be used throughout your entire site easily, as well as easily portable to any other site you create. No more annoying workarounds for centering something properly.
Hope this is useful for someone out there! Enjoy.
Lot's of ways to do this. My object is kept hidden with display:none just inside the BODY tag so that positioning is relative to the BODY. After using $("#object_id").show(), I call $("#object_id").center()
I use position:absolute because it is possible, especially on a small mobile device, that the modal window is larger than the device window, in which case some of the modal content could be inaccessible if positioning was fixed.
Here's my flavor based on other's answers and my specific needs:
$.fn.center = function () {
this.css("position","absolute");
//use % so that modal window will adjust with browser resizing
this.css("top","50%");
this.css("left","50%");
//use negative margin to center
this.css("margin-left",(-1*this.outerWidth()/2)+($(window).scrollLeft())+"px");
this.css("margin-top",(-1*this.outerHeight()/2)+($(window).scrollTop())+"px");
//catch cases where object would be offscreen
if(this.offset().top<0)this.css({"top":"5px","margin-top":"0"});
if(this.offset().left<0)this.css({"left":"5px","margin-left":"0"});
return this;
};
You could use the CSS translate property:
position: absolute;
transform: translate(-50%, -50%);
Read this post for more details.
Normally, I would do this with CSS only... but since you asked you a way to do this with jQuery...
The following code centers a div both horizontally and vertically inside its container :
$("#target").addClass("centered-content")
.wrap("<div class='center-outer-container'></div>")
.wrap("<div class='center-inner-container'></div>");
body {
margin : 0;
background: #ccc;
}
.center-outer-container {
position : absolute;
display: table;
width: 100%;
height: 100%;
}
.center-inner-container {
display: table-cell;
vertical-align: middle;
text-align: center;
}
.centered-content {
display: inline-block;
text-align: left;
background: #fff;
padding : 20px;
border : 1px solid #000;
}
<script type="text/javascript" src="https://code.jquery.com/jquery-1.12.1.min.js"></script>
<div id="target">Center this!</div>
(see also this Fiddle)
Just say:
$("#divID").html($('').html($("#divID").html()));
It can be done with only CSS. But they asked with jQuery or JavaScript
Here, use CSS Flex box property to align the div center.
body.center{
display:flex;
align-items:center; // Vertical alignment
justify-content:center; // Horizontal alignment
}
align-items:center; - used to align vertically.
justify-content:center; - used to align horizontally.
document.querySelector("body").classList.add("center");
body {
margin : 0;
height:100vh;
width:100%;
background: #ccc;
}
#main{
background:#00cc00;
width:100px;
height:100px;
}
body.center{
display:flex;
align-items:center;
justify-content:center;
}
<body>
<div id="main"></div>
</body>
I used this to put the UL in the middle position.
cadasWidth = $('.card-dashboard').innerWidth();
cadasWidthCenter = cadasWidth/2;
ulmenuWidth = $('.card-dashboard ul#menu').outerWidth();
ulmenuWidthCenter = ulmenuWidth/2;
ulmenuStart = cadasWidthCenter - ulmenuWidthCenter;
$('.card-dashboard ul#menu').css({
'left' : ulmenuStart,
'position' : 'relative'
});
Why you don't use CSS for centering a div?
#timer_wrap{
position: fixed;
left: 50%;
top: 50%;
}

make div scoll untill it reaches top of page then fixed

let's get straight to the point:
My code looks like the following:
<div id="keep_up">
<div id="thread_menu">
<div id="new_thread">
</div>
</div>
</div>
And my css:
#keep_up {
position: fixed;
width: 13%;
}
#thread_menu{
height: 80vh;
width: 100%;
float: left;
position: relative;
}
Now i use this for a forum. and this is basically to show the active and new threads on the side of the screen.
However. When watching a thread, the header disappears (Wich makes sense because we are scrolling down).
but i want the thread menu to stay on my side (So that it is always visible). In this case that is happening because my keep_up div has position: fixed. But i only see half of the thread menu becuase it is too long and won't scroll up.
My question:
I want the thread menu to scroll up, untill it reaches the top of my window. From then on i want it to stay there.
How do i do this?
I saw a few examples but none of them worked for me.
EDIT: Code i tried:
<script src="jquery.min.js">
$(window).scroll(function () {
var margin = null;
$(window).on("scroll", function () {
var scrollHeight = $(document).height(),
scrollTop = $(window).scrollTop(),
offsetBottom = 110, // Offset depending on the height of the footer
offsetTop = 100, // Offset depending on the height of the header
positionTop = $(".keep_up").offset().top,
affix;
if (margin != null && (scrollTop + margin <= positionTop)) {
// The sidebar has reached the bottom and is still on the bottom
affix = false;
} else if (positionTop + $(".keep_up").height() >= scrollHeight - offsetBottom) {
// The sidebar has reached the bottom
affix = 'bottom';
} else if (scrollTop <= offsetTop) {
// The sidebar has reached the top
affix = 'top';
} else {
// The sidebar is midway
affix = false;
}
// If the sidebar hasnot changed his state, return;
if ($(".keep_up").hasClass('at' + (affix ? '-' + affix : ''))) return;
if (affix == 'bottom') {
margin = positionTop - scrollTop;
} else {
margin = null;
}
// If the related class is added to the div
$(".keep_up").removeClass('at at-top at-bottom').addClass('at' + (affix ? '-' + affix : ''))
});
});
</script>
And the CSS:
.keep_up{
/*position: fixed;*/
width: 13%;
}
.keep_up.at {
top: 1px;
position: fixed;
}
.keep_up.at-top{
}
.keep_up.at-bottom {
top: 438px;
position: absolute;
}
modify this on HTML:
<div id="prevent"></div>
<div id="keep_up" data-spy="affix" data-offset-top="200">
Add this CSS:
.affix{position: fixed !important; top:0px; z-index:999;}
.affixpatch{margin-top:100px !important;}
this will fix the div when you scroll down 200px. Change data-offset-top value to reach it on different break point.
.affixpatch is a class that will be loaded with next jquery function. it prevents to hide content behind top fixed div. Change margin-top to another value if this don't solves the "hide content" problem that always generate affixing divs.
<script>
$(function() {
//caches a jQuery object containing the header element
var header = $(".affix");
$(window).scroll(function() {
var scroll = $(window).scrollTop();
if (scroll >= 200) {
$('#prevent').addClass("affixpatch");
} else {
$('#prevent').removeClass("affixpatch");
}
});
});
</script>
Hope it helps. If not, you may have some class that rewrite or impede the correct function of this affix.
I've tested this hundreds of times, usually to fix navbars.
SCROLL:
Using overflow to scroll content:
#keep_up{
max-height:400px;
width: auto;
overflow:auto;}
This will scroll the content inside #keep_up div (or use it in another one)
NOTE: you must declare a fixed max height for this div. Set max-width only if you need.
You can use %, em, rem... no need to be px for fix the max witdth. (to get a responsive effect, use responsive measurements)
If I understand your scenario correctly, the way to do this might be to use jQuery (or native JS, but you've tagged jQuery so I'm assuming that's in play).
There's a plugin that handles this kind of thing: http://leafo.net/sticky-kit/
I'd suggest you look at the plugin source code to see how it works - an event handler function on $(window).scroll() which then toggles classes on your #thread_menu to fix it in place. To keep your code lightweight, you probably don't need everything the plugin provides.

Image animate down javascript (no jQuery)

I know how to fix the animation that goes down only when the image is showing up in the window with jQuery, but now I want to do that with JavaScript. Struggling with that. The image must be fluently go down (+50px for 1.6 seconds). Have googling around, but most of them are done with jQuery I suggest and that is not what I want. Furtermore the animation should start when the scrollTop is between 600px and 800px.
function scrollFunction() {
var animate = document.getElementById("picture");
var position = 0;
var top = 0;
var scrollTop = window.pageYOffset || document.documentElement.scrollTop;
if(scrollTop > 600 && scrollTop < 800){
position++;
animate.style.top = position + "50px";
} else {
stop();
}
}
function stop() {
clearTimeout(animate);
}
#picture {
width: 100%;
height: auto;
top: -5px;
position: relative;
display: block;
margin-left: auto;
margin-right: auto;
margin-bottom: 20px;
}
<div class="col-sm-12 col-xs-12">
<h1 class="responsive-h1">Mi<span class="logo-orange"> Pad2</span></h1>
<p class="edition-title above-text-black">Black Edition</p>
<img src="Img/picture.jpg" id="picture"/>
</div>
jsFiddle : https://jsfiddle.net/n1q3fy8w/
Javascript
var imgSlide = document.getElementById('slidedown-image');
var slideDown = setInterval(function() {
var topVal = parseInt(window.getComputedStyle(imgSlide).top, 10);
imgSlide.style.top = (topVal + 1) + "px";
}, 15);
setTimeout(function( ) { clearInterval( slideDown ); }, 1600);
You get the element first, after that you setup a setInterval which will basically move our img downwards, we then also set a setTimeout which after 1600ms remvoes the slideDown interval and the image stops. Your image however may need position: absolute.
The above answer will only work in Chrome, this however should work in all browswers
jsFiddle : https://jsfiddle.net/n1q3fy8w/1/
javascript
var imgSlide = document.getElementById('slidedown-image');
var slideDown = setInterval(function() {
var topVal = parseInt(imgSlide.style.top, 10);
imgSlide.style.top = (topVal + 1) + "px";
}, 15);
setTimeout(function( ) { clearInterval( slideDown ); }, 1600);
Ok so getComputedStyle only works in chrome, so to get this to work on all other browsers, you have to specifically set the css property on the element and not via CSS.
When you use javascript to access an element and change its style like so element.style.bottom = '150px' the .style gets you all of the css values for your inline styles on that element, so any css changes on an element that is done via a .css/.less file you can't access via javascript.
So all the above code does is we set a top: 0 on the element itself and in our code we use imageSlide.style.top instead of chrome's window.getComputedStyle
Have you considered using a CSS transition? if you are changing the value of top you should be able to add transition: top 1.6s in your css (to picture). (Then the vendor prefixed versions when you get it working)

How do you make a floating sidebar like envato?

I really like the floating panel on the left side of the following site:
http://envato.com/
I have no idea what its called, but I like how when you click on the search button, it expands to a search page, you click on another icon, and it expands with what appears like its own page.
How do I accomplish this? Is there some tutorial out there using html5, JavaScript or jQuery?
NOTE: All the answers so far only cover the floating bar, but not the clicking on a link on that floating bar to show a window expanded to the right.
<div id="float"></div>
#float{
position:fixed;
top:50px;
left:0;
}
Check working example at http://jsfiddle.net/TVwAv/
done using css,
HTML
<div id="floating_sidebar">
whatever you want to put here
</div>
CSS
#floating_sidebar {
position:fixed;
left: 0;
top: 100px; /* change to adjust height from the top of the page */
}
I am using this for a "floating (sticky) menu". What I have added is:
1. to avoid my 'footer' always being "scrolled" down in case the sidemenu is a little high, I only do the scrolling if necessary, i.e -
when the content is higher than the sidebar.
2. I found the animate effect a little "jumpy" to my taste, so I just changed the css through jquery. of-course you put a 0 in the animate time, but the animation still occurs, so it's cleaner and faster to use the css.
3. 100 is the height of my header. you can assume it to be the "threshold" of when to do the scrolling.
$(window).scroll(function(){
if ($('#sidebar').height() < $('#content').height())
{
if ($(this).scrollTop() > 90)
$('#sidebar').css({"margin-top": ($(this).scrollTop()) - 100 });
//$('#sidebar').animate({"marginTop": ($(this).scrollTop()) - 100 }, 0);
else
$('#sidebar').css({"margin-top": ($(this).scrollTop()) });
//$('#sidebar').animate({"marginTop": ($(this).scrollTop()) }, 0);
}
});`
you can use this ..
your html div is here
<div id="scrolling_div">Your text here</div>
And you javascript function is here
$(window).scroll(function(){
$('#scrolling_div').stop().animate({"marginTop": ($(this).scrollTop()) +10+ "px"}, "slow"});
});
You can also use the css for this
#scrolling_div {
position:absolute;
left: 0;
top: 100px;
}
I have not tested it but hopefully its worked.
I know this looks quite a big piece of code, however this function just works by specifying three simple options; your floater "top", your "target" (floater) and "reference" element to set the boundaries, it also takes care of the top and bottom position automatically, no css involved.
function scrollFloater(marginTop, reference, target, fixWhidth = false){
var processScroll = function(){
var from = reference.offset().top - marginTop;
var to = reference.offset().top + reference.outerHeight() + marginTop - target.outerHeight();
var scrollTop = $(this).scrollTop();
var bottom = to - reference.offset().top + marginTop;
if( fixWhidth )
target.css('width', target.width());
if( scrollTop > from && scrollTop < to )
target.css('position', 'fixed').css('top',marginTop);
else if( scrollTop >= to )
target.css('position', 'absolute').css('top', bottom);
else
target.css('position', '').css('top',marginTop);
}
$(window).scroll(function(){ processScroll(); });
processScroll();
}
And this is how you would use it:
$(function() {
scrollFloater(41, $('.box.auth.register'), $('.plans-floater'), true);
});
I hope this helps someone.

Using jQuery to center a DIV on the screen

How do I go about setting a <div> in the center of the screen using jQuery?
I like adding functions to jQuery so this function would help:
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;
}
Now we can just write:
$(element).center();
Demo: Fiddle (with added parameter)
I put a jquery plugin here
VERY SHORT VERSION
$('#myDiv').css({top:'50%',left:'50%',margin:'-'+($('#myDiv').height() / 2)+'px 0 0 -'+($('#myDiv').width() / 2)+'px'});
SHORT VERSION
(function($){
$.fn.extend({
center: function () {
return this.each(function() {
var top = ($(window).height() - $(this).outerHeight()) / 2;
var left = ($(window).width() - $(this).outerWidth()) / 2;
$(this).css({position:'absolute', margin:0, top: (top > 0 ? top : 0)+'px', left: (left > 0 ? left : 0)+'px'});
});
}
});
})(jQuery);
Activated by this code :
$('#mainDiv').center();
PLUGIN VERSION
(function($){
$.fn.extend({
center: function (options) {
var options = $.extend({ // Default values
inside:window, // element, center into window
transition: 0, // millisecond, transition time
minX:0, // pixel, minimum left element value
minY:0, // pixel, minimum top element value
withScrolling:true, // booleen, take care of the scrollbar (scrollTop)
vertical:true, // booleen, center vertical
horizontal:true // booleen, center horizontal
}, options);
return this.each(function() {
var props = {position:'absolute'};
if (options.vertical) {
var top = ($(options.inside).height() - $(this).outerHeight()) / 2;
if (options.withScrolling) top += $(options.inside).scrollTop() || 0;
top = (top > options.minY ? top : options.minY);
$.extend(props, {top: top+'px'});
}
if (options.horizontal) {
var left = ($(options.inside).width() - $(this).outerWidth()) / 2;
if (options.withScrolling) left += $(options.inside).scrollLeft() || 0;
left = (left > options.minX ? left : options.minX);
$.extend(props, {left: left+'px'});
}
if (options.transition > 0) $(this).animate(props, options.transition);
else $(this).css(props);
return $(this);
});
}
});
})(jQuery);
Activated by this code :
$(document).ready(function(){
$('#mainDiv').center();
$(window).bind('resize', function() {
$('#mainDiv').center({transition:300});
});
);
is that right ?
UPDATE :
From CSS-Tricks
.center {
position: absolute;
left: 50%;
top: 50%;
transform: translate(-50%, -50%); /* Yep! */
width: 48%;
height: 59%;
}
I would recommend jQueryUI Position utility
$('your-selector').position({
of: $(window)
});
which gives you much more possibilities than only centering ...
Here's my go at it. I ended up using it for my Lightbox clone. The main advantage of this solution is that the element will stay centered automatically even if the window is resized making it ideal for this sort of usage.
$.fn.center = function() {
this.css({
'position': 'fixed',
'left': '50%',
'top': '50%'
});
this.css({
'margin-left': -this.outerWidth() / 2 + 'px',
'margin-top': -this.outerHeight() / 2 + 'px'
});
return this;
}
You can use CSS alone to center like so:
Working Example
.center{
position: absolute;
height: 50px;
width: 50px;
background:red;
top:calc(50% - 50px/2); /* height divided by 2*/
left:calc(50% - 50px/2); /* width divided by 2*/
}
<div class="center"></div>
calc() allows you to do basic calculations in css.
MDN Documentation for calc()
Browser support table
I'm expanding upon the great answer given by #TonyL. I'm adding Math.abs() to wrap the values, and also I take into account that jQuery might be in "no conflict" mode, like for instance in WordPress.
I recommend that you wrap the top and left values with Math.abs() as I have done below. If the window is too small, and your modal dialog has a close box at the top, this will prevent the problem of not seeing the close box. Tony's function would have had potentially negative values. A good example on how you end up with negative values is if you have a large centered dialog but the end user has installed several toolbars and/or increased his default font -- in such a case, the close box on a modal dialog (if at the top) might not be visible and clickable.
The other thing I do is speed this up a bit by caching the $(window) object so that I reduce extra DOM traversals, and I use a cluster CSS.
jQuery.fn.center = function ($) {
var w = $(window);
this.css({
'position':'absolute',
'top':Math.abs(((w.height() - this.outerHeight()) / 2) + w.scrollTop()),
'left':Math.abs(((w.width() - this.outerWidth()) / 2) + w.scrollLeft())
});
return this;
}
To use, you would do something like:
jQuery(document).ready(function($){
$('#myelem').center();
});
I would use the jQuery UI position function.
See working demo.
<div id="test" style="position:absolute;background-color:blue;color:white">
test div to center in window
</div>
If i have a div with id "test" to center then the following script would center the div in the window on document ready. (the default values for "my" and "at" in the position options are "center")
<script type="text/javascript">
$(function(){
$("#test").position({
of: $(window)
});
};
</script>
I would like to correct one issue.
this.css("top", ( $(window).height() - this.height() ) / 2+$(window).scrollTop() + "px");
Above code won't work in cases when this.height (lets assume that user resizes the screen and content is dynamic) and scrollTop() = 0, example:
window.height is 600
this.height is 650
600 - 650 = -50
-50 / 2 = -25
Now the box is centered -25 offscreen.
This is untested, but something like this should work.
var myElement = $('#myElement');
myElement.css({
position: 'absolute',
left: '50%',
'margin-left': 0 - (myElement.width() / 2)
});
I dont think having an absolute position would be best if you want an element always centered in the middle of the page. You probably want a fixed element. I found another jquery centering plugin that used fixed positioning. It is called fixed center.
Edit:
If the question taught me anything, it's this: don't change something that already works :)
I'm providing an (almost) verbatim copy of how this was handled on http://www.jakpsatweb.cz/css/css-vertical-center-solution.html - it's heavily hacked for IE but provides a pure CSS way of answering the question:
.container {display:table; height:100%; position:absolute; overflow:hidden; width:100%;}
.helper {#position:absolute; #top:50%;
display:table-cell; vertical-align:middle;}
.content {#position:relative; #top:-50%;
margin:0 auto; width:200px; border:1px solid orange;}
Fiddle: http://jsfiddle.net/S9upd/4/
I've run this through browsershots and it seems fine; if for nothing else, I'll keep the original below so that margin percentage handling as dictated by CSS spec sees the light of day.
Original:
Looks like I'm late to the party!
There are some comments above that suggest this is a CSS question - separation of concerns and all. Let me preface this by saying that CSS really shot itself in the foot on this one. I mean, how easy would it be to do this:
.container {
position:absolute;
left: 50%;
top: 50%;
overflow:visible;
}
.content {
position:relative;
margin:-50% 50% 50% -50%;
}
Right? Container's top left corner would be in the center of the screen, and with negative margins the content will magically reappear in the absolute center of the page! http://jsfiddle.net/rJPPc/
Wrong! Horizontal positioning is OK, but vertically... Oh, I see. Apparently in css, when setting top margins in %, the value is calculated as a percentage always relative to the width of the containing block. Like apples and oranges! If you don't trust me or Mozilla doco, have a play with the fiddle above by adjusting content width and be amazed.
Now, with CSS being my bread and butter, I was not about to give up. At the same time, I prefer things easy, so I've borrowed the findings of a Czech CSS guru and made it into a working fiddle. Long story short, we create a table in which vertical-align is set to middle:
<table class="super-centered"><tr><td>
<div class="content">
<p>I am centered like a boss!</p>
</div>
</td></tr></table>
And than the content's position is fine-tuned with good old margin:0 auto;:
.super-centered {position:absolute; width:100%;height:100%;vertical-align:middle;}
.content {margin:0 auto;width:200px;}​
Working fiddle as promised: http://jsfiddle.net/teDQ2/
The transition component of this function worked really poorly for me in Chrome (didn't test elsewhere). I would resize the window a bunch and my element would sort of scoot around slowly, trying to catch up.
So the following function comments that part out. In addition, I added parameters for passing in optional x & y booleans, if you want to center vertically but not horizontally, for example:
// Center an element on the screen
(function($){
$.fn.extend({
center: function (x,y) {
// var options = $.extend({transition:300, minX:0, minY:0}, options);
return this.each(function() {
if (x == undefined) {
x = true;
}
if (y == undefined) {
y = true;
}
var $this = $(this);
var $window = $(window);
$this.css({
position: "absolute",
});
if (x) {
var left = ($window.width() - $this.outerWidth())/2+$window.scrollLeft();
$this.css('left',left)
}
if (!y == false) {
var top = ($window.height() - $this.outerHeight())/2+$window.scrollTop();
$this.css('top',top);
}
// $(this).animate({
// top: (top > options.minY ? top : options.minY)+'px',
// left: (left > options.minX ? left : options.minX)+'px'
// }, options.transition);
return $(this);
});
}
});
})(jQuery);
To center the element relative to the browser viewport (window), don't use position: absolute, the correct position value should be fixed (absolute means: "The element is positioned relative to its first positioned (not static) ancestor element").
This alternative version of the proposed center plugin uses "%" instead of "px" so when you resize the window the content is keep centered:
$.fn.center = function () {
var heightRatio = ($(window).height() != 0)
? this.outerHeight() / $(window).height() : 1;
var widthRatio = ($(window).width() != 0)
? this.outerWidth() / $(window).width() : 1;
this.css({
position: 'fixed',
margin: 0,
top: (50*(1-heightRatio)) + "%",
left: (50*(1-widthRatio)) + "%"
});
return this;
}
You need to put margin: 0 to exclude the content margins from the width/height (since we are using position fixed, having margins makes no sense).
According to the jQuery doc using .outerWidth(true) should include margins, but it didn't work as expected when I tried in Chrome.
The 50*(1-ratio) comes from:
Window Width: W = 100%
Element Width (in %): w = 100 * elementWidthInPixels/windowWidthInPixels
Them to calcule the centered left:
left = W/2 - w/2 = 50 - 50 * elementWidthInPixels/windowWidthInPixels =
= 50 * (1-elementWidthInPixels/windowWidthInPixels)
This is great. I added a callback function
center: function (options, callback) {
if (options.transition > 0) {
$(this).animate(props, options.transition, callback);
} else {
$(this).css(props);
if (typeof callback == 'function') { // make sure the callback is a function
callback.call(this); // brings the scope to the callback
}
}
What I have here is a "center" method that ensures the element you are attempting to center is not only of "fixed" or "absolute" positioning, but it also ensures that the element you are centering is smaller than its parent, this centers and element relative to is parent, if the elements parent is smaller than the element itself, it will pillage up the DOM to the next parent, and center it relative to that.
$.fn.center = function () {
/// <summary>Centers a Fixed or Absolute positioned element relative to its parent</summary>
var element = $(this),
elementPos = element.css('position'),
elementParent = $(element.parent()),
elementWidth = element.outerWidth(),
parentWidth = elementParent.width();
if (parentWidth <= elementWidth) {
elementParent = $(elementParent.parent());
parentWidth = elementParent.width();
}
if (elementPos === "absolute" || elementPos === "fixed") {
element.css('right', (parentWidth / 2) - elementWidth / 2 + 'px');
}
};
CSS solution
In two lines only
It centralize your inner div horizontally and vertically.
#outer{
display: flex;
}
#inner{
margin: auto;
}
for only horizontal align, change
margin: 0 auto;
and for vertical, change
margin: auto 0;
i use this:
$(function() {
$('#divId').css({
'left' : '50%',
'top' : '50%',
'position' : 'absolute',
'margin-left' : -$('#divId').outerWidth()/2,
'margin-top' : -$('#divId').outerHeight()/2
});
});
Please use this:
$(window).resize(function(){
$('.className').css({
position:'absolute',
left: ($(window).width() - $('.className').outerWidth())/2,
top: ($(window).height() - $('.className').outerHeight())/2
});
});
// To initially run the function:
$(window).resize();
you're getting that poor transition because you're adjusting the position of the element every time the document is scrolled. What you want is to use fixed positioning. I tried that fixed center plugin listed above and that seems to do solve the problem nicely. Fixed positioning allows you to center an element once, and the CSS property will take care of maintaining that position for you every time you scroll.
Here is my version. I may change it after I look at these examples.
$.fn.pixels = function(property){
return parseInt(this.css(property));
};
$.fn.center = function(){
var w = $($w);
return this.each(function(){
$(this).css("position","absolute");
$(this).css("top",((w.height() - $(this).height()) / 2) - (($(this).pixels('padding-top') + $(this).pixels('padding-bottom')) / 2) + w.scrollTop() + "px");
$(this).css("left",((w.width() - $(this).width()) / 2) - (($(this).pixels('padding-left') + $(this).pixels('padding-right')) / 2) + w.scrollLeft() + "px");
});
};
No need jquery for this
I used this to center Div element.
Css Style,
.black_overlay{
display: none;
position: absolute;
top: 0%;
left: 0%;
width: 100%;
height: 100%;
background-color: black;
z-index:1001;
-moz-opacity: 0.8;
opacity:.80;
filter: alpha(opacity=80);
}
.white_content {
display: none;
position: absolute;
top: 25%;
left: 25%;
width: 50%;
height: 50%;
padding: 16px;
border: 16px solid orange;
background-color: white;
z-index:1002;
overflow: auto;
}
Open element
$(document).ready(function(){
$(".open").click(function(e){
$(".black_overlay").fadeIn(200);
});
});
MY UPDATE TO TONY L'S ANSWER
This is the modded version of his answer that I use religiously now. I thought I would share it, as it adds slightly more functionality to it for various situations you may have, such as different types of position or only wanting horizontal/vertical centering rather than both.
center.js:
// We add a pos parameter so we can specify which position type we want
// Center it both horizontally and vertically (dead center)
jQuery.fn.center = function (pos) {
this.css("position", pos);
this.css("top", ($(window).height() / 2) - (this.outerHeight() / 2));
this.css("left", ($(window).width() / 2) - (this.outerWidth() / 2));
return this;
}
// Center it horizontally only
jQuery.fn.centerHor = function (pos) {
this.css("position", pos);
this.css("left", ($(window).width() / 2) - (this.outerWidth() / 2));
return this;
}
// Center it vertically only
jQuery.fn.centerVer = function (pos) {
this.css("position", pos);
this.css("top", ($(window).height() / 2) - (this.outerHeight() / 2));
return this;
}
In my <head>:
<script src="scripts/center.js"></script>
Examples of usage:
$("#example1").centerHor("absolute")
$("#example2").centerHor("fixed")
$("#example3").centerVer("absolute")
$("#example4").centerVer("fixed")
$("#example5").center("absolute")
$("#example6").center("fixed")
It works with any positioning type, and can be used throughout your entire site easily, as well as easily portable to any other site you create. No more annoying workarounds for centering something properly.
Hope this is useful for someone out there! Enjoy.
Lot's of ways to do this. My object is kept hidden with display:none just inside the BODY tag so that positioning is relative to the BODY. After using $("#object_id").show(), I call $("#object_id").center()
I use position:absolute because it is possible, especially on a small mobile device, that the modal window is larger than the device window, in which case some of the modal content could be inaccessible if positioning was fixed.
Here's my flavor based on other's answers and my specific needs:
$.fn.center = function () {
this.css("position","absolute");
//use % so that modal window will adjust with browser resizing
this.css("top","50%");
this.css("left","50%");
//use negative margin to center
this.css("margin-left",(-1*this.outerWidth()/2)+($(window).scrollLeft())+"px");
this.css("margin-top",(-1*this.outerHeight()/2)+($(window).scrollTop())+"px");
//catch cases where object would be offscreen
if(this.offset().top<0)this.css({"top":"5px","margin-top":"0"});
if(this.offset().left<0)this.css({"left":"5px","margin-left":"0"});
return this;
};
You could use the CSS translate property:
position: absolute;
transform: translate(-50%, -50%);
Read this post for more details.
Normally, I would do this with CSS only... but since you asked you a way to do this with jQuery...
The following code centers a div both horizontally and vertically inside its container :
$("#target").addClass("centered-content")
.wrap("<div class='center-outer-container'></div>")
.wrap("<div class='center-inner-container'></div>");
body {
margin : 0;
background: #ccc;
}
.center-outer-container {
position : absolute;
display: table;
width: 100%;
height: 100%;
}
.center-inner-container {
display: table-cell;
vertical-align: middle;
text-align: center;
}
.centered-content {
display: inline-block;
text-align: left;
background: #fff;
padding : 20px;
border : 1px solid #000;
}
<script type="text/javascript" src="https://code.jquery.com/jquery-1.12.1.min.js"></script>
<div id="target">Center this!</div>
(see also this Fiddle)
Just say:
$("#divID").html($('').html($("#divID").html()));
It can be done with only CSS. But they asked with jQuery or JavaScript
Here, use CSS Flex box property to align the div center.
body.center{
display:flex;
align-items:center; // Vertical alignment
justify-content:center; // Horizontal alignment
}
align-items:center; - used to align vertically.
justify-content:center; - used to align horizontally.
document.querySelector("body").classList.add("center");
body {
margin : 0;
height:100vh;
width:100%;
background: #ccc;
}
#main{
background:#00cc00;
width:100px;
height:100px;
}
body.center{
display:flex;
align-items:center;
justify-content:center;
}
<body>
<div id="main"></div>
</body>
I used this to put the UL in the middle position.
cadasWidth = $('.card-dashboard').innerWidth();
cadasWidthCenter = cadasWidth/2;
ulmenuWidth = $('.card-dashboard ul#menu').outerWidth();
ulmenuWidthCenter = ulmenuWidth/2;
ulmenuStart = cadasWidthCenter - ulmenuWidthCenter;
$('.card-dashboard ul#menu').css({
'left' : ulmenuStart,
'position' : 'relative'
});
Why you don't use CSS for centering a div?
#timer_wrap{
position: fixed;
left: 50%;
top: 50%;
}

Categories

Resources