Re-sizing Image Width Using JavaScript - javascript

I am trying to re-size an image in a popup. The original image is 6000 x 4000. I do a check to see if the image is greater than 500, and if so I just try and set the image to 500. Trying to set it using 'this', makes the pop open in a tab and the image is still its original size. If I try and set the image not using 'this', the pop up works as intended regarding where it is positioned on screen and the size of the box, but the image, is still its original size--6000 x 4000. (PS: I have to use ES5 as well.)
What gives?
Thanks,
CM
<script language="javascript" type="text/javascript"><!--
// let i=0;
function resize() {
console.log("Testing");
let i=0;
if (window.navigator.userAgent.indexOf('MSIE 6.0') != -1 && window.navigator.userAgent.indexOf('SV1') != -1) {
i=30; //This browser is Internet Explorer 6.x on Windows XP SP2
} else if (window.navigator.userAgent.indexOf('MSIE 6.0') != -1) {
i=0; //This browser is Internet Explorer 6.x
} else if (window.navigator.userAgent.indexOf('Firefox') != -1 && window.navigator.userAgent.indexOf("Windows") != -1) {
i=25; //This browser is Firefox on Windows
} else if (window.navigator.userAgent.indexOf('Mozilla') != -1 && window.navigator.userAgent.indexOf("Windows") != -1) {
i=45; //This browser is Mozilla on Windows
} else {
i=80; //This is all other browsers including Mozilla on Linux
}
var imgWidth = document.images[0].width;
var imgHeight = document.images[0].height;
console.log("Original image width is: " + imgWidth);
console.log("Original image height is: " + imgHeight);
if(imgWidth > 500){
//Shrink the image to size of popup frame
this.imgWidth = 500;
this.imgHeight = 500;
console.log("Adjusted image width is: " + imgWidth);
console.log("Adjusted image height is: " + imgHeight);
//Get display/screen width and height
var screenWidth = screen.width;
var screenHeight = screen.height;
console.log("Screen width is: " + screenWidth);
console.log("Screen height is: " + screenHeight);
//Set popup position on display/screen
var leftpos = screenWidth / 2 ;
var toppos = screenHeight / 2 - imgHeight / 2;
console.log("Left position is: " + leftpos);
console.log("Top position is: " + toppos);
//Set popup frame width and height equal to adjusted image width and height
var frameWidth = imgWidth;
var frameHeight = imgHeight+i;
console.log("Frame width is: " + frameWidth);
console.log("Frame height is: " + frameHeight);
window.moveTo(leftpos, toppos);
window.resizeTo(frameWidth,frameHeight+i);
}
else if (document.documentElement && document.documentElement.clientWidth) {
var imgHeight = document.images[0].height + 40 - i;
var imgWidth = document.images[0].width + 20;
var height = screen.height;
var width = screen.width;
var leftpos = width / 2 - imgWidth / 2;
var toppos = height / 2 - imgHeight / 2;
frameWidth = imgWidth;
frameHeight = imgHeight + i;
window.moveTo(leftpos, toppos);
window.resizeTo(frameWidth, frameHeight + i);
} else if (document.body) {
window.resizeTo(document.body.clientWidth, document.body.clientHeight - i);
}
self.focus();
}//end resize() function
//--></script>

Use
var imgWidth = document.images[0].style.width;
instead of
var imgWidth = document.images[0].width;

Related

Resize window with smooth transition for different height sizes

