Zoom div content on scroll - javascript

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/

Related

How to make CTRL + '+' in js or jquery [duplicate]

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

Float DIV is not fixed

I install Float Left Right Advertising plugin on my site: www.displej.me and I set banners at the side of site. But when you scroll baners are not fixed, they follow page but they are refreshing and blinking. Also, when I'm scrolling down they stay fixed aside and later start to follow the page. Ths is JS code:
function FloatTopDiv()
{
startLX = ((document.body.clientWidth -MainContentW)/2) - (LeftBannerW+LeftAdjust) , startLY = TopAdjust;
startRX = ((document.body.clientWidth -MainContentW)/2) + (MainContentW+RightAdjust) , startRY = TopAdjust;
var d = document;
function ml(id)
{
var el=d.getElementById?d.getElementById(id):d.all?d.all[id]:d.layers[id];
el.sP=function(x,y){this.style.left=x + 'px';this.style.top=y + 'px';};
el.x = startRX;
el.y = startRY;
return el;
}
function m2(id)
{
var e2=d.getElementById?d.getElementById(id):d.all?d.all[id]:d.layers[id];
e2.sP=function(x,y){this.style.left=x + 'px';this.style.top=y + 'px';};
e2.x = startLX;
e2.y = startLY;
return e2;
}
window.stayTopLeft=function()
{
if (document.documentElement && document.documentElement.scrollTop)
var pY = document.documentElement.scrollTop;
else if (document.body)
var pY = document.body.scrollTop;
if (document.body.scrollTop > 200){startLY = 3;startRY = 3;} else {startLY = TopAdjust;startRY = TopAdjust;};
ftlObj.y += (pY+startRY-ftlObj.y)/1;
ftlObj.sP(ftlObj.x, ftlObj.y);
ftlObj2.y += (pY+startLY-ftlObj2.y)/1;
ftlObj2.sP(ftlObj2.x, ftlObj2.y);
setTimeout("stayTopLeft()", 1);
}
ftlObj = ml("divAdRight");
//stayTopLeft();
ftlObj2 = m2("divAdLeft");
stayTopLeft();
}
function ShowAdDiv()
{
var objAdDivRight = document.getElementById("divAdRight");
var objAdDivLeft = document.getElementById("divAdLeft");
objAdDivRight.style.display = "block";
objAdDivLeft.style.display = "block";
FloatTopDiv();
}
What to do? I try to change the numbers in the code but not sucsses.
clear:both
is something I would try to keep the sides free from the centered divs movements.

jQuery: change class after conditional is met

