fixed div only vertically with jquery - javascript

I want fixed an div or image in left of html page, and when scroll y, image scroll, but when scroll x image not scroll or fixed in left, I use jquery.sticky-kit.js and jquery-scrolltofixed.js plugin but when page resize to small width (mobile size) scroll x that, note that my page not responsive.
Another note that a mootools plugin is that work well, but I want do this in jquery.
Mootools plugin is in this link: http://demo.rickyh.co.uk/css-position-x-and-position-y/

HTML:
<div id="content"></div>
CSS:
#content {
width:50px;
height:50px;
background:#ccc;
position:fixed;
top:50px;
left:50px;
}
jQuery:
$(window).scroll(function () {
var content = $("#content");
var windowWidth = $(window).width()
content.css("top",-$(window).scrollTop() + 50) // 50 is initial top position
// if the window width is smaller than 600px - scroll also x-asis
if (windowWidth < 600) {
content.css("left",-$(window).scrollLeft() + 50) // 50 is initial left position
} else {
content.css("left", "50px") // 50 is initial top position
}
});
Fiddle: http://jsfiddle.net/n4we5xma/3/

Use CSS position property : horizontal fixed ,vertical relative
.scroll_fixed {
position:absolute;
}
See a working example

Related

Changing to fixed positioning when scroll position is at bottom

Basically, I am checking to see if the scroll position is at the bottom of the page and adding and remove a class based on that. However when removing the fixed class I can't scroll to the bottom of the page. The browser already assumes I am at the bottom. How can I correct this? If this doesn't make sense please let me know. Below is my code:
JavaScript :
function fixedToRelative(){
var scrollPos = $(window).scrollTop() + $(window).height();
if(scrollPos == $(document).height()) {
$('.mobile.full').removeClass('fixed');
} else {
$('.mobile.full').addClass('fixed');
}
}
Css :
.mobile { position:relative; }
.mobile.fixed { position:fixed; bottom:0; left:0; right:0; }
I think you are trying to append add the .fixed class when you scroll to the bottom of the page. If so, you could do something like:
Codepen
$(window).on('scroll', function(){
var scrollPos = $(this).scrollTop() + $(this).height(); // Current Scroll position plus height of window
var atBottom = (scrollPos == $(document).height()); // Returns true/false based on if at bottom
$('.mobile').toggleClass('fixed', atBottom); // If at bottom of page, fixed class is appended
});

Button sticks to bottom of page jQuery

So I did not find anything related to this, only making the button scrolls down to bottom of page on click but I already got this.
My problem is:
I got an 'Explore Button' on top a slide show that when you click on it the page scrolls down, the thing is, in some screens the slideshow is bigger than the size of the window so you can't see the button unless you scroll down (therefore no point in having the button). I fixed it by adding:
$(document).ready(function() {
var slideHeight = $('.item').height();
var headerHeight = $('header').height();
var windowHeight = $(window).height();
$('.exploreImage').css('bottom', (Math.max(headerHeight + slideHeight, windowHeight) - windowHeight) + 20 + "px");
});
But now when I scroll down I want the button to scroll down and stay at the bottom of the window (until a certain height which is the end of the slide show).
I've got so far something similar which is:
$(window).on('scroll', function() {
$('.exploreImage').css('bottom', 0 + "px");
});
But this puts the button at the bottom of the slide show when it scrolls and not bottom of the windows as I want to!
Notice: I need to get this done with jQuery.
Thanks for your help guys!
EDIT: fiddle: https://jsfiddle.net/1fr27eLu/7/ but the jQuery doesn't seem to work there!
When combined with the other answer, you could use a form of throttle along with the animate() method.
I haven't got it perfect, but hopefully you'll see the value.
$(window).scroll( $.throttle( 250, btnScroll ) );
jsFiddle Demo
Resources:
http://benalman.com/projects/jquery-throttle-debounce-plugin/
https://css-tricks.com/the-difference-between-throttling-and-debouncing/
http://www.paulirish.com/2009/throttled-smartresize-jquery-event-handler/ (see bottom comments)
This is a poor example, but it may give you something to start with. Incorrect positioning of button has something to do with this:
https://api.jquery.com/scrollTop/
The vertical scroll position is the same as the number of pixels that are hidden from view above the scrollable area. If the scroll bar is at the very top, or if the element is not scrollable, this number will be 0.
Anyway, here is the sample code that might put you onto the right track:
var screenWidth = Math.max(document.documentElement.clientWidth, window.innerWidth || 0); //Max of page size vs window size, or zero
var screenHeight = Math.max(document.documentElement.clientHeight, window.innerHeight || 0);
screenHeight = screenHeight - 100; //correct for jsFiddle
var st, btnFixed=false, bd = $('#btnDIV');
$(window).scroll(function(){
st = $(window).scrollTop();
$('#rpt').html( st +'/'+ screenHeight); //DEV
if (st < screenHeight && !btnFixed){
bd.css({'top':st*1.3});
}else{
bd.css({'top': screenHeight+'px'});
btnFixed = true
}
if (st < screenHeight && btnFixed){
bd.css({'top':st*1.3});
btnFixed = true
}
});
html,body{
100%;
}
div{
position:relative;
}
#wrap{
height:2000px;
}
#btnDIV{
position:fixed;
top:0;
left:0;
background:red;
overflow:hidden;
z-index:2;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="btnDIV"><button class="exploreImage">Explore</button></div>
<div id="rpt"></div>
<div id="wrap"></div>
#rpt{position:fixed;top:0;right:0;height:40px;width:100px;background:wheat;}
jsFiddle Demo

