a(this).css({
position: 'fixed',
top: "200px",
left: "1270px",
width: "30px",
height: "30px",
margin: "0"
padding: "0",
minWidth: "65px",
listStyleType: "none",
zIndex: 1e7
});
I have this bit of code, which fixes an element to the screen so that, when you scroll, it follows the screen. However, when I resize the window, say, to just have the header, the image is not where it should be when I scroll down. What I want is for it to be in an absolute position when it's not in view but, when it comes into view, it follows the page and is fixed. Is this possible?
Yes this is possible, almost everything is.
All you need to do is detect how large the viewport is whenever somebody resizes. It's a lot easier in jQuery than with normal JavaScript.
var element = a(this);
$(document).on('resize', function(){
// if viewport is smaller than offset (200) plus height (30) of element
if($(window).height() < 230){
// set element to absolute
element.css({position: 'absolute'});
}else{
// set element to fixed
element.css({position: 'fixed'});
}
}
If you don't want to use jQuery, then you can still use most of the same code, but you'll have to create a function to get the height of the viewport. JavaScript - Get Browser Height
function returnHeight() {
var myHeight = 0;
if( typeof( window.innerHeight ) === 'number' ) {
//Non-IE
myHeight = window.innerHeight;
} else if( document.documentElement && document.documentElement.clientHeight ) {
//IE 6+ in 'standards compliant mode'
myHeight = document.documentElement.clientHeight;
} else if( document.body && document.body.clientHeight) {
//IE 4 compatible
myHeight = document.body.clientHeight;
}
return myHeight;
}
var element = a(this);
function resizeCallback(){
// if viewport is smaller than offset (200) plus height (30) of element
if(returnHeight() < 230){
// set element to absolute
element.css({position: 'absolute'});
}else{
// set element to fixed
element.css({position: 'fixed'});
}
}
if(window.attachEvent) {
window.attachEvent('onresize', resizeCallback);
}
else{
window.addEventListener('resize', resizeCallback, true);
}
Related
I would like to animate a div when user scrolls the page.
For that, i implemented this code:
var slide = jQuery(".apresentacao-spc-01");
var opening = false;
var closing = false;
var pos = jQuery(window).scrollTop();
jQuery(window).scroll(function() {
var pos = jQuery(window).scrollTop();
console.log(pos);
if (pos > 100) {
if (!opening) {
opening = true; closing = false;
slide.stop().animate({
'opacity': 1,
'margin-left': '0px'
}, 700, function() {
opening = false;
});
}
} else {
if (!closing) {
closing = true; opening = false;
slide.stop().animate({
'opacity': 0,
'margin-left': '-1000px'
}, 500, function() {
closing = false;
});
}
}
});
The issue is:
Using "if (pos > 100) {", if the user resolution is big enough to show the element before he needs to scroll, he won't see the element unless he begins to scroll the page.
My question is:
How can I get a scroll animation that will be executed when the element is visible?
I mean: If the element is visible on page load, the animation automatically starts... If the element is not visible on page load, the animation waits the scroll reach the element to start...
Thanks.
There a few different things you could do. My first thought was to query the height of the viewport with something like this:
var viewportWidth = document.documentElement.clientWidth
, viewportHeight = document.documentElement.clientHeight
And then trigger the animation if it is taller than the distance the element is down.
A more dynamic solution would be to use a function that checks to see if the element is in viewport the automatically, that way you wouldn't need to worry about adjusting the height if you changed stuff on your page:
function isElementInViewport (el) {
var rect = el.getBoundingClientRect();
return (
rect.top >= 0 &&
rect.left >= 0 &&
rect.bottom <= (window.innerHeight || document.documentElement.clientHeight) && /*or $(window).height() */
rect.right <= (window.innerWidth || document.documentElement.clientWidth) /*or $(window).width() */
);
}
credit to this response.
There is a use guide and further information in the link provided.
Good luck!
Refer the thread : Div at the browser bottom
Problem image :
http://i.imgur.com/I9vVv.png
http://i.stack.imgur.com/jTU5U.png
I used all the methods and it all went in wain. Is there any method in Jquery to place a div at the bottom if even the page is scrolled ?
Thanks in Advance
For browsers other than IE6, use position: fixed is enough:
#footer {
position: fixed !important; /* IE6 hack */
position: absolute;
right: 0;
bottom: 0;
background: yellow;
}
For IE6, a general approach is to register the scroll event and dynamically change the top style property of #footer
var footer = document.getElementById('footer');
// Test IE6
if (footer.currentStyle &&
footer.currentStyle.position !== 'fixed') {
// Set bottom to 'auto' because we would use top property
footer.style.bottom = 'auto';
// Only for IE6, so use window.attachEvent
window.attachEvent(
'onscroll',
function() {
var scrollTop = document.documentElement.scrollTop;
var pageHeight = document.documentElement.offsetHeight;
var height = footer.offsetHeight;
footer.style.top = (scrollTop + pageHeight - height) + 'px';
}
);
}
I'm hoping to find a way to get the current viewable window's position (relative to the total page width/height) so I can use it to force a scroll from one section to another. However, there seems to be a tremendous amount of options when it comes to guessing which object holds the true X/Y for your browser.
Which of these do I need to make sure IE 6+, FF 2+, and Chrome/Safari work?
window.innerWidth
window.innerHeight
window.pageXOffset
window.pageYOffset
document.documentElement.clientWidth
document.documentElement.clientHeight
document.documentElement.scrollLeft
document.documentElement.scrollTop
document.body.clientWidth
document.body.clientHeight
document.body.scrollLeft
document.body.scrollTop
And are there any others? Once I know where the window is I can set an event chain that will slowly call window.scrollBy(x,y); until it reaches my desired point.
The method jQuery (v1.10) uses to find this is:
var doc = document.documentElement;
var left = (window.pageXOffset || doc.scrollLeft) - (doc.clientLeft || 0);
var top = (window.pageYOffset || doc.scrollTop) - (doc.clientTop || 0);
That is:
It tests for window.pageXOffset first and uses that if it exists.
Otherwise, it uses document.documentElement.scrollLeft.
It then subtracts document.documentElement.clientLeft if it exists.
The subtraction of document.documentElement.clientLeft / Top only appears to be required to correct for situations where you have applied a border (not padding or margin, but actual border) to the root element, and at that, possibly only in certain browsers.
Maybe more simple;
var top = window.pageYOffset || document.documentElement.scrollTop,
left = window.pageXOffset || document.documentElement.scrollLeft;
Credits: so.dom.js#L492
Using pure javascript you can use Window.scrollX and Window.scrollY
window.addEventListener("scroll", function(event) {
var top = this.scrollY,
left =this.scrollX;
}, false);
Notes
The pageXOffset property is an alias for the scrollX property, and The
pageYOffset property is an alias for the scrollY property:
window.pageXOffset == window.scrollX; // always true
window.pageYOffset == window.scrollY; // always true
Here is a quick demo
window.addEventListener("scroll", function(event) {
var top = this.scrollY,
left = this.scrollX;
var horizontalScroll = document.querySelector(".horizontalScroll"),
verticalScroll = document.querySelector(".verticalScroll");
horizontalScroll.innerHTML = "Scroll X: " + left + "px";
verticalScroll.innerHTML = "Scroll Y: " + top + "px";
}, false);
*{box-sizing: border-box}
:root{height: 200vh;width: 200vw}
.wrapper{
position: fixed;
top:20px;
left:0px;
width:320px;
background: black;
color: green;
height: 64px;
}
.wrapper div{
display: inline;
width: 50%;
float: left;
text-align: center;
line-height: 64px
}
.horizontalScroll{color: orange}
<div class=wrapper>
<div class=horizontalScroll>Scroll (x,y) to </div>
<div class=verticalScroll>see me in action</div>
</div>
Maybe this has not been mentioned due to this article been 11 years old.
But currently I am using window.scrollY (inside an onscroll event listner and a throttle function) and it works just fine most of the time.
And when it doesn't I use intersectionObserver API for similar effect which is also a fairly new feature I guess.
if (window.scrollY > desiredAmount) {
doThis();
}
function FastScrollUp()
{
window.scroll(0,0)
};
function FastScrollDown()
{
$i = document.documentElement.scrollHeight ;
window.scroll(0,$i)
};
var step = 20;
var h,t;
var y = 0;
function SmoothScrollUp()
{
h = document.documentElement.scrollHeight;
y += step;
window.scrollBy(0, -step)
if(y >= h )
{clearTimeout(t); y = 0; return;}
t = setTimeout(function(){SmoothScrollUp()},20);
};
function SmoothScrollDown()
{
h = document.documentElement.scrollHeight;
y += step;
window.scrollBy(0, step)
if(y >= h )
{clearTimeout(t); y = 0; return;}
t = setTimeout(function(){SmoothScrollDown()},20);
}
I'm trying to work out how to enlarge all elements on a page, but keep the centre of enlargement in the centre of the window.
On this page, once the image reaches the top or the left side of the window the centre of enlargement changes. It also changes when you move the image. (exactly what you would expect)
I'm thinking I'd need to take a completely different approach to achieve what I want. But I'm not sure what that approach is..
Any ideas?
Well, here's my take.
Only thing is that I ditched the containers you were using. Is that cheating? Seems like they were only there to get the image centered. No need.
This works as expected with no side effects.
Here's a working demo you can test:
http://jsfiddle.net/YFPRB/1/
(You need to click on the pane with the baboon first.)
HTML
<body>
<img src="http://cdn.sstatic.net/stackoverflow/img/apple-touch-icon.png" />
</body>
CSS
html, body {
width: 100%;
height: 100%;
overflow: hidden;
}
jQuery
EDIT: Thanks to #stagas for the reminder to clean up redundancies.
var $img = $('img'); // Cache the image. Better for performance.
$img.draggable();
$img.css({left: ($('body').width() / 2) - ($img.width() / 2)})
.css({top: ($('body').height() / 2) - ($img.height() / 2)})
$(document).keydown(function(event) {
if (event.keyCode == 38) {
var adjustment = 1.25;
} else if (event.keyCode == 40) {
var adjustment = 0.8;
} else {
return;
}
var offset = $img.offset();
var width = $img.width();
var height = $img.height();
var newWidth = width * adjustment;
var newHeight = height * adjustment;
var diffWidth = newWidth - width;
var diffHeight = newHeight - height;
var hcenter = $('body').width() / 2;
var vcenter = $('body').height() / 2;
var leftPercent = (hcenter - offset.left) / width;
var topPercent = (vcenter - offset.top) / height;
$img.offset({top: offset.top - (diffHeight * topPercent), left: offset.left - (diffWidth * leftPercent)});
$img.width(newWidth).height(newHeight);
});
This is what I came up, it works as you say except the image will always go to the center after zooming in or out:
$('document').ready(function() {
zoomimg=$('#zoomimg'); // we store this in a variable since we don't need to traverse the DOM every time -- this is faster
var viewportWidth = $(window).width();
var viewportHeight = window.innerHeight ? window.innerHeight : $(window).height(); // this is to work with Opera
zoomimg.css({'position': 'absolute', 'left': (viewportWidth/2)-(zoomimg.width()/2), 'top' : (viewportHeight/2)-(zoomimg.height()/2)}).draggable();
$(document).keydown(function(event) {
event = event || window.event;
var viewportWidth = $(window).width();
var viewportHeight = window.innerHeight ? window.innerHeight : $(window).height(); // this is to work with Opera
if (event.keyCode == 38) {
width = zoomimg.width();
height = zoomimg.height();
zoomimg.width(width*1.2).height(height*1.2);
var viewportWidth = $(window).width();
var viewportHeight = window.innerHeight ? window.innerHeight : $(window).height();
zoomimg.css({'left': (viewportWidth/2)-(zoomimg.width()/2), 'top' : (viewportHeight/2)-(zoomimg.height()/2)});
} else if (event.keyCode == 40) {
width = zoomimg.width();
height = zoomimg.height();
zoomimg.width(width*0.8).height(height*0.8);
var viewportWidth = $(window).width();
var viewportHeight = window.innerHeight ? window.innerHeight : $(window).height();
zoomimg.css({'left': (viewportWidth/2)-(zoomimg.width()/2), 'top' : (viewportHeight/2)-(zoomimg.height()/2)});
} else {
return
}
});
});
You should put an ID 'zoomimg' on the tag for it to work, and overflow:hidden on the #container . Also ditch that display:table and display:table-cell they're useless now that we center with Javascript. Also, pressing the down arrow key will cause the container to scroll down, so you should use other keys, as the arrows are reserved by the browser for scrolling the viewport.
I am looking for a code snippet to get the height of the viewable area within a browser window.
I had this code, however it is somewhat bugged as if the the body doesn't exceed the height the of the window then it comes back short.
document.body.clientHeight;
I have tried a couple of other things but they either return NaN or the same height as the above.
Does anyone know how to get the real height of the browsing window?
You'll want something like this, taken from http://www.howtocreate.co.uk/tutorials/javascript/browserwindow
function alertSize() {
var myWidth = 0, myHeight = 0;
if( typeof( window.innerWidth ) == 'number' ) {
//Non-IE
myWidth = window.innerWidth;
myHeight = window.innerHeight;
} else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) {
//IE 6+ in 'standards compliant mode'
myWidth = document.documentElement.clientWidth;
myHeight = document.documentElement.clientHeight;
} else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) {
//IE 4 compatible
myWidth = document.body.clientWidth;
myHeight = document.body.clientHeight;
}
window.alert( 'Width = ' + myWidth );
window.alert( 'Height = ' + myHeight );
}
So that's innerHeight for modern browsers, documentElement.clientHeight for IE, body.clientHeight for deprecated/quirks.
Try using jquery:
window_size = $(window).height();
You can use the window.innerHeight
The way that I like to do it is like this with a ternary assignment.
var width = isNaN(window.innerWidth) ? window.clientWidth : window.innerWidth;
var height = isNaN(window.innerHeight) ? window.clientHeight : window.innerHeight;
I might point out that, if you run this in the global context that from that point on you could use window.height and window.width.
Works on IE and other browsers as far as I know (I have only tested it on IE11).
Super clean and, if I am not mistaken, efficient.
There's a simpler way than a whole bunch of if statements. Use the or (||) operator.
function getBrowserDimensions() {
return {
width: (window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth),
height: (window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight)
};
}
var browser_dims = getBrowserDimensions();
alert("Width = " + browser_dims.width + "\nHeight = " + browser_dims.height);
This should works too. First create an absolute <div> element with absolute position and 100% height:
<div id="h" style="position:absolute;top:0;bottom:0;"></div>
Then, get the window height from that element via offsetHeight
var winHeight = document.getElementById('h').offsetHeight;
Update:
function getBrowserSize() {
var div = document.createElement('div');
div.style.position = 'absolute';
div.style.top = 0;
div.style.left = 0;
div.style.width = '100%';
div.style.height = '100%';
document.documentElement.appendChild(div);
var results = {
width: div.offsetWidth,
height: div.offsetHeight
};
div.parentNode.removeChild(div); // remove the `div`
return results;
}
console.log(getBrowserSize());
var winWidth = window.screen.width;
var winHeight = window.screen.height;
document.write(winWidth, winHeight);
With JQuery you can try this $(window).innerHeight() (Works for me on Chrome, FF and IE). With bootstrap modal I used something like the following;
$('#YourModal').on('show.bs.modal', function () {
$('.modal-body').css('height', $(window).innerHeight() * 0.7);
});
I prefer the way I just figured out... No JS... 100% HTML & CSS:
(Will center it perfectly in the middle, regardless of the content size.
HTML FILE
<html><head>
<link href="jane.css" rel="stylesheet" />
</head>
<body>
<table id="container">
<tr>
<td id="centerpiece">
123
</td></tr></table>
</body></html>
CSS FILE
#container{
border:0;
width:100%;
height:100%;
}
#centerpiece{
vertical-align:middle;
text-align:center;
}
for centering images / div's held within the td, you may wish to try margin:auto; and specify a div dimension instead. -Though, saying that... the 'text-align' property will align much more than just a simple text element.
JavaScript version in case if jQuery is not an option:
window.screen.availHeight