Some context:
I'm working on a Chrome Extension where the user can launch it via default "popup.html", or if the user so desires this Extension can be detached from the top right corner and be used on a popup window via window.open
This question will also apply for situations where users create a Shortcut for the extension on Chrome via:
"..." > "More tools" > "Create Shortcut"
Problem:
So what I need is for those cases where users use the extension detached via window.open or through a shortcut, when navigating through different options, for the Height of the window to be resized smoothly.
I somewhat achieve this but the animation is clunky and also the final height is not always the same. Sometimes I need to click twice on the button to resize too because 1 click won't be enough. Another issue is there is also some twitching of the bottom text near the edge of the window when navigating.
Here's what I got so far:
(strWdif and strHdif are used to compensate for some issues with CSS setting proper sizes which I haven't figured out yet.)
const popup = window;
function resizeWindow(popup) {
setTimeout(function () {
var strW = getComputedStyle(window.document.querySelector(".body_zero")).getPropertyValue("width");
var strW2 = strW.slice(0, -2);
var strWdif = 32;
var bodyTargetWidth = (parseFloat(strW2) + parseFloat(strWdif));
var strH = getComputedStyle(window.document.querySelector(".body_zero")).getPropertyValue("height");
var strH2 = strH.slice(0, -2);
var strHdif = 54;
var bodyTargetHeight = (parseFloat(parseInt(strH2)) + parseFloat(strHdif));
var height = window.innerHeight;
console.log("Window Height: ", height, "CSS Height: ", bodyTargetHeight);
var timer = setInterval(function () {
if (height < bodyTargetHeight) {
popup.resizeTo(bodyTargetWidth, height += 5);
if (height >= bodyTargetHeight) {
clearInterval(timer);
}
} else if (height > bodyTargetHeight) {
popup.resizeTo(bodyTargetWidth, height -= 5);
if (height <= bodyTargetHeight) {
clearInterval(timer);
}
} else {
clearInterval(timer);
}
}, 0);
}, 0400);
}
Question:
Is there a way to make this more responsive, and smooth and eliminate all the twitching and clunkiness?
I guess the issue might be that I am increasing/diminishing by 5 pixels at a time but that is the speed I need. Maybe there is another way to increase/decrease by 1px at a faster rate? Could this be the cause of the twitching and clunkiness?
Also, I should add that troubleshooting this is difficult because the browser keeps crashing so there is also a performance issue sometimes when trying different things.
EDIT:
Another option using resizeBy:
function animateClose(time) {
setTimeout(function () {
var strW = getComputedStyle(window.document.querySelector(".body_zero")).getPropertyValue("width");
var strW2 = strW.slice(0, -2);
var strWdif = 32;
var bodyTargetWidth = (parseFloat(strW2) + parseFloat(strWdif));
var strH = getComputedStyle(window.document.querySelector(".body_zero")).getPropertyValue("height");
var strH2 = strH.slice(0, -2);
var strHdif = 54;
var bodyTargetHeight = (parseFloat(parseInt(strH2)) + parseFloat(strHdif));
var w = window.innerWidth; //Get window width
var h = window.innerHeight; //Get window height
var loops = time * 0.1; //Get nb of loops
var widthPercentageMinus = (w / loops) * -0;
var heightPercentageMinus = (h / loops) * -1;
var widthPercentagePlus = (w / loops) * +0;
var heightPercentagePlus = (h / loops) * +1;
console.log("Window Height: ", h, "CSS Height: ", bodyTargetHeight);
var loopInterval = setInterval(function () {
if (h > bodyTargetHeight) {
window.resizeBy(widthPercentageMinus, heightDecrheightPercentageMinuseasePercentageMinus);
} else if (h < bodyTargetHeight) {
window.resizeBy(widthPercentagePlus, heightPercentagePlus);
} else {
clearInterval(loopInterval);
}
}, 1);
}, 0400);
}
This one is a bit more smooth but I can't make it stop at the desired Height. It also is not differentiating between resizing up or down, also crashes the browser sometimes.
maybe with requestAnimationFrame
try something like this (not tested):
function resizeWindow(popup) {
var gcs = getComputedStyle(window.document.querySelector(".body_zero"));
var strW = gcs.getPropertyValue("width");
var strW2 = strW.slice(0, -2);
var strWdif = 32;
var bodyTargetWidth = (parseFloat(strW2) + parseFloat(strWdif));
var strH = gcs.getPropertyValue("height");
var strH2 = strH.slice(0, -2);
var strHdif = 54;
var bodyTargetHeight = (parseFloat(parseInt(strH2)) + parseFloat(strHdif));
var height = window.innerHeight;
console.log("Window Height: ", height, "CSS Height: ", bodyTargetHeight);
window.myRequestAnimationFrame = window.requestAnimationFrame || window.webkitRequestAnimationFrame;
var hStep = 2; //choose the step. Must be an integer
function internalFunc() {
if (Math.abs(height - bodyTargetHeight) > hStep) {
if (height < bodyTargetHeight)
hStep *= 1;
else if (height > bodyTargetHeight)
hStep *= -1;
popup.resizeBy(0, hStep);
height += hStep;
window.myRequestAnimationFrame(internalFunc)
} else
popup.resizeBy(0, bodyTargetHeight - height)
}
popup.resizeTo(bodyTargetWidth, height);
window.myRequestAnimationFrame(internalFunc)
}
<html>
<head>
<script>
const bodyTargetWidth = 150;
const bodyTargetHeight = 250; //target height
var height; //height at beginning
window.myRequestAnimationFrame = window.requestAnimationFrame || window.mozRequestAnimationFrame || window.webkitRequestAnimationFrame;
var hStep = 5; //choose the step. Must be an integer
var dir;
var myPopup;
function doResize() {
function internalFunc() {
console.log('height: ', height) ;
if (Math.abs(height - bodyTargetHeight) > hStep) {
dir = Math.sign(bodyTargetHeight - height);
myPopup.resizeBy(0, dir * hStep);
height += dir * hStep;
window.myRequestAnimationFrame(internalFunc)
} else
myPopup.resizeBy(0, bodyTargetHeight - height)
}
if (!myPopup || myPopup?.closed) {
myPopup = window.open("about:blank", "hello", "left=200,top=200,menubar=no,status=no,location=no,toolbar=no");
height = 150;
myPopup.resizeTo(bodyTargetWidth, height);
} else {
myPopup.focus();
height = myPopup.outerHeight
}
myPopup.resizeTo(bodyTargetWidth, height);
window.myRequestAnimationFrame(internalFunc)
}
document.addEventListener('DOMContentLoaded', _ => document.getElementById('myBtn').addEventListener('click', doResize))
</script>
</head>
<body>
<button type="button" id="myBtn">Create popup<br>\<br>Reset popup height</button><br>
<p>First create the popup, then change popup height and click the button above again</p>
</body>
</html>

Increase element size everytime window is resized

my problem today is that I have 12 elements with size 60px x 60px and I'd like to increase the size with 0.2 everytime the screen size increase of 10px, with javascript. For example: screensize 600px and element size 60.2 x 60.2, screensize 610px and element size 60.4 x 60.4 and so on. It would give something like this to increase :
var circle_data={
container: document.querySelector(".container"),
classname: "astro-item",
nb_elem: 12,
elem_size: 60,
};
var screenSize = window.innerWidth;
circle_data.elem_size += 0.2;
The thing is that I don't know how to increase everytime the screen size increase by 10px
Thanks for your help !!
So with your answers here's the code I tried but it doesn't work, maybe because I already have a function that set elements size up, here's the full script:
function circle_container(objdata) {
var circle_dim=objdata.container.getBoundingClientRect();
var rayon=Math.round(circle_dim.width/2 - objdata.elem_size/2);
var center_x=rayon;
var center_y=rayon;
if (objdata.rayon) rayon*=objdata.rayon/100;
for(var i=0;i<objdata.nb_elem;i++) {
var new_elem=objdata.container.querySelector("."+objdata.classname+i);
if (!new_elem) {
var new_elem=document.createElement("button");
new_elem.className="astro-item"+" "+objdata.classname+i;
var new_img=document.createElement("img");
new_img.src = astroList[i].icon;
}
new_elem.style.position="absolute";
new_elem.style.width=objdata.elem_size+"px";
new_elem.style.height=objdata.elem_size+"px";
new_elem.style.top=Math.round( (center_y - rayon * Math.cos(i*(2*Math.PI)/objdata.nb_elem)))+"px";
new_elem.style.left=Math.round( (center_x + rayon * Math.sin(i*(2*Math.PI)/objdata.nb_elem)))+"px";
objdata.container.appendChild(new_elem);
new_elem.appendChild(new_img);
}
}
var circle_data={
container: document.querySelector(".container"),
classname: "astro-item",
nb_elem: 12,
elem_size: 60,
};
function onResize(e) {
var screenSize = e.target.outerWidth;
var width = (screenSize - (screenSize % 100) + (((screenSize + 10) % 100)/10 *2))/10;
var items = document.querySelectorAll('.astro-item');
for(var i = 0; i < items.length; i++) {
items[i].innerHTML = 'width: ' + screenSize + ' size: ' + width ;
}
}
circle_container(circle_data);
addEvent(window,"resize",function() {
circle_container(circle_data);
onresize();
});
The purpose of this function is to create 12 buttons aligned in circle (just like a wheel) and fully responsive, that's why I need them to get bigger when the screen gets larger. Thank you so much !
With pure javascript bind an event onresize and set size based on window width. The size increase 0.2 everytime the screen size increase of 10px:
window.addEventListener("resize", onresize);
var onresize = function(e) {
var width = e.target.outerWidth;
circle_data.elem_size = (width - (width % 100) + (((width + 10) %
100)/10 *2))/10;
}
Working example:
(open in full screen)
*Edited for max min limitations
var min = 500; //min width in pixel
var max= 700; //max width in pixel
window.addEventListener("resize", onresize);
var onresize = function(e) {
var width = e.target.outerWidth;
var s = (width - (width % 100) + (((width + 10) % 100)/10 *2))/10
if(width <=max && width >=min){
//change size here
document.getElementById('s').innerHTML = 'width: ' + width + ' size: ' + s ;
}
}
<span id='s'> </span>

Iframe height definition in IE 7

I have a problem with resizing iframe content in IE7.
I have an external iframe
<IFRAME id=fl_game src="my_iframe_page" frameBorder=0 allowTransparency scrolling=no></IFRAME>
with width=100%, height=93%
and add my page into it. Here is a page body
<div id="container">
<div id="game-box">
<div id="flashcontent">
</div>
</div>
</div>
<script type="text/javascript">
swfobject.embedSWF("<%=application.getContextPath()%>/flash/<%= request.getParameter(PARAM_GAME) %>/game.swf", "flashcontent", gameWidth, gameHeight, "10.1", "/flash/expressInstall.swf", flashvars, params);
</script>
On my page I add resize events.
if (window.addEventListener) {
window.addEventListener("load", resizeGame, false);
window.addEventListener("resize", resizeGame, false);
} else if (window.attachEvent) {
window.attachEvent("onload", resizeGame);
window.attachEvent("onresize", resizeGame);
} else {
window.onload = function() {resizeGame();};
window.onresize = function() {resizeGame();}
}
Here is my resizeGame function
function resizeGame(isIEResize) {
var flash = document.getElementById('flashcontent');
var screen = screenSize();
var width = screen.width;
var height = screen.height;
var left = 0;
var top = 0;
if (height * 1.5 > width) {
height = width / 1.5
} else {
width = height * 1.5;
}
flash.width = width;
flash.height = height;
document.getElementById('flashcontent').style.width = width + 'px';
document.getElementById('flashcontent').style.height = height + 'px';
document.getElementById('flashcontent').style.top = '50%';
document.getElementById('flashcontent').style.left = '50%';
if (width < screen.width) {
left = (screen.width - width) / 2 + left;
}
if (height < screen.height) {
top = (screen.height - height) / 2;
}
document.getElementById('game-box').style.top = top + 'px';
document.getElementById('game-box').style.left = left + 'px';
}
function screenSize() {
var w, h;
w = (window.innerWidth ? window.innerWidth : (document.documentElement.clientWidth ? document.documentElement.clientWidth : document.body.offsetWidth));
h = (window.innerHeight ? window.innerHeight : (document.documentElement.clientHeight ? document.documentElement.clientHeight : document.body.offsetHeight));
return {width:w, height:h};
}
And here is a question:
In IE7 function screenSize() gives me wrong height on load. Under other browsers and IE>7 function screenSize() gives me correct height. That's why I can't resize my content properly.
And when I explicitly resize a window, function screenSize() starts to give correct height.
Here some screens before explicit resizing and after it.
screenSize() gives strange height ONLY in IE7.
I am ready to add any extra information to find a reason of this situation.
I hope someone can help me to find out how to define iframe height in IE7. Any help will be useful.

Fill box dynamically with screen height

I have a box, which I am trying to size perfectly to fit within the browser viewport if the image is not larger then it. So the image would appear to be centered within the window.
Currently I don' think my method of seeking the browser height is working. And for some reason there is a lot of extra space
Example (src)
here is where I define the page sizes
if ( style['img-width'] > screenwidth ) {
style['body-width'] = style['img-width'] + ( style['img-padding'] * 2 );
} else {
style['body-width'] = screenwidth;
}
style['body-height'] = ( style['img-height'] > screenheight ) ?
( style['img-height'] +
( style['img-padding'] * 2 ) +
style['header-height']
) :
screenheight;
$('body').css({ 'width': style['body-width']+'px' });
theater.css({
'width': style['body-width']+'px',
'height': style['body-height']+'px',
});
theaterheadcon.css('width', style['body-width']+'px');
theaterheader.css('width', style['body-width']+'px');
How I am defining screen width/height
screenwidth = isNaN(window.outerWidth) ? window.clientWidth : window.outerWidth,
screenheight = isNaN(window.outerHeight) ? window.clientHeight : window.outerHeight;
Here is the basic of centering items to a content with javascript and css:
/*css*/
#myImage
{
position:absolute;
}
And in java:
/*javascript*/
var img=$('#myImage');
var winWidth=$(window).width();
var winHeight=$(window).height();
if(img.height()>winHeight)
{
img.css('height', winHeight + "px");
}
img.css('left',(winWidth/2) + "px");
img.css('top',(winHeight/2) + "px");
img.css('margin-left',(-(img.width()/2)) + "px");
img.css('margin-top',(-(img.height()/2)) + "px");
The margin approach guaranties that the image will stay at the center even on page resize
I tried here in DIVs in your case code will detect your image size itself
$(document).ready(function(){
var windowheight = $(window).height();
var windowwidth = $(window).width();
var boxheight = $('#box').outerHeight();
var boxwidth = $('#box').outerWidth();
var imgheight = $('.img').outerHeight();
var imgwidth = $('.img').outerWidth();
if(imgheight > boxheight || imgwidth > boxwidth){
$('#box').css('height', windowheight).css('width', windowwidth);
$('.img').css('margin-left',((windowwidth - imgwidth)/2)+'px');
$('.img').css('margin-top',((windowheight - imgheight)/2)+'px');
}
});
DEMO
change your img width in css to see the action
if you want your div to not going outside the window after margin the image to center use that code
$(document).ready(function(){
var windowheight = $(window).height();
var windowwidth = $(window).width();
var boxheight = $('#box').outerHeight();
var boxwidth = $('#box').outerWidth();
var imgheight = $('.img').outerHeight();
var imgwidth = $('.img').outerWidth();
if(imgheight > boxheight || imgwidth > boxwidth){
$('#box').css('position','absolute').css('width', 'auto').css('height', 'auto').css('left', '0').css('top', '0').css('right', '0').css('bottom', '0');
$('.img').css('margin-left',((windowwidth - imgwidth)/2)+'px');
$('.img').css('margin-top',((windowheight - imgheight)/2)+'px');
}
});
DEMO

Mouse on left of screen move image to left, same when mouse on right of screen

I'm trying to get an image that is around 1920x1200px to pan around on a 800x600px browser window.
So if my mouse is on the top-left of the browser window the image is alined so it's top-left margins are on the top-left of the browser window. The same goes for the bottum-right.
So if the mouse is in the centre of the screen the image should be centered too.
Im not sure what calculations are needed as my math is a bit rusty.
Currently I'm using a bit of javascript that just moves the image using CSS's top/left properties but without much success as it's just moving the picture around from it's top/left corner.
I'v also set the image's position to absolute in css.
function updateImgPosition( e )
{
var avatar = document.getElementById("avatar");
// Width
var windowWidth = window.innerWidth;
var mouseWidthLocation = e.x;
var percentOfWidth = (100 / windowWidth) * mouseWidthLocation;
// Height
var windowHeight = window.innerHeight;
var mouseHeightLocation = e.y;
var percentOfHeight = (100 / windowHeight) * mouseHeightLocation;
avatar.style.top = percentOfHeight + "%";
avatar.style.left = percentOfWidth + "%";
}
document.onmousemove = updateImgPosition;
This is a demo of what I have: http://jsfiddle.net/uQAmQ/1/
Fiddle: http://jsfiddle.net/uQAmQ/2/
You should not "pan" on an absolutely positioned element, because the window's width and height keep changing according to the image. A smoother solution involves using a background image. See the middle of my answer for the used logic.
Consider this JavaScript (read comments; HTML + CSS at fiddle):
(function(){ //Anonymous function wrapper for private variables
/* Static variables: Get the true width and height of the image*/
var avatar = document.getElementById("avatar");
var avatarWidth = avatar.width;
var avatarHeight = avatar.height;
var windowWidth = window.innerWidth;
var windowHeight = window.innerHeight;
/* Logic: Move */
var ratioY = (avatarHeight - windowHeight) / windowHeight;
var ratioX = (avatarWidth - windowWidth) / windowWidth;
function updateImgPosition( e ) {
var mouseY = e.pageX; //e.pageX, NOT e.x
var mouseX = e.pageY;
var imgTop = ratioY*(-mouseY);
var imgLeft = ratioX*(-mouseX);
document.body.style.backgroundPosition = imgLeft + "px " + imgTop + "px";
}
/* Add event to WINDOW, NOT "document"! */
window.onmousemove = updateImgPosition;
})();
The logic behind it:
Relative units cannot be used, because the image size is specified in absolute units.
The offsets should change according to a specific ratio, which is similar to: image size divided by window size.However, this ratio is not complete: The image would disappear at the bottom/left corner of the window. To fix this, substract the window's size from the image's size. The result can be found in the code at variable ratioX and ratioY.
The previous code had to be loaded at the window.onload event, because the image's size was dynamically calculated. For this reason, a HTML element was also included in the body.
The same code can be written much smaller and efficient, by specifying the size of the background in the code. See this improved code. Fiddle: http://jsfiddle.net/uQAmQ/3/
(function(){ //Anonymous function wrapper for private variables
/* Static variables: Get the true width and height of the image*/
var avatarWidth = 1690;
var avatarHeight = 1069;
var windowWidth = window.innerWidth;
var windowHeight = window.innerHeight;
/* Logic: Move */
var ratioY = (avatarHeight - windowHeight) / windowHeight;
var ratioX = (avatarWidth - windowWidth) / windowWidth;
function updateImgPosition( e ) {
var mouseX = e.pageX; //e.pageX, NOT e.x
var mouseY = e.pageY;
var imgTop = ratioY*(-mouseY);
var imgLeft = ratioX*(-mouseX);
document.body.style.backgroundPosition = imgLeft + "px " + imgTop + "px";
}
/* Add event to WINDOW, NOT "document"! */
window.onmousemove = updateImgPosition;
})();
If you don't mind a decreased code readability, the following code is the best solution, Fiddle: http://jsfiddle.net/uQAmQ/4/:
(function(){ //Anonymous function wrapper for private variables
/* Static variables: Get the true width and height of the image*/
var windowWidth = window.innerWidth;
var windowHeight = window.innerHeight;
var ratioY = (windowHeight - 1069) / windowHeight;
var ratioX = (windowWidth - 1690) / windowWidth;
window.onmousemove = function( e ) {
document.body.style.backgroundPosition = ratioX * e.pageX + "px " + ratioY * e.pageY + "px";
}
})();

Categories

Resources