Scrolling Two Divs Using JQuery/Javascript

Wrapper - Overflow Hidden
Div One: Sidebar
Div Two: Main Content
Div Two will have a normal scroll. Div One I wish to have no visible scroll however when you scroll Div One it scrolls Div Two.
Upon Div One's height hitting the bottom, it will no longer scroll and visa-versa for scrolling back up.
This will result in the sidebar always being visible at the side. Before you ask, I've tried all positioning types to get this to work resulting in many failed attempts.
My live demo can be seen here: http://rafflebananza.com/admin/newadmin.html#
Note I've tried to make a JSFiddle simplified but my maths does not seem to work in there the same. Please suggest whether I should fork all my page to there or whatnot for future visitors needing the same help.
Overview
Scrolling in the wrapper will scroll sidebar to point x only (x being the sidebars height) then stopping but will continue to allow the content to be scrolled. Visa-versa for scrolling back up.
Somewhat half way there...
var scrollTop = (window.pageYOffset !== undefined) ? window.pageYOffset : (document.documentElement || document.body.parentNode || document.body).scrollTop,
position = document.body.scrollTop;
function scrollD() {
var scroll = document.body.scrollTop;
if (scroll > position) {
// Scrolling Down Functions
} else {
// Scrolling Up Functions
}
position = scroll;
}
Updated the answer to match OPs requirements.
I downloaded your website in its current state and made the following changes to your code:
var scrollY = 0;
$(window).scroll(function() {
var sideNav = $('.SideNav'); // The side navigation
var wScrollY = $(this).scrollTop(); // Current scroll position of Window
var navHeight = sideNav.height(); // Height of the Navigation
var StageHeight = $(window).height() - 46; // The display space
if(sideNav.height() > StageHeight) { // Do the following if the side navigation is higher than the display space
var spaceLeft = sideNav.height() - StageHeight; // spaceLeft -> how many pixel left before fixing navigation when scrolling
if(scrollY < wScrollY) { // Scroll direction is down
if (wScrollY >= spaceLeft) // If scroll top > space left -> fixate navigation at the bottom, otherwise scroll with the content
sideNav.css({top:46-spaceLeft+wScrollY});
if (wScrollY <= 46) // Set top strict to 46. Sometimes there is white space left, caused by the scroll event.
sideNav.css({top:46});
} else { // Scroll direction is up
var sideNavTop;
if (sideNav.offset().top < 0) {
sideNavTop = Math.pow(sideNav.offset().top); // if top is negative, make it positive for comparison
} else {
sideNavTop = sideNav.offset().top;
}
if (sideNavTop > (46+wScrollY)) // Fixate the header if top of navigation appears
sideNav.css({top:46+wScrollY});
}
} else {
sideNav.css({top:46+wScrollY}); // Fixate always
}
scrollY = wScrollY;
});
This will let you scroll your side navigation up until its end. Then fixate. If you scroll up, it will still be fixated until your reach the point, where the navigation must scrolled back to its original position.
You can check the edited version here: http://pastebin.com/Zkx4pSKe
Just copy the raw code into a blank html page and try it out.
It's a bit messy and maybe not the best solution, but it works.
Ok, here you go:
var $sidebar = $('.sidebar'),
$window = $(window),
previousScroll = 0;
$window.on('scroll', function (e) {
if ($window.scrollTop() - previousScroll > 0) {
$sidebar.css({
'top': Math.max($window.scrollTop() + $window.height() - $sidebar.outerHeight(true), parseInt($sidebar.css('top'))) + 'px'
});
} else {
$sidebar.css({
'top': Math.min($window.scrollTop(), parseInt($sidebar.css('top'))) + 'px'
});
}
previousScroll = $window.scrollTop();
});
http://jsfiddle.net/7nwzcpqk/1/
i might have misunderstood your desired result incorrectly but you can see if this works for you :
.SideNav {
position: fixed; // you currently have this as position:absolute;
}
You don't need nor a wrapper element nor jQuery. I assume that you are using a wrapper because you want to have the top bar placed there. I think there is a better way to do it by using simply three divs.
The top bar has to be fixed (to be always visible) and of full width.
The side bar also has to be fixed (to be always visible) with a top margin of the height of the top bar.
The content needs just a left padding (width of side bar) and top padding (height of top bar).
Here is the example code (http://jsfiddle.net/zckfwL4p/):
HTML
<div id="top_bar"></div>
<div id="side_bar">links here</div>
<div id="content"></div>
CSS
body {
margin:0px;
padding:0px;
}
#side_bar {
width:50px;
position: fixed;
left:0px;
top:20px;
background-color:blue;
}
#top_bar {
position:fixed;
height:20px;
left:0px;
right:0px;
background-color:red;
}
#content {
position:relative;
padding-left:55px;
padding-top:25px;
}

