jQuery: Animate Margins to Auto? - javascript

I'm trying to animate an image so that it centers itself. Here's the code I'd like to use:
$('#myImage').animate({'margin-right': 'auto'});
But when I do that, it's ignored and doesn't change the margin.
Is there a way to animate a margin to auto, or otherwise center an image?
Thanks!

As 'auto' isn't a number, jQuery cannot animate it.
If you are okay with taking the image out of the flow of the document, you can set position to absolute or fixed and try:
$('#myImage').animate({'left': '50%', 'margin-left': -$('#myImage').width()/2 });

You cannot animate an auto property. To properly animate the element to the center of the screen you will need to position it absolutely (or other) and then calculate the screen size, element size, and scroll position. Here is a another SO answer on something similar. Here is the Fiddle
jQuery.fn.center = function () {
this.css("position","absolute");
var top = ( $(window).height() - this.height() ) / 2+$(window).scrollTop() + "px",
left = ( $(window).width() - this.width() ) / 2+$(window).scrollLeft() + "px";
this.animate({top: top, left: left});
return this;
}
Alternatively if you only want the horizontal alignment you can remove the top from the animate function. And if you really want to get creative you can remove the position:absolute, and reposition margin:auto after the animation in case of screen resizing. See another fiddle.
jQuery.fn.center = function () {
this.css("position","absolute");
var left = ( $(window).width() - this.width() ) / 2+$(window).scrollLeft() + "px";
this.animate({left: left}, function(){
$(this).css({position: 'static', margin: '0 auto'});
});
return this;
}
$('#selector').center();

Expanding on Josiah Ruddell's answer. If you guys need your image to keep its flow in the document, use this modified version of Josiah's answer. My image was originally positioned at margin: 0 -1000px, and slides in to the calculated margin left and right. While keeping its flow in the dom the whole time
jQuery.fn.center = function () {
var margin = ( $(window).width() - this.width() ) / 2;
this.animate({
marginLeft: margin,
marginRight: margin
}, function(){
$(this).css({margin: '0 auto'});
});
return this;
}

Related

Calculate distance to left/right viewport edge on load AND resize

I am trying to calculate the distance of an element to the left (and in another case to the right) edge of the viewport, so I could add it as a negative margin for the element to align with the viewport's edge. So far it works on load, but does some strange calculations when resizing the browser. Do I think something wrong here?
Here's what I use so far:
Right-viewport alignment:
$sidepic_element = jQuery('.right_element');
if($sidepic_element.length) {
jQuery(window).on("load resize", function() {
$offset = $sidepic_element.offset();
$sidepic_margin = -(jQuery(window).width() - ($sidepic_element.offset().left + $sidepic_element.width()));
$sidepic_element.css({
'margin-right': $sidepic_margin
});
});
}
Left-viewport alignment:
$blog_element = jQuery('.left_element');
jQuery(window).on("load resize", function() {
$offset = $blog_element.offset();
$blog_margin = -($blog_element.offset().left - jQuery(window).scrollLeft());
$blog_element.css({
'margin-left': $blog_margin
});
});

How to use jQuery scroll to change the height of an element?

I have a HTML class navigation with the initial height of 100px and min-height is 40px. I want to change the height of the class, based on the scroll (if scroll down than size will decrease and if scroll up than size will increase). I use the following code and it's working perfectly.
$(window).scroll( function() {
if( $('.navigation').offset().top > 50 )
{
$('.navigation').css({
'height' : '40px',
'background' : 'rgba(37, 37, 37, 0.9)'
});
} else {
$('.navigation').css({
'height' : '100px',
'background' : '#b24926'
});
}
});
If I press the keyboard down arrow key two times than navigation class moved from original height to minimum height and if the up arrow key press two times than navigation class moved from minimum height to original height.
But I want to make the scroll more smooth (like 4-5 up or down key presses to reach from one height to another).
For example: initial height is: 100px and minimum height is 30px. Now:
if down arrow key is pressed/mouse wheel is move down one time than height will be 85px, if again down arrow is pressed height will be 70px and so on. That means for each down arrow key is pressed/mouse wheel is move down than height will decrease by 15-20px and for each up arrow key is pressed/mouse wheel is move up, height will increase by 15-20px.
Can anyone tell me how can I do that (without using third party api).
Thanks
You can use simple percent calculation to update height
var limitForMinimalHeight = 400; //after this distance navigation will be minimal height
var maxHeight = 100;
var minHeight = 40;
$(window).scroll( function() {
var screenTop = $(document).scrollTop();
var achievedDistancePercent = Math.min(screenTop*100/limitForMinimalHeight, 100);
var amounToAdd = ((maxHeight - minHeight) * (100 - achievedDistancePercent))/100;
var newHeight = minHeight + amounToAdd;
$('.navigation').height(newHeight);
});
You can test it on JSFiddle
$(document).scroll(function() {
if($(this).scrollTop()>100) {
$('.selector').addClass('scrolled');
}
if($(this).scrollTop()<40) {
$('.selector').removeClass('scrolled');
}
});

