I have need to create 2 buttons on my site that would change the browser zoom level (+) (-). I'm requesting browser zoom and not css zoom because of image size and layout issues.
Well, is this even possible? I've heard conflicting reports.
Possible in IE and chrome although it does not work in firefox:
<script>
function toggleZoomScreen() {
document.body.style.zoom = "80%";
}
</script>
<img src="example.jpg" alt="example" onclick="toggleZoomScreen()">
I would say not possible in most browsers, at least not without some additional plugins. And in any case I would try to avoid relying on the browser's zoom as the implementations vary (some browsers only zoom the fonts, others zoom the images, too etc). Unless you don't care much about user experience.
If you need a more reliable zoom, then consider zooming the page fonts and images with JavaScript and CSS, or possibly on the server side. The image and layout scaling issues could be addressed this way. Of course, this requires a bit more work.
Try if this works for you. This works on FF, IE8+ and chrome. The else part applies for non-firefox browsers. Though this gives you a zoom effect, it does not actually modify the zoom value at browser level.
var currFFZoom = 1;
var currIEZoom = 100;
$('#plusBtn').on('click',function(){
if ($.browser.mozilla){
var step = 0.02;
currFFZoom += step;
$('body').css('MozTransform','scale(' + currFFZoom + ')');
} else {
var step = 2;
currIEZoom += step;
$('body').css('zoom', ' ' + currIEZoom + '%');
}
});
$('#minusBtn').on('click',function(){
if ($.browser.mozilla){
var step = 0.02;
currFFZoom -= step;
$('body').css('MozTransform','scale(' + currFFZoom + ')');
} else {
var step = 2;
currIEZoom -= step;
$('body').css('zoom', ' ' + currIEZoom + '%');
}
});
You can use the CSS3 zoom function, but I have not tested it yet with jQuery. Will try now and let you know.
UPDATE: tested it, works but it's fun
I could't find a way to change the actual browser zoom level, but you can get pretty close with CSS transform: scale(). Here is my solution based on JavaScript and jQuery:
<!-- Trigger -->
<ul id="zoom_triggers">
<li><a id="zoom_in">zoom in</a></li>
<li><a id="zoom_out">zoom out</a></li>
<li><a id="zoom_reset">reset zoom</a></li>
</ul>
<script>
jQuery(document).ready(function($)
{
// Set initial zoom level
var zoom_level=100;
// Click events
$('#zoom_in').click(function() { zoom_page(10, $(this)) });
$('#zoom_out').click(function() { zoom_page(-10, $(this)) });
$('#zoom_reset').click(function() { zoom_page(0, $(this)) });
// Zoom function
function zoom_page(step, trigger)
{
// Zoom just to steps in or out
if(zoom_level>=120 && step>0 || zoom_level<=80 && step<0) return;
// Set / reset zoom
if(step==0) zoom_level=100;
else zoom_level=zoom_level+step;
// Set page zoom via CSS
$('body').css({
transform: 'scale('+(zoom_level/100)+')', // set zoom
transformOrigin: '50% 0' // set transform scale base
});
// Adjust page to zoom width
if(zoom_level>100) $('body').css({ width: (zoom_level*1.2)+'%' });
else $('body').css({ width: '100%' });
// Activate / deaktivate trigger (use CSS to make them look different)
if(zoom_level>=120 || zoom_level<=80) trigger.addClass('disabled');
else trigger.parents('ul').find('.disabled').removeClass('disabled');
if(zoom_level!=100) $('#zoom_reset').removeClass('disabled');
else $('#zoom_reset').addClass('disabled');
}
});
</script>
as the the accepted answer mentioned, you can enlarge the fontSize css attribute of the element in DOM one by one, the following code for your reference.
<script>
var factor = 1.2;
var all = document.getElementsByTagName("*");
for (var i=0, max=all.length; i < max; i++) {
var style = window.getComputedStyle(all[i]);
var fontSize = style.getPropertyValue('font-size');
if(fontSize){
all[i].style.fontSize=(parseFloat(fontSize)*factor)+"px";
}
if(all[i].nodeName === "IMG"){
var width=style.getPropertyValue('width');
var height=style.getPropertyValue('height');
all[i].style.height = (parseFloat(height)*factor)+"px";
all[i].style.width = (parseFloat(width)*factor)+"px";
}
}
</script>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
var currFFZoom = 1;
var currIEZoom = 100;
function plus(){
//alert('sad');
var step = 0.02;
currFFZoom += step;
$('body').css('MozTransform','scale(' + currFFZoom + ')');
var stepie = 2;
currIEZoom += stepie;
$('body').css('zoom', ' ' + currIEZoom + '%');
};
function minus(){
//alert('sad');
var step = 0.02;
currFFZoom -= step;
$('body').css('MozTransform','scale(' + currFFZoom + ')');
var stepie = 2;
currIEZoom -= stepie;
$('body').css('zoom', ' ' + currIEZoom + '%');
};
</script>
</head>
<body>
<!--zoom controls-->
<a id="minusBtn" onclick="minus()">------</a>
<a id="plusBtn" onclick="plus()">++++++</a>
</body>
</html>
in Firefox will not change the zoom only change scale!!!
You can use Window.devicePixelRatio and Window.matchMedia()
const onChange = e => {
const pr = window.devicePixelRatio;
const media = `(resolution: ${pr}dppx)`;
const mql = matchMedia(media);
const prString = (pr * 100).toFixed(0);
const textContent = `${prString}% (${pr.toFixed(2)})`;
console.log(textContent);
document.getElementById('out').append(
Object.assign(document.createElement('li'), {textContent})
)
mql.addEventListener('change', onChange, {once: true});
};
document.getElementById('checkZoom').addEventListener('click', e => onChange());
onChange();
<button id="checkZoom">get Zoom</button>
<ul id="out"></ul>
You can target which part of CSS zooming out and in, or the entire document.body.style.zoom
You can set the maximum and minimum zoom levels. Meaning, more clicks on the button (+) or (-) will not zoom in more or zoom out more.
var zoomingTarget = document.querySelector('.zooming-target')
var zoomInTool = document.getElementById('zoom-in');
var zoomOutTool = document.getElementById('zoom-out');
let zoomIndex = 0;
function zooming () {
if (zoomIndex > 2) {
zoomIndex = 2
} else if (zoomIndex < -2) {
zoomIndex = -2
}
zoomingTarget.style.zoom = "calc(100% + " + zoomIndex*10 + "%)";
}
Now make the buttons (+) and (-) work.
zoomInTool.addEventListener('click', () => {
zoomIndex++;
if(zoomIndex == 0) {
console.log('zoom level is 100%')
}
zooming();
})
zoomOutTool.addEventListener('click', () => {
zoomIndex--
if(zoomIndex == 0) {
console.log('zoom level is 100%')
}
zooming();
})
Since style.zoom doesn't work on Firefox, consider using style.transform = scale(x,y).
I fixed by the below code.
HTML:
<div class="mt-5"
[ngStyle]="getStyles()">
TS:
getStyles() {
const screenWidth = screen.width;
const windowWidth = window.innerWidth;
if (windowWidth != screenWidth) {
const percentDifference = Math.ceil((screenWidth / windowWidth) * 100);
if (percentDifference > 100) {
this.bannerBackgroundImageSize = '20%, 74%';
} else if (percentDifference === 100) {
this.bannerBackgroundImageSize = '20%, 72%';
} else if (percentDifference >= 90 && percentDifference <= 99) {
this.bannerBackgroundImageSize = '25%, 70%';
} else if (percentDifference >= 80 && percentDifference <= 89) {
this.bannerBackgroundImageSize = '28%, 68%';
} else if (percentDifference >= 75 && percentDifference <= 79) {
this.bannerBackgroundImageSize = '29%, 67%';
} else if (percentDifference >= 67 && percentDifference <= 74) {
this.bannerBackgroundImageSize = '30%, 65%';
} else if (percentDifference >= 50 && percentDifference <= 66) {
this.bannerBackgroundImageSize = '30%, 61%';
} else if (percentDifference < 50) {
this.bannerBackgroundImageSize = '30%, 58%';
}
} else {
this.bannerBackgroundImageSize = '20%, 72%';
}
const myStyles = {
'background-size': this.bannerBackgroundImageSize,
};
return myStyles;
}
I Hope this will work with all zoom levels and it can be considered with all styles.
Useful links:
https://css-tricks.com/can-javascript-detect-the-browsers-zoom-level/
https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Backgrounds_and_Borders/Resizing_background_images
Related
I have need to create 2 buttons on my site that would change the browser zoom level (+) (-). I'm requesting browser zoom and not css zoom because of image size and layout issues.
Well, is this even possible? I've heard conflicting reports.
Possible in IE and chrome although it does not work in firefox:
<script>
function toggleZoomScreen() {
document.body.style.zoom = "80%";
}
</script>
<img src="example.jpg" alt="example" onclick="toggleZoomScreen()">
I would say not possible in most browsers, at least not without some additional plugins. And in any case I would try to avoid relying on the browser's zoom as the implementations vary (some browsers only zoom the fonts, others zoom the images, too etc). Unless you don't care much about user experience.
If you need a more reliable zoom, then consider zooming the page fonts and images with JavaScript and CSS, or possibly on the server side. The image and layout scaling issues could be addressed this way. Of course, this requires a bit more work.
Try if this works for you. This works on FF, IE8+ and chrome. The else part applies for non-firefox browsers. Though this gives you a zoom effect, it does not actually modify the zoom value at browser level.
var currFFZoom = 1;
var currIEZoom = 100;
$('#plusBtn').on('click',function(){
if ($.browser.mozilla){
var step = 0.02;
currFFZoom += step;
$('body').css('MozTransform','scale(' + currFFZoom + ')');
} else {
var step = 2;
currIEZoom += step;
$('body').css('zoom', ' ' + currIEZoom + '%');
}
});
$('#minusBtn').on('click',function(){
if ($.browser.mozilla){
var step = 0.02;
currFFZoom -= step;
$('body').css('MozTransform','scale(' + currFFZoom + ')');
} else {
var step = 2;
currIEZoom -= step;
$('body').css('zoom', ' ' + currIEZoom + '%');
}
});
You can use the CSS3 zoom function, but I have not tested it yet with jQuery. Will try now and let you know.
UPDATE: tested it, works but it's fun
I could't find a way to change the actual browser zoom level, but you can get pretty close with CSS transform: scale(). Here is my solution based on JavaScript and jQuery:
<!-- Trigger -->
<ul id="zoom_triggers">
<li><a id="zoom_in">zoom in</a></li>
<li><a id="zoom_out">zoom out</a></li>
<li><a id="zoom_reset">reset zoom</a></li>
</ul>
<script>
jQuery(document).ready(function($)
{
// Set initial zoom level
var zoom_level=100;
// Click events
$('#zoom_in').click(function() { zoom_page(10, $(this)) });
$('#zoom_out').click(function() { zoom_page(-10, $(this)) });
$('#zoom_reset').click(function() { zoom_page(0, $(this)) });
// Zoom function
function zoom_page(step, trigger)
{
// Zoom just to steps in or out
if(zoom_level>=120 && step>0 || zoom_level<=80 && step<0) return;
// Set / reset zoom
if(step==0) zoom_level=100;
else zoom_level=zoom_level+step;
// Set page zoom via CSS
$('body').css({
transform: 'scale('+(zoom_level/100)+')', // set zoom
transformOrigin: '50% 0' // set transform scale base
});
// Adjust page to zoom width
if(zoom_level>100) $('body').css({ width: (zoom_level*1.2)+'%' });
else $('body').css({ width: '100%' });
// Activate / deaktivate trigger (use CSS to make them look different)
if(zoom_level>=120 || zoom_level<=80) trigger.addClass('disabled');
else trigger.parents('ul').find('.disabled').removeClass('disabled');
if(zoom_level!=100) $('#zoom_reset').removeClass('disabled');
else $('#zoom_reset').addClass('disabled');
}
});
</script>
as the the accepted answer mentioned, you can enlarge the fontSize css attribute of the element in DOM one by one, the following code for your reference.
<script>
var factor = 1.2;
var all = document.getElementsByTagName("*");
for (var i=0, max=all.length; i < max; i++) {
var style = window.getComputedStyle(all[i]);
var fontSize = style.getPropertyValue('font-size');
if(fontSize){
all[i].style.fontSize=(parseFloat(fontSize)*factor)+"px";
}
if(all[i].nodeName === "IMG"){
var width=style.getPropertyValue('width');
var height=style.getPropertyValue('height');
all[i].style.height = (parseFloat(height)*factor)+"px";
all[i].style.width = (parseFloat(width)*factor)+"px";
}
}
</script>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
var currFFZoom = 1;
var currIEZoom = 100;
function plus(){
//alert('sad');
var step = 0.02;
currFFZoom += step;
$('body').css('MozTransform','scale(' + currFFZoom + ')');
var stepie = 2;
currIEZoom += stepie;
$('body').css('zoom', ' ' + currIEZoom + '%');
};
function minus(){
//alert('sad');
var step = 0.02;
currFFZoom -= step;
$('body').css('MozTransform','scale(' + currFFZoom + ')');
var stepie = 2;
currIEZoom -= stepie;
$('body').css('zoom', ' ' + currIEZoom + '%');
};
</script>
</head>
<body>
<!--zoom controls-->
<a id="minusBtn" onclick="minus()">------</a>
<a id="plusBtn" onclick="plus()">++++++</a>
</body>
</html>
in Firefox will not change the zoom only change scale!!!
You can use Window.devicePixelRatio and Window.matchMedia()
const onChange = e => {
const pr = window.devicePixelRatio;
const media = `(resolution: ${pr}dppx)`;
const mql = matchMedia(media);
const prString = (pr * 100).toFixed(0);
const textContent = `${prString}% (${pr.toFixed(2)})`;
console.log(textContent);
document.getElementById('out').append(
Object.assign(document.createElement('li'), {textContent})
)
mql.addEventListener('change', onChange, {once: true});
};
document.getElementById('checkZoom').addEventListener('click', e => onChange());
onChange();
<button id="checkZoom">get Zoom</button>
<ul id="out"></ul>
You can target which part of CSS zooming out and in, or the entire document.body.style.zoom
You can set the maximum and minimum zoom levels. Meaning, more clicks on the button (+) or (-) will not zoom in more or zoom out more.
var zoomingTarget = document.querySelector('.zooming-target')
var zoomInTool = document.getElementById('zoom-in');
var zoomOutTool = document.getElementById('zoom-out');
let zoomIndex = 0;
function zooming () {
if (zoomIndex > 2) {
zoomIndex = 2
} else if (zoomIndex < -2) {
zoomIndex = -2
}
zoomingTarget.style.zoom = "calc(100% + " + zoomIndex*10 + "%)";
}
Now make the buttons (+) and (-) work.
zoomInTool.addEventListener('click', () => {
zoomIndex++;
if(zoomIndex == 0) {
console.log('zoom level is 100%')
}
zooming();
})
zoomOutTool.addEventListener('click', () => {
zoomIndex--
if(zoomIndex == 0) {
console.log('zoom level is 100%')
}
zooming();
})
Since style.zoom doesn't work on Firefox, consider using style.transform = scale(x,y).
I fixed by the below code.
HTML:
<div class="mt-5"
[ngStyle]="getStyles()">
TS:
getStyles() {
const screenWidth = screen.width;
const windowWidth = window.innerWidth;
if (windowWidth != screenWidth) {
const percentDifference = Math.ceil((screenWidth / windowWidth) * 100);
if (percentDifference > 100) {
this.bannerBackgroundImageSize = '20%, 74%';
} else if (percentDifference === 100) {
this.bannerBackgroundImageSize = '20%, 72%';
} else if (percentDifference >= 90 && percentDifference <= 99) {
this.bannerBackgroundImageSize = '25%, 70%';
} else if (percentDifference >= 80 && percentDifference <= 89) {
this.bannerBackgroundImageSize = '28%, 68%';
} else if (percentDifference >= 75 && percentDifference <= 79) {
this.bannerBackgroundImageSize = '29%, 67%';
} else if (percentDifference >= 67 && percentDifference <= 74) {
this.bannerBackgroundImageSize = '30%, 65%';
} else if (percentDifference >= 50 && percentDifference <= 66) {
this.bannerBackgroundImageSize = '30%, 61%';
} else if (percentDifference < 50) {
this.bannerBackgroundImageSize = '30%, 58%';
}
} else {
this.bannerBackgroundImageSize = '20%, 72%';
}
const myStyles = {
'background-size': this.bannerBackgroundImageSize,
};
return myStyles;
}
I Hope this will work with all zoom levels and it can be considered with all styles.
Useful links:
https://css-tricks.com/can-javascript-detect-the-browsers-zoom-level/
https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Backgrounds_and_Borders/Resizing_background_images
I would like you to help me for a thing here, for a function to increase and then decrease SVG shape when it hits limit.
It should go from 3 to 6 and then 6 to 3 and so on... but instead it goes from 3 to 6 and then 6 to minus infinite. And I don't understand why.
Here is my code :
var size = 3;
var sizeManager = 1;
function increaseAnimation(el){
var elem = document.getElementById(el);
elem.style.transform = "scale("+size+")";
timer = setTimeout('increaseAnimation(\''+el+'\',3000)');
size=size+0.005*sizeManager;
if(size >= 6){
sizeManager=sizeManager*-1;
}
if (size <= 3){
sizeManager=sizeManager*+1;
}
}
Your weird setTimeout implementation, with bound was broken.
There's also the issue that your sizeManager is not properly reflecting:
function increaseAnimation(id, interval) {
var size = 1;
var velocity = 0.05;
var elem = document.getElementById(id);
function iterate() {
elem.style.transform = "scale(" + size + ")";
size += velocity;
if (size > 2 || size < 1) {
velocity *= -1; // velocity reflected
}
}
var timer = setInterval(iterate, interval);
return function stop() {
clearInterval(timer)
}
}
I also added a stop function which you can call at a later point.
var stopper = increaseAnimation("content", 16);
setTimeout(stopper, 5000);
The error is with the line sizeManager=sizeManager*+1; Multiplying a number by one doesn't change it. You basically want to toggle sizeManager between -1 and +1, and you can do so by multiplying by -1, regardless of whether it is currently negative or positive.
I've tested this code and it seems to work:
var size = 3;
var sizeManager = 1;
function increaseAnimation(el) {
var elem = document.getElementById(el);
elem.style.transform = "scale(" + size + ")";
timer = setTimeout("increaseAnimation('" + el + "', 3000)");
size += 0.005 * sizeManager;
if (size >= 6 || size <= 3) {
sizeManager *= -1;
}
}
Full HTML for a POC demo at: https://pastebin.com/GW0Ncr9A
Holler, if you have questions.
function Scaler(elementId, minScale, maxScale, deltaScale, direction, deltaMsecs) {
var scale = (1 == direction)?minScale:maxScale;
var timer = null;
function incrementScale() {
var s = scale + deltaScale*direction;
if (s < minScale || s > maxScale) direction *= -1;
return scale += deltaScale*direction;
};
function doScale(s) {
document.getElementById(elementId).style.transform = 'scale(' + s + ')';
};
this.getDeltaMsecs = function() {return deltaMsecs;};
this.setTimer = function(t) {timer = t;};
this.run = function() {doScale(incrementScale());};
this.stop = function() {
clearInterval(timer);
this.setTimer(null);
};
};
var scaler = new Scaler('avatar', 3, 6, .05, 1, 50);
function toggleScaler(ref) {
if ('run scaler' == ref.value) {
ref.value = 'stop scaler';
scaler.setTimer(setInterval('scaler.run()', scaler.getDeltaMsecs()));
}
else {
scaler.stop();
ref.value = 'run scaler';
}
};
I want to make div content resizable, but the div itself to stay the same size. This should happen when the user scrolls. I have this function:
var zoomable = document.getElementById('zoomable'),
zX = 1;
window.addEventListener('wheel', function (e) {
var dir;
if (!e.ctrlKey) {
return;
}
dir = (e.deltaY > 0) ? 0.1 : -0.1;
zX += dir;
zoomable.style.transform = 'scale(' + zX + ')';
e.preventDefault();
return;
});
This works but only with the div itself. In this div I have multiple small draggable tables with .foo class and I want to resize them without changing parents size. I have also tried this:
var zoomable = document.getElementsByClassName('foo'),
zX = 1;
window.addEventListener('wheel', function (e) {
var dir;
if (!e.ctrlKey) {
return;
}
dir = (e.deltaY > 0) ? 0.1 : -0.1;
zX += dir;
zoomable.each(function(){
$(this).style.transform = 'scale(' + zX + ')';
})
e.preventDefault();
return;
});
But is does not work either. Is there a way to resize content but not the div?
EDIT: Here is jsfiddle: https://jsfiddle.net/vaxobasilidze/ba2n9a61/
It's not exactly my project (Because it's too complex), but the idea is the same. I want to make #zoomable div to stay the same size and its content (paragraphs in this case) to be resizable.
I've adjusted your fiddle to work. I think this is what you wanted. You need to target your content to make this work like your description.
var content = document.getElementById('zoomable').getElementsByTagName('p');
var zX = 1;
window.addEventListener('wheel', function (e) {
var dir;
if (!e.ctrlKey) {
return;
}
dir = (e.deltaY > 0) ? 0.1 : -0.1;
zX += dir;
for (var i = 0; i<content.length; i++) {
content[i].style.transform = 'scale(' + zX + ')';
}
e.preventDefault();
return;
});
https://jsfiddle.net/Karadjordje1389/z254o87v/
I have an element with animated top margin. I need to detect if it isn't too close from the border, and if it is, scroll parent div to lower position, to prevent animated element from hiding. Here is an example:
http://jsfiddle.net/zYYBR/5/
This green box shouldn't be below the red line after clicking the "down" button.
Do you mean this?
var new_margin;
var step = 75;
var limit = $("#max")[0].offsetTop;
$('#down').click(function() {
var goStep = step;
var elHeight = $("#animated")[0].offsetTop + $("#animated")[0].offsetHeight;
if((elHeight + step) > limit)
{
goStep = limit - elHeight;
}
new_margin = goStep + parseInt($('#animated').css('margin-top'));
$("#animated").animate({marginTop: new_margin}, 1000);
});
http://jsfiddle.net/zYYBR/8/
EDIT: Or maybe something like that (of course you can improve the calculation, because currently it's very buggy with scroll):
var new_margin;
var step = 75;
$('#down').click(function () {
scroll(1000);
});
var scrollTimer = null;
$("#container").bind("scroll", function () {
clearTimeout(scrollTimer);
scrollTimer = setTimeout(function () { scroll(1); }, 10);
});
function scroll(speed) {
var scrollStep, animationStep = step;
var currentBoxBottom = $("#animated")[0].offsetTop + $("#animated")[0].offsetHeight;
var nextCurrentBoxBottom = currentBoxBottom + step;
var limit = $("#max")[0].offsetTop + $("#container")[0].scrollTop;
if (nextCurrentBoxBottom > limit) {
if (limit >= $("#container")[0].scrollTop) {
scrollStep = $("#container")[0].scrollTop + nextCurrentBoxBottom - limit;
}
else {
scrollStep = $("#container")[0].scrollTop - nextCurrentBoxBottom - limit;
animationStep = nextCurrentBoxBottom - limit;
}
$("#container")[0].scrollTop = scrollStep;
}
new_margin = animationStep + parseInt($('#animated').css('margin-top'));
$("#animated").animate({ marginTop: new_margin }, speed);
}
http://jsfiddle.net/zYYBR/13/
Do you mean something like this?
I have the same visual result as Alex Dn did, but I added a little extra direction to what I think you're talking about. If it's what you're looking for I'll make updates:
var new_margin;
var step = 75;
var limit = $("#max")[0].offsetTop;
$('#down2').click(function() {
var anim = $("#animated");
var hrOff = $("#max").offset();
var thOff = anim.offset();
new_margin = Math.min(hrOff.top - thOff.top - anim.height(), 75);
console.log(new_margin, hrOff.top, thOff.top);
var st = 0;
if (new_margin < 75) {
st = 75 - new_margin;
//have container scroll by this much?
}
anim.animate({
marginTop: "+=" + new_margin
}, 1000);
});
http://jsfiddle.net/zYYBR/10/
how to determine, using jquery, if the element is visible on the current page view. I'd like to add a comment functionality, which works like in facebook, where you only scroll to element if it's not currently visible. By visible, I mean that it is not in the current page view, but you can scroll to the element.
Live Demo
Basically you just check the position of the element to see if its within the windows viewport.
function checkIfInView(element){
var offset = element.offset().top - $(window).scrollTop();
if(offset > window.innerHeight){
// Not in view so scroll to it
$('html,body').animate({scrollTop: offset}, 1000);
return false;
}
return true;
}
Improving Loktar's answer, fixing the following:
Scroll up
Scroll to a display:none element (like hidden div's etc)
function scrollToView(element){
var offset = element.offset().top;
if(!element.is(":visible")) {
element.css({"visibility":"hidden"}).show();
var offset = element.offset().top;
element.css({"visibility":"", "display":""});
}
var visible_area_start = $(window).scrollTop();
var visible_area_end = visible_area_start + window.innerHeight;
if(offset < visible_area_start || offset > visible_area_end){
// Not in view so scroll to it
$('html,body').animate({scrollTop: offset - window.innerHeight/3}, 1000);
return false;
}
return true;
}
After trying all these solutions and many more besides, none of them satisfied my requirement for running old web portal software (10 years old) inside IE11 (in some compatibility mode). They all failed to correctly determine if the element was visible. However I found this solution. I hope it helps.
function scrollIntoViewIfOutOfView(el) {
var topOfPage = window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop;
var heightOfPage = window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight;
var elY = 0;
var elH = 0;
if (document.layers) { // NS4
elY = el.y;
elH = el.height;
}
else {
for(var p=el; p&&p.tagName!='BODY'; p=p.offsetParent){
elY += p.offsetTop;
}
elH = el.offsetHeight;
}
if ((topOfPage + heightOfPage) < (elY + elH)) {
el.scrollIntoView(false);
}
else if (elY < topOfPage) {
el.scrollIntoView(true);
}
}
I made a slightly more generic version of digitalPBK's answer that minimally scrolls an element contained within a div or some other container (including the body). You can pass DOM elements or selectors to the function, as long as the element is somehow contained within the parent.
function scrollToView(element, parent) {
element = $(element);
parent = $(parent);
var offset = element.offset().top + parent.scrollTop();
var height = element.innerHeight();
var offset_end = offset + height;
if (!element.is(":visible")) {
element.css({"visibility":"hidden"}).show();
var offset = element.offset().top;
element.css({"visibility":"", "display":""});
}
var visible_area_start = parent.scrollTop();
var visible_area_end = visible_area_start + parent.innerHeight();
if (offset-height < visible_area_start) {
parent.animate({scrollTop: offset-height}, 600);
return false;
} else if (offset_end > visible_area_end) {
parent.animate({scrollTop: parent.scrollTop()+ offset_end - visible_area_end }, 600);
return false;
}
return true;
}
You can take a look at his awesome link from the jQuery Cookbook:
Determining Whether an Element Is Within the Viewport
Test if Element is contained in the Viewport
jQuery(document).ready(function() {
var viewportWidth = jQuery(window).width(),
viewportHeight = jQuery(window).height(),
documentScrollTop = jQuery(document).scrollTop(),
documentScrollLeft = jQuery(document).scrollLeft(),
$myElement = jQuery('#myElement'),
elementOffset = $myElement.offset(),
elementHeight = $myElement.height(),
elementWidth = $myElement.width(),
minTop = documentScrollTop,
maxTop = documentScrollTop + viewportHeight,
minLeft = documentScrollLeft,
maxLeft = documentScrollLeft + viewportWidth;
if (
(elementOffset.top > minTop && elementOffset.top + elementHeight < maxTop) &&
(elementOffset.left > minLeft && elementOffset.left + elementWidth < maxLeft)
) {
alert('entire element is visible');
} else {
alert('entire element is not visible');
}
});
Test how much of the element is visible
jQuery(document).ready(function() {
var viewportWidth = jQuery(window).width(),
viewportHeight = jQuery(window).height(),
documentScrollTop = jQuery(document).scrollTop(),
documentScrollLeft = jQuery(document).scrollLeft(),
$myElement = jQuery('#myElement'),
verticalVisible, horizontalVisible,
elementOffset = $myElement.offset(),
elementHeight = $myElement.height(),
elementWidth = $myElement.width(),
minTop = documentScrollTop,
maxTop = documentScrollTop + viewportHeight,
minLeft = documentScrollLeft,
maxLeft = documentScrollLeft + viewportWidth;
function scrollToPosition(position) {
jQuery('html,body').animate({
scrollTop : position.top,
scrollLeft : position.left
}, 300);
}
if (
((elementOffset.top > minTop && elementOffset.top < maxTop) ||
(elementOffset.top + elementHeight > minTop && elementOffset.top +
elementHeight < maxTop))
&& ((elementOffset.left > minLeft && elementOffset.left < maxLeft) ||
(elementOffset.left + elementWidth > minLeft && elementOffset.left +
elementWidth < maxLeft)))
{
alert('some portion of the element is visible');
if (elementOffset.top >= minTop && elementOffset.top + elementHeight
<= maxTop) {
verticalVisible = elementHeight;
} else if (elementOffset.top < minTop) {
verticalVisible = elementHeight - (minTop - elementOffset.top);
} else {
verticalVisible = maxTop - elementOffset.top;
}
if (elementOffset.left >= minLeft && elementOffset.left + elementWidth
<= maxLeft) {
horizontalVisible = elementWidth;
} else if (elementOffset.left < minLeft) {
horizontalVisible = elementWidth - (minLeft - elementOffset.left);
} else {
horizontalVisible = maxLeft - elementOffset.left;
}
var percentVerticalVisible = (verticalVisible / elementHeight) * 100;
var percentHorizontalVisible = (horizontalVisible / elementWidth) * 100;
if (percentVerticalVisible < 50 || percentHorizontalVisible < 50) {
alert('less than 50% of element visible; scrolling');
scrollToPosition(elementOffset);
} else {
alert('enough of the element is visible that there is no need to scroll');
}
} else {
// element is not visible; scroll to it
alert('element is not visible; scrolling');
scrollToPosition(elementOffset);
}
The following code helped me achieve the result
function scroll_to_element_if_not_inside_view(element){
if($(window).scrollTop() > element.offset().top){
$('html, body').animate( { scrollTop: element.offset().top }, {duration: 400 } );
}
}
Here is the solution I came up with, working both up and down and using only Vanilla Javascript, no jQuery.
function scrollToIfNotVisible(element) {
const rect = element.getBoundingClientRect();
// Eventually an offset corresponding to the height of a fixed navbar for example.
const offset = 70;
let scroll = false;
if (rect.top < offset) {
scroll = true;
}
if (rect.top > window.innerHeight) {
scroll = true;
}
if (scroll) {
window.scrollTo({
top: (window.scrollY + rect.top) - offset,
behavior: 'smooth'
})
}
}
There is a jQuery plugin which allows us to quickly check if a whole element (or also only part of it) is within the browsers visual viewport regardless of the window scroll position. You need to download it from its GitHub repository:
Suppose to have the following HTML and you want to alert when footer is visible:
<section id="container">
<aside id="sidebar">
<p>
Scroll up and down to alert the footer visibility by color:
</p>
<ul>
<li><span class="blue">Blue</span> = footer <u>not visible</u>;</li>
<li><span class="yellow">Yellow</span> = footer <u>visible</u>;</li>
</ul>
<span id="alert"></span>
</aside>
<section id="main_content"></section>
</section>
<footer id="page_footer"></footer>
So, add the plugin before the close of body tag:
<script type="text/javascript" src="js/jquery-1.12.0.min.js"></script>
<script type="text/javascript" src="js/jquery_visible/examples/js/jq.visible.js"></script>
After that you can use it in a simple way like this:
<script type="text/javascript">
jQuery( document ).ready(function ( $ ) {
if ($("footer#page_footer").visible(true, false, "both")) {
$("#main_content").css({"background-color":"#ffeb3b"});
$("span#alert").html("Footer visible");
} else {
$("#main_content").css({"background-color":"#4aafba"});
$("span#alert").html("Footer not visible");
}
$(window).scroll(function() {
if ($("footer#page_footer").visible(true, false, "both")) {
$("#main_content").css({"background-color":"#ffeb3b"});
$("span#alert").html("Footer visible");
} else {
$("#main_content").css({"background-color":"#4aafba"});
$("span#alert").html("Footer not visible");
}
});
});
</script>
Here a demo
No-JQuery version.
The particular case here is where the scroll container is the body (TBODY, table.body) of a TABLE (scrolling independently of THEAD). But it could be adapted to any situation, some simpler.
const row = table.body.children[ ... ];
...
const bottomOfRow = row.offsetHeight + row.offsetTop ;
// if the bottom of the row is in the viewport...
if( bottomOfRow - table.body.scrollTop < table.body.clientHeight ){
// ... if the top of the row is in the viewport
if( row.offsetTop - table.body.scrollTop > 0 ){
console.log( 'row is entirely visible' );
}
else if( row.offsetTop - table.body.scrollTop + row.offsetHeight > 0 ){
console.log( 'row is partly visible at top')
row.scrollIntoView();
}
else {
console.log( 'top of row out of view above viewport')
row.scrollIntoView();
}
}
else if( row.offsetTop - table.body.scrollTop < table.body.clientHeight ){
console.log( 'row is partly visible at bottom')
row.scrollIntoView();
}
else {
console.log( 'row is out of view beneath viewport')
row.scrollIntoView();
}
I think this is the complete answer. An elevator must be able to go both up and down ;)
function ensureVisible(elementId, top = 0 /* set to "top-nav" Height (if you have)*/) {
let elem = $('#elementId');
if (elem) {
let offset = elem.offset().top - $(window).scrollTop();
if (offset > window.innerHeight) { // Not in view
$('html,body').animate({ scrollTop: offset + top }, 1000);
} else if (offset < top) { // Should go to top
$('html,body').animate({ scrollTop: $(window).scrollTop() - (top - offset) }, 1000);
}
}
}