jquery body css overflow-x not work

I want make a screen width judge, when screen width is bigger than 1024px, the body scroll bar will hidden, else when screen width is smaller than 1024px the body scroll bar will show its scroll.
See code in
http://jsfiddle.net/xmJzU/ (overflow-x)
http://jsfiddle.net/xmJzU/1/ (overflowX)
And test in
http://jsfiddle.net/xmJzU/show
http://jsfiddle.net/xmJzU/1/show
However when I dragged my browser edge, adjuce screen width smaller than 1024px, there have no scroll bar appear. Thanks.
It works, you just need to also declare the width variable inside your resize handler as the global variable is not in its' scope.
jQuery(document).ready(function() {
var width = $(window).width();
if (width < 1025) {
$('body').css('overflow-x', 'scroll');
} else {
$('body').css('overflow-x', 'hidden');
}
$(window).bind('resize', function() {
var width = $(window).width();
if (width < 1025) {
$('body').css('overflow-x', 'scroll');
} else {
$('body').css('overflow-x', 'hidden');
}
});
});
Example fiddle
An alternative method to using javascript for this is to use CSS3 Media Queries, but obviously this is dependant on the min-browser spec requirements you have.
Try using this css:
body {
width:100%;
min-width:200px;
overflow-x:hidden;
}

Scrollpane on the bottom, css is hacky, javascript is hard