I created this site where you have multiple sliders moving vertically using this example on stackoverflow > here < along with this fiddle.
The site when loaded has an overflow: hidden on the body and position fixed on my main content div(div class="content-fs row"). The idea is that when you first arrive on the page, you scroll through each slide and once you hit the last one, the position changes on the main content div(div class="content-fs row") from fixed to static and the overflow: hidden is removed from the body. I'm having trouble writing the conditional statement that says "if its the last slider, change the position." The jquery below is the code i'm using for the site along with the conditional statement that doesn't work.
Any pointers/advice would be greatly appreciated!
jquery:
function scrollLax(){
/*
initialize
*/
var scrollDown = false;
var scrollUp = false;
var scroll = 0;
var $view = $('#portfolio');
var t = 0;
var h = $view.height() - 250;
$view.find('.portfolio-sliders').each(function() {
var $moving = $(this);
// position the next moving correctly
if($moving.hasClass('from-bottom')) {
$moving.css('top', h); // subtract t so that a portion of the other slider is showing
}
// make sure moving is visible
$moving.css('z-index', 10);
});
var $moving = $view.find('.portfolio-sliders:first-child');
$moving.css('z-index', 10);
/*
event handlers
*/
var mousew = function(e) {
var d = 0;
if(!e) e = event;
if (e.wheelDelta) {
d = -e.wheelDelta/3;
} else if (e.detail) {
d = e.detail/120;
}
parallaxScroll(d);
}
if (window.addEventListener) {
window.addEventListener('DOMMouseScroll', mousew, false);
}
window.onmousewheel = document.onmousewheel = mousew;
/*
parallax loop display loop
*/
window.setInterval(function() {
if(scrollDown)
parallaxScroll(4);
else if(scrollUp)
parallaxScroll(-4);
}, 50);
function parallaxScroll(scroll) {
// current moving object
var ml = $moving.position().left;
var mt = $moving.position().top;
var mw = $moving.width();
var mh = $moving.height();
// calc velocity
var fromBottom = false;
var vLeft = 0;
var vTop = 0;
if($moving.hasClass('from-bottom')) {
vTop = -scroll;
fromBottom = true;
}
// calc new position
var newLeft = ml + vLeft;
var newTop = mt + vTop;
// check bounds
var finished = false;
if(fromBottom && (newTop < t || newTop > h)) {
finished = true;
newTop = (scroll > 0 ? t : t + h);
}
// set new position
$moving.css('left', newLeft);
$moving.css('top', newTop);
// if finished change moving object
if(finished) {
// get the next moving
if(scroll > 0) {
$moving = $moving.next('.portfolio-sliders');
if($moving.length == 0)
$moving = $view.find('.portfolio-sliders:last');
//this is where I am trying to add the if conditional statement.
if ('.portfolio-sliders:last')
$('.content-fs.row').css({'position': 'static'});
if('.portfolio-sliders:last' && (mt == 0))
$('html, body').removeClass('overflow');
} else {
$moving = $moving.prev('.portfolio-sliders');
if($moving.length == 0)
$moving = $view.find('.portfolio-sliders:first-child');
//reverse the logic and if last slide change position
if('.portfolio-sliders:first-child')
$('.content-fs.row').css({'position': 'fixed'});
}
}
// for debug
//$('#direction').text(scroll + "/" + t + " " + ml + "/" + mt + " " + finished + " " + $moving.text());
}
}
Your code as it is simply asks whether .portfolio-sliders:last exists. Seems you should be doing:
if ($moving == $('.portfolio-sliders:last') )
or something along those lines, instead checking whether the active slide is the last.

Make img not to move in html

I have an image on my page, and I would like to listen to onmousemove events when the mouse is down. But I can't because in my browser (Firefox), when I drag an image, well actually I drag the image, which I don't want.
Here's my code:
JavaScript part:
document.onmousemove=getMouseCoordinates;
var x;
var y;
var clicked = false;
function getMouseCoordinates(event){
ev = event || window.event;
x = ev.pageX;
y = ev.pageY;
}
function onClickMap(){
var obj = document.getElementById("selectArea");
var tempX = x;
var tempY = y;
obj.style.left = tempX + "px";
obj.style.top = tempY + "px";
clicked = true;
}
function onMoveMap(){
if(clicked){
var obj = document.getElementById("selectArea");
var xToSize = Math.abs(parseInt(obj.style.left) - x);
var yToSize = Math.abs(parseInt(obj.style.top) - y);
obj.style.width = xToSize + "px";
obj.style.height = yToSize + "px";
}
}
HTML part:
<img src="pixels.png" id ="pixelDiv" usemap="#pixelMap" onClick="onClickMap()" onmousemove="onMoveMap()">
Here is a jQuery solution.
This will disable all drags:
$(document).bind("dragstart", function() {
return false;
});
If you want to disable drags only on img elements:
$(document).bind("dragstart", function(e) {
if (e.target.nodeName.toUpperCase() == "IMG") {
return false;
}
});
You can add a mousedown handler that just returns false. This seems to stop the dragging in FF.
ok it's nice, but I suppose it is something firefox specific, now I disabled the onlcick and onmove methods of my image, but I can stil drag the image
now I've found the solution, I was looking for this
http://www.develobert.info/2008/10/disable-firefox-image-drag.html

Changing the browser zoom level

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

Categories

Resources