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');
}
});
Related
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);
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});
});
Right now the code below floats to the left side of the content and it's visible when you scroll down. So far everything is Okay as long as the window is maximized. But when it's minimized or you increase the zoom the bar shows over the content which I don't want it to. In these cases (minimized window and increased zoom) I'd like the bar to be stuck to left margin so it won't be shown over the content. Obviously the bar must keep being floating to the left and visible when scrolled down (if the window is maximized). What changes do I need to do to accomplish this? Thank you very much for your support in advance!
#pageshare
{
position:fixed;
bottom:15%;
right:10px;
float:left;
border: 1px solid #5c5c5c;
border-radius:5px;
-moz-border-radius:5px;
-webkit-border-radius:5px;
background-color:#e5e5e5;
padding:0 0 2px 0;
z-index:10;}
#pageshare .sbutton
{
float:left;
clear:both;
margin:5px 5px 0 5px;
...
}
You can accomplish this by using JavaScript to modify the attributes of both the main site container as well as the pageshare container. For simplicity, I utilized jQuery.
Adjust Site Margin (jsfiddle)
I created a method that adjusts the site margin based on the amount of space needed by the pageshare container. First, this method calculates the amount of space needed for the pageshare container (based on its width and its left offset) and the amount of space available (the site width subtracted from the window width, normalized to zero if negative). The method then calculates the difference between these two values and applies the value to the left margin of site container. This ensures that the pageshare container does not overlay the content. In addition, the reason I am setting and removing scroll event handlers is because otherwise the pageshare container will still appear over the content on a small window when you scroll left and right (example of issue).
function adjustSiteMarginForPageShare() {
// Get the window dimensions
var windowWidth = $(window).width();
var windowHeight = $(window).height();
// Get the site width
var siteWidth = $('#inner-wrapper').outerWidth();
// Get the pageshare dimensions
var pageshareWidth = $('#pageshare').outerWidth();
var pageshareHeight = $('#pageshare').outerHeight();
// Get the pageshare left offset
var pageshareLeft = $('#pageshare').offset().left;
// Calculate the needed pageshare space
var pageshareSpaceNeeded = pageshareWidth + pageshareLeft;
// Calculate the available pageshare space (division because of centering)
var pageshareSpaceAvailable = (windowWidth - siteWidth) / 2;
// Ensure the minimum available pageshare space as zero
pageshareSpaceAvailable = (pageshareSpaceAvailable > 0) ? pageshareSpaceAvailable : 0;
// If the pageshare space available is less than what is needed
if (pageshareSpaceAvailable <= pageshareSpaceNeeded) {
// Calculate the left margin needed as the difference between the two
var leftMarginNeeded = pageshareSpaceNeeded - pageshareSpaceAvailable;
// Add the left margin needed to the site
$('#inner-wrapper').css('margin-left', leftMarginNeeded);
// Modify the pageshare style
$('#pageshare').css({
'position': 'absolute'
});
// Set the pageshare scroll behavior
$(window).off('scroll.pageshare');
$(window).on('scroll.pageshare', function() {
// Set the bottom to top conversion factor (100% total height - 15% bottom offset = 85% top offset)
var conversionFactor = 0.85;
// Calculate the top offset based on the conversion factor and the pageshare height
var pageshareTopOffset = (conversionFactor * windowHeight) - pageshareHeight;
// Adjust the pageshare top offset by the current scroll amount
pageshareTopOffset += $(window).scrollTop();
$('#pageshare').css({
'top': pageshareTopOffset + 'px',
'bottom': 'auto'
});
});
// Trigger the pageshare scroll handler
$(window).triggerHandler('scroll.pageshare');
} else {
// Reset the pageshare style
$('#pageshare').css({
'position': 'fixed',
'top': 'auto',
'bottom': '15%'
});
// Turn off the pageshare scroll behavior
$(window).off('scroll.pageshare');
}
}
The last step is to call that method, both on page load and every time the window is resized.
// Adjust the content margin for pageshare container on load
adjustSiteMarginForPageShare();
// When the window is resized
$(window).resize(function () {
// Adjust the content margin for the pageshare container
adjustSiteMarginForPageShare();
});
Greeting's
I'am still relatively new to JavaScript and Jquery and I know there has got to be a better method than the one I'am using.
I'am working on a serialScroll implementation. There is a master scrollTo that controls the left/right movement of a number of slides. Each slide contains it's own implementation of a vertical serialScroll. I have the resize on the scrollTo working great and the resize on the vertical works but I can't figure an elegant method for ensuring that on resize the current position remains centered, My current method works but is very inefficient.
$(function(){
var $up = $('#sec1_nav a.up').hide();//up button -- each slide needs it's own unique nav buttons
var $down = $('#sec1_nav a.down');//down button -- each slide needs it's own unique nav buttons
$('#screen1').serialScroll({
target:'#section1',
items:'.item',
prev:'#sec1_nav a.up',
next:'#sec1_nav a.down',
axis:'y',
duration:1000,
force:true,
cylce: false,
onBefore:function( e, elem, $pane, $items, pos ){
$up.add($down).show();
if( pos == 0 )$up.hide();
else if( pos == $items.length -1 )
$down.hide();
// Here's where it get ugly, I'am adding a unique class for each slide to the item's
$('.item').removeClass('pos1'); //Each slides need's it's own class i.e. slide1 = pos1, slide2 = pos2 etc.
$(elem).addClass('pos1');
}
});
$(window).bind("resize", function(){
resize1(); // Same goes for the resize function, each slide need's it's own function.
});
});
function resize1() {
height = $(window).height();
width = $(window).width();
mask_height = height * $('.item').length; // sets the new mask height
// Resize Height of the area
$('.sections').css({height: height, width : width});
$('.item').css({height: height, width : width});
$('#mask').css({height : mask_height, width : width});
$('.sections').scrollTo('.pos1', 0 ); // This issue is where it all fall apart, instead of using serialScroll, i'am stuck using scrollTo to maintain the current slide position.
}
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;
}