I want to put a bar on the bottom of my page containing a varying number of pictures, which (if wider than the page) can be scrolled left and right.
The page width is varying, and I want the pane to be 100% in width.
I was trying to do a trick by letting the middle div overflow and animate it's position with jquery.animate().
Like this:
Here is a fiddle without the js: http://jsfiddle.net/SoonDead/DdPtv/7/
The problems are:
without declaring a large width to the items holder it will not overflow horizontally but vertically. Is this a good hack? (see the width: 9000px in the fiddle)
I only want to scroll the middle pane if it makes sense. For this I need to calculate the width of the overflowing items box (which should be the sum of the items' width inside), and the container of it with the overflow: hidden attribute. (this should be the width of the browser window minus the left and right buttons).
Is there a way to calculate the length of something in js without counting all of it's childrens length manually and sum it up?
Is there a way to get the width of the browser window? Is there a way to get a callback when the window is resized? I need to correct the panes position if the window suddenly widens (and the items are in a position that should not be allowed)
Since the window's width can vary I need to calculate on the fly if I can scroll left or right.
Can you help me with the javascript?
UPDATE: I have a followup question for this one: Scroll a div vertically to a desired position using jQuery Please help me solve that one too.
Use white-space:nowrap on the item container and display:inline or display:inline-block to prevent the items from wrapping and to not need to calculate or set an explicit width.
Edit:: Here's a live working demo: http://jsfiddle.net/vhvzq/2/
HTML
<div class="hscroll">
<ol>
<li>...</li>
<li>...</li>
</ol>
<button class="left"><</button>
<button class="right">></button>
</div>
CSS
.hscroll { white-space:nowrap; position:relative }
.hscroll ol { overflow:hidden; margin:0; padding:0 }
.hscroll li { list-style-type:none; display:inline-block; vertical-align:middle }
.hscroll button { position:absolute; height:100%; top:0; width:2em }
.hscroll .left { left:0 }
.hscroll .right { right:0 }
JavaScript (using jQuery)
$('.hscroll').each(function(){
var $this = $(this);
var scroller = $this.find('ol')[0];
var timer,offset=15;
function scrollLeft(){ scroller.scrollLeft -= offset; }
function scrollRight(){ scroller.scrollLeft += offset; }
function clearTimer(){ clearInterval(timer); }
$this.find('.left').click(scrollLeft).mousedown(function(){
timer = setInterval(scrollLeft,20);
}).mouseup(clearTimer);
$this.find('.right').click(scrollRight).mousedown(function(){
timer = setInterval(scrollRight,20);
}).mouseup(clearTimer);
});
Thanks Phrogz for this part -- give the image container the white-space: nowrap; and display: inline-block;.
You can calculate the width without having to calculate the width of the children every time but you will need to calculate the width of the children once.
//global variables
var currentWidth = 0;
var slideDistance = 0;
var totalSize = 0;
var dispWidth = (winWidth / 2); //this should get you the middle of the page -- see below
var spacing = 6; //padding or margins around the image element
$(Document).Ready(function() {
$("#Gallery li").each(function () {
totalSize = totalSize + parseFloat($(this).children().attr("width"));// my images are wrapped in a list so I parse each li and get it's child
});
totalSpacing = (($("#Gallery li").siblings().length - 1) * spacing); //handles the margins between pictures
currentWidth = (parseFloat($("#Gallery li.pictureSelected").children().attr("width")) + spacing);
maxLeftScroll = (dispWidth - (totalSize + totalSpacing)); //determines how far left you can scroll
});
function NextImage() {
currentWidth = currentWidth + (parseFloat($("#Gallery li.pictureSelected").next().children().attr("width")) + spacing); //gets the current width plus the width of the next image plus spacing.
slideDistance = (dispWidth - currentWidth)
$("#Gallery").animate({ left: slideDistance }, 700);
}
There is a way to get the browser window with in javascript (jQuery example).
and there is a way to catch the resize event.
var winWidth = $(window).width()
if (winWidth == null) {
winWidth = 50;
}
$(window).resize(function () {
var winNewWidth = $(window).width();
if (winWidth != winNewWidth) {
window.clearTimeout(timerID);
timerID = window.setInterval(function () { resizeWindow(false); }, 100);
}
winWidth = winNewWidth;
});
On my gallery there's actually quite a bit more but this should get you pointed in the right direction.
You need to change your #items from
#items
{
float: left;
background: yellow;
width: 9000px;
}
to
#items {
background: yellow;
}
Then calculate the width very easily with jQuery
// #items width is calculated as the number of child .item elements multiplied by their outerWidth (width+padding+border)
$("#items").width(
$(".item").length * $(".item").outerWidth()
);
and simply declare click events for the #left and #right elements
$("#left").click(function() {
$("#middle").animate({
scrollLeft: "-=50px"
}, 'fast');
});
$("#right").click(function() {
$("#middle").animate({
scrollLeft: "+=50px"
}, 'fast');
});
jsFiddle link here
EDIT
I overlooked that detail about the varying image widths. Here is the correct way to calculate the total width
var totalWidth = 0;
$(".item").each(function(index, value) {
totalWidth += $(value).outerWidth();
});
$("#items").width(totalWidth);

Categories

Resources