followTo issue with higher resolutions

I use this snippet to make an element "stop" at a certain point when scrolling.
$.fn.followTo = function (pos) {
var $this = this,
$window = $(window);
$window.scroll(function (e) {
if ($window.scrollTop() > pos) {
$this.css({
position: 'absolute',
top: pos
});
} else {
$this.css({
position: 'fixed',
top: 0
});
}
});
};
$('#braille').followTo(865);
The problem is that if there's not enough space to scroll (in higher resolutions), it's not positioned correctly.
It's important that you watch these 2 videos to understand how it works.
1920x1080: https://www.youtube.com/watch?v=WjT8FKAKTxA
It's properly positioned.
2775x1514: https://www.youtube.com/watch?v=oqQXm8BsfYA
Here instead as you can see it's not in the right place because there's not enough space to scroll
Resolutions until about 1190px height are ok, with higher resolutions there's this problem.
How can I solve this..? Can I set a followTo starting from the bottom of the page? Or set it in percentage? Or say "if height is > than 1190 just put that there"....
Here is the live webpage. To see what I'm talking about just zoom out like 3 times the resolution of your browser and try to scroll the page. The braille image isn't positioned properly under the music staff and above the yellow paragraph.
The short answer is yes, you can set followTo relative to the bottom of the page using $(document).height() - pos. The basic principle is:
$(window).scrollTop() == $(document).height() - $(window).height()
To change the followTo to work relative to the bottom of the page:
if ($(document).height() - $window.height() - $window.scrollTop() < pos)
To use a percentage you could do the calculation:
var percentageDownPage = $window.scrollTop() / ($(document).height() - $(window).height()) * 100;
if (percentageDownPage > pos) { /* your code*/ }

stick div to screen if bottom of div and screen matches

Hello all I am working on a project where in a page I have to stick the div to screen (disable scrolling) when its bottom is at the bottom of screen. I have two divs in the page and both the divs are of variable height. I want to stick the div2 and scroll the div1.
<script>
var divheight
var scrolltop
var screenheight
if(divheight-scrolltop <= screenheight){
/* now stick the div wherever it is i can not
use fixed position as both the divs are floating and
fixing the position will make it to change the position*/ }
else { /*un stick the div*/ }
</script>
i dont know what to put in if and else please help me
Make a function which fire on scroll. The main aim of the function would be to see the difference between screen height and bottom of the div. Once the difference is less than or equal to zero modify the css position to fixed. This will help you
(function ($) {
$('.DIV1').scroll(function () {
var $this = $(this),
win_ht = $(window).height(),
div_ht = $this.height(),
div_bot = $this.offset().top + div_ht;
if (win_ht - div_bot <= 0) {
$this.css({
'position': 'fixed',
'bottom': '0'
})
}
});
})(jQuery);

element.height returns visible height - I want total?

So apparently this is only happening to me - and I can't think why but if it works, I'm happy :)
I have a full screen slideshow and I have created a function that will vertically center any images that are too large.
function fixImages(){
maxheight = $('.index-slide-container').height();
$('.index-slide-container img').each( function(index, ele){
if (ele.height > maxheight){
offset = ( maxheight - ele.height ) / 2;
$(ele).css('top', offset + 'px');
}
});
}
fixImages();
However, ele.height returns the height of the visible part of the image (the height of it's container, as it has overflow:hidden, even though when I console.log(ele) and expand the element, 'height' is clearly the correct value.
I have also tried $(ele).height(), $(ele).css('height'), $(ele).outerHeight() and ele.clientHeight; all of which return the same.
Thanks
I made some tests, and $('img').height(); is giving me the right height of the picture.
If you wish to center the picture vertically why don't you use the absolute positioning with css like this for example :
.index-slide-container img {
position:absolute;
top:50%;
}
And than, you could set the negative margin programmatically with jQuery :
$('.index-slide-container img').each( function(i, e){
var height = $(e).height() / 2;
$(e).css({'margin-top':'-'+height});
});

Categories

Resources