Image Resize NaN Error - javascript

I am getting NaN back from one of my functions. After doing the research I found out the answer was not a number but I figured that it must be imposable. I am only working with numbers and I am rounding the answer.
function resize(iid, eid) {
//Get the ID of the elements (ele being the container that the image is in and img being the image its self)
var img = document.getElementById('img');
var ele = document.getElementById('contaner');
//makes the var needed
var currentwidth = ele.clientWidth;
var currentheight = ele.clientHeight;
var naturalwidth = img.naturalHeight;
var naturalheight = img.naturalWidth;
var newheight = naturalheight;
var newwidth = naturalwidth;
var x;
//runs a loop that should size the image
while (newheight > currentheight && newwidth > currentwidth){
x = x + 1;
newheight = naturalheight / x;
newwidth = naturalwidth / x;
}
newheight = Math.round(newheight);
newwidth = Math.round(newwidth);
//alerts out the answers
alert(newheight);
alert(newwidth)
}
#contaner {
height: 450px;
width: 90%;
margin: 5% auto;
position: relative;
}
#img {
height: 450px;
width: 90%;
}
<div id="contaner">
<img src = "..\..\Resorces\Images\SlideShow\img1.jpg" style="width:652px;height:489px;" id="img"/>
<div id="left_holder"><img onClick="slide(-1)" src="..\..\Resorces\Images\arrow_left.png" class="left"/></div>
<div id="right_holder"><img onClick="slide(+1)" src="..\..\Resorces\Images\arrow_right.png" class="right"/></div>
</div>

You have:
var x;
And then when you do:
x = x + 1;
x is undefined it get cast to string and then concatenated with the 1. So:
x = 'undefined1';
When x is used on a division it returns NaN.
Solution: Change x declaration:
var x = 0;

NaN is due by this line of code:
var x;
while (newheight > currentheight && newwidth > currentwidth) {
x = x + 1; //<- Here x is undefined
}

Related

how to run a function only for the clicked element and not for the whole class

I am looking for a way to resize individually several div on a page (like a browser window, that you can resize from a bottom corner), keeping the same proportions/ratio. I made the code work for a class .handle and .dragger, but all the div with the same class are being modified at the same time, while I would like it to be executed only for the div we click on.
Here is the code to resize that I'm working with:
$(".handle").bind('mousedown', draggerDown);
$("body").bind('mouseup', draggerUp);
function calculateNewSize(size) {
// {currHeight, currWidth, newHeight, newWidth, offsetX, offsetY}
var newWidth;
var newHeight;
if (Math.abs(size.offsetX) > Math.abs(size.offsetY)) {
newWidth = size.currWidth + size.offsetX;
newHeight = newWidth * (size.currHeight / size.currWidth);
} else {
newHeight = size.currHeight + size.offsetY;
newWidth = newHeight * (size.currWidth / size.currHeight);
}
return {
"height": newHeight,
"width": newWidth
};
}
function draggerDown() {
event.stopPropagation();
event.preventDefault();
currentX = event.pageX;
currentY = event.pageY;
currentHeight = $(".dragger").height();
currentWidth = $(".dragger").width();
$("body").bind('mousemove', draggerMove);
}
function draggerMove() {
var draggerElements = document.getElementsByClassName("dragger");
for (var n = 0; n < draggerElements.length; ++n) {
var targetStyle = window.getComputedStyle(draggerElements[n], null);
var newHeight = currentHeight + (event.pageY - currentY);
var newWidth = currentWidth + (event.pageX - currentX);
// AT THIS POINT, THE LOGIC COMES IN.
// CUSTOMIZE 'calculateNewSize' function above
var newSize = calculateNewSize({
"currHeight": currentHeight,
"currWidth": currentWidth,
"newHeight": newHeight,
"newWidth": newWidth,
"offsetX": (event.pageX - currentX),
"offsetY": (event.pageY - currentY)
});
currentHeight = newSize.height;
currentWidth = newSize.width;
newHeight = newSize.height;
newWidth = newSize.width;
// AT THIS POINT, THE LOGIC IS DONE.
// SIZES SHOULD BE COOL NOW
$(".dragger").css("height", newHeight + "px");
$(".dragger").css("width", newWidth + "px");
console.log($(".dragger").height());
currentX = event.pageX;
currentY = event.pageY;
}
}
function draggerUp() {
$("body").unbind('mousemove');
}
// tell the embed parent frame the height of the content
if (window.parent && window.parent.parent){
window.parent.parent.postMessage(["resultsFrame", {
height: document.body.getBoundingClientRect().height,
slug: "xUAZ5"
}], "*")
}
// always overwrite window.name, in case users try to set it manually
window.name = "result"
}
I am trying to do it with that methodology (from another project) but I don't really know if it could work with the previous code:
var u;
for(var i=1; i<13; i++) {
var specificClass= document.getElementsByClassName("class"+i);
for (u = 0; u < specificClass.length; u++) {
specificClass[u].addEventListener("click", thefunction);
}
}
function thefunction(evenement) {
// alert(evenement.target.classList)
var clickedElement = document.getElementsByClassName(evenement.target.classList);
for (u = 0; u < clickedElement.length; u++) {
clickedElement[u].style etc.
}
}
In that case I would these two groups of class: handle1, handle2, handle3,... and dragger1, dragger2, dragger3...
Here is my simplified html body:
<div class="draggableDiv dragger div1">
<div class="handle"></div>
</div>
<div class="draggableDiv dragger div2">
<div class="handle"></div>
</div>
Any other methodology is very welcomed of course, this is only what I've been trying :)
Let me know if you would need more details
Thanks!

Does not resize image

here is my URL
https://firebasestorage.googleapis.com/v0/b/apartments-ea9e5.appspot.com/o/bulletinboard%2Fsample-1494577677180.jpg?alt=media&token=7a0c1ff0-1bc7-4ea9-9176-072aacc4349c
This image height and width is 225 & 400
i need height and width 100
here is javascript function
var myUrl = 'https://firebasestorage.googleapis.com/v0/b/apartments-ea9e5.appspot.com/o/bulletinboard%2Fsample-1494577677180.jpg?alt=media&token=7a0c1ff0-1bc7-4ea9-9176-072aacc4349c';
var img = new Image();
img.src = myUrl;
var width;
var height;
img.addEventListener("load", function(){
console.log( this.naturalWidth +' '+ this.naturalHeight )
var imagewidth=this.naturalWidth;
var imageheight=this.naturalHeight;
var maxht =100;
var maxwt = 100;
if (imageheight > maxht || imagewidth > maxwt)
{
var old_ratio = imageheight / imagewidth;
var min_ratio = maxht / maxwt;
// If it can scale perfectly.
if (old_ratio === min_ratio) {
// this.resize_image(img, maxht, maxwt);
console.log(old_ratio);
console.log(min_ratio);
img.height = maxht;
img.width = maxwt;
console.log("does not change height and width");
console.log(img.src);
}
else {
var newdim = [imageheight, imagewidth];
newdim[0] = maxht; // Sort out the height first
// ratio = ht / wt => wt = ht / ratio.
var old_ratio = imageheight / imagewidth;
newdim[1] = newdim[0] / old_ratio;
// Do we still have to sort out the width?
if (newdim[1] > maxwt) {
newdim[1] = maxwt;
newdim[0] = newdim[1] * old_ratio;
}
//this.resize_image(img, newdim[0], newdim[1]);
img.height = newdim[0];
img.width = newdim[1];
console.log("change heigth and width");
console.log(img.src);
}
}
// width=this.naturalWidth;
// height=this.naturalHeight;
});
But does not change the height and width.
Kindly advice me,
Thanks
You can do this using only css properties.Below is a code sample.
Hope it will be useful
img {
max-width: 100px;
max-height: 100px;
}
<div>
<img src="https://firebasestorage.googleapis.com/v0/b/apartments-ea9e5.appspot.com/o/bulletinboard%2Fsample-1494577677180.jpg?alt=media&token=7a0c1ff0-1bc7-4ea9-9176-072aacc4349c">
<div>
You can just use CSS to resize your image, something like this:
img {
width: 100px;
height: 100px;
}
Always CSS first, if you couldn't solve it this way, then find a JavaScript way to solve it..
in JavaScript do it this way(as example), you can refine the code as suite you:
function resizeIMG(w, h){
var img = document.getElementsByTagName('img'), i=0;
while(img.length > i) {
img[i].style.width = w + 'px';
img[i].style.height = h + 'px';
i++;
}
}
and call it like this:
resizeIMG(100, 100);
function resizeIMG(w, h) {
var img = document.getElementsByTagName('img'),
i = 0;
while (img.length > i) {
img[i].style.width = w + 'px';
img[i].style.height = h + 'px';
i++;
}
}
resizeIMG(100, 100);
<div>
<img src="https://firebasestorage.googleapis.com/v0/b/apartments-ea9e5.appspot.com/o/bulletinboard%2Fsample-1494577677180.jpg?alt=media&token=7a0c1ff0-1bc7-4ea9-9176-072aacc4349c">
<div>
You can do this by writing this simple structure and css without stretching the image
.box {
width: 100px;
height: 100px;
overflow: hidden;
display: inline-block;
}
img {
max-width: 100%;
height: auto;
}
<div class="box">
<img src="https://firebasestorage.googleapis.com/v0/b/apartments-ea9e5.appspot.com/o/bulletinboard%2Fsample-1494577677180.jpg?alt=media&token=7a0c1ff0-1bc7-4ea9-9176-072aacc4349c" />
</div>
<div class="box">
<img src="https://firebasestorage.googleapis.com/v0/b/apartments-ea9e5.appspot.com/o/bulletinboard%2Fsample-1494577677180.jpg?alt=media&token=7a0c1ff0-1bc7-4ea9-9176-072aacc4349c">
</div>
<div class="box">
<img src="https://firebasestorage.googleapis.com/v0/b/apartments-ea9e5.appspot.com/o/bulletinboard%2Fsample-1494577677180.jpg?alt=media&token=7a0c1ff0-1bc7-4ea9-9176-072aacc4349c">
</div>
<div class="box">
<img src="https://firebasestorage.googleapis.com/v0/b/apartments-ea9e5.appspot.com/o/bulletinboard%2Fsample-1494577677180.jpg?alt=media&token=7a0c1ff0-1bc7-4ea9-9176-072aacc4349c">
</div>

Javascript function not giving expected results for image

This code when run should resize the height and width that a image to fit the container.
This is the output from the code(from alerts):
2488: Images natural height
3264: Images natural width
450: The containers height
1063: The containers width
612: New height
844: New width
4: The number of times it was divided to get to output
**It should divide it 6 times to provide the outcome of:
New width: 544
New height: 414
**
I am almost certain that the problem is in the Java Script:
function resize(iid, eid) {
//Get the ID of the elements (ele being the container that the image is in and img being the image its self)
var img = document.getElementById('img');
var ele = document.getElementById('contaner');
//makes the var needed
var currentwidth = ele.clientWidth;
var currentheight = ele.clientHeight;
var naturalheight = img.naturalHeight;
var naturalwidth = img.naturalWidth;
var newheight = naturalheight;
var newwidth = naturalwidth;
var x = 0;
//runs a loop that should size the image
while (newheight > currentheight && newwidth > currentwidth){
x = x + 1;
newheight = naturalheight / x;
newwidth = naturalwidth / x;
}
newheight = Math.ceil(newheight);
newwidth = Math.ceil(newwidth);
//alerts out the answers
alert(naturalheight);
alert(naturalwidth);
alert(currentheight);
alert(currentwidth);
alert(newheight);
alert(newwidth);
alert(x);
}
#contaner {
height: 450px;
width: 90%;
margin: 5% auto;
position: relative;
}
#img {
height: 450px;
width: 90%;
}
<div id="contaner">
<img src = "..\..\Resorces\Images\SlideShow\img1.jpg" style="width:652px;height:489px;" id="img"/>
<div id="left_holder"><img onClick="slide(-1)" src="..\..\Resorces\Images\arrow_left.png" class="left"/></div>
<div id="right_holder"><img onClick="slide(+1)" src="..\..\Resorces\Images\arrow_right.png" class="right"/></div>
</div>
The problem is this line:
while (newheight > currentheight && newwidth > currentwidth)
It's stopping as soon as either width or height fits within the container, where as it seems like you want both to fit within the bounds of the container. Change to || and you'll get six iterations:
while (newheight > currentheight || newwidth > currentwidth)

Have child divs fill parent div with set proportions

I would like to create a function with jQuery/javascript that would fill a parent div with children divs of random sizes that add up the size of the parent.
For example, 10 child divs to fill a container div with proportions 1200px x 600px
<div class="container">
<!-- 10 child divs with random height and width. -->
</div>
You can use a function which splits a rectangle into two subrectangles, and recursivelly split these.
When splitting a rectangle into two parts, if it must contain an even number N of subrectangles, each part will have N/2 subrectangles.
When splitting a rectangle into two, if it must contain an odd number of leaf subrectangles, the bigger part will have one more child than the other.
function fillWithChilds(el, N) {
function rand(n) {
/* weight=100 means no random
weight=0 means totally random */
var weight = 50;
return Math.floor(weight*n/2+n*(100-weight)*Math.random())/100;
}
function main(N, x, y, hei, wid) {
if(N < 1) return;
if(N === 1) {
var child = document.createElement('div');
child.className = 'child';
child.style.left = x + 'px';
child.style.top = y + 'px';
child.style.width = wid + 'px';
child.style.height = hei + 'px';
el.appendChild(child);
return;
}
var halfN = Math.floor(N/2);
if(wid > hei) {
var newWid = rand(wid);
if(2*newWid > wid) halfN = N-halfN;
main(halfN, x, y, hei, newWid);
main(N-halfN, x+newWid, y, hei, wid-newWid);
} else {
var newHei = rand(hei);
if(2*newHei > hei) halfN = N-halfN;
main(halfN, x, y, newHei, wid);
main(N-halfN, x, y+newHei, hei-newHei, wid);
}
}
main(N, 0, 0, el.clientHeight, el.clientWidth);
}
fillWithChilds(document.getElementById('wrapper'), 11);
#wrapper {
background: #ccf;
position: relative;
height: 300px;
width: 400px
}
.child {
background: #cfc;
outline: 2px solid red;
position: absolute;
}
<div id="wrapper"></div>
The distributing will be a pain. I think there's a jQuery library out there that handles some of it... I'll poke around. This is a pretty fun problem, though.
Here's what I've go so far. It's a bit sparse.
http://jsfiddle.net/twPQ7/2/
The part that attempts to determine how many more components it should build is the rough part. I'm trying to keep this down to as few loops as possible:
var containerSize = getContainerSize();
var elementWidth = 0;
var elementHeight = 0;
// width
while (elementWidth < containerSize.x)
{
var size = generateElement();
elementWidth += size.x;
elementHeight += size.y;
}
// height, if not already full
while (elementHeight < containerSize.y)
{
var size = generateElement();
elementWidth += size.x;
elementHeight += size.y;
}
Cleaned it up a bit. Check the fiddle again: http://jsfiddle.net/twPQ7/2/
// determine the size of the container
var containerSize = getContainerSize();
var elementWidth = 0;
var elementHeight = 0;
// iteratively generate elements until we've hit the width of the container
while (elementWidth < containerSize.x)
{
var size = generateElement();
elementWidth += size.x;
// keep track of the tallest element.
if (size.y > elementHeight) elementHeight = size.y;
}
// iteratively generate elements until we've hit the height of the container
while (elementHeight < containerSize.y)
{
var size = generateElement();
elementHeight += size.y;
}

jQuery image manipulation

I want to draw gridlines of varying frequency on top of a static image in jquery, any suggestions as to the best/easiest approach - thanks!
// Specify the number of boxes
var verticalBoxes = 10;
var horizontalBoxes = 10;
var countBoxes = verticalBoxes*horizontalBoxes;
var imageHeight = img.height();
var imageWidth = img.width();
var boxHeight = imageHeight / verticalBoxes;
var boxWidth = imageWidth / horizontalBoxes;
// #grid needs to be relatively positioned
var grid = $('#grid').detach();
for(i = 0; i < countBoxes ; i++){
grid.append('<div class=\'boxes\'></div>');
}
// This is the absolutely positioned container overlaying the image
$('#grid-container').append(grid);
$('head').append('<style>.boxes {outline:1px solid black; height:'+boxHeight+'px; width:'+boxWidth+'px; float:left; }</style>');
I believe this version is more performant, relies on the CSS box model rather than placing each box individually. However it specifies the number of boxes rather than box size...
Here's a very quick mockup that should help give you an idea of my take
var top = image.top;
var left = image.left;
var width = image.width;
var height = image.height;
var boxHeight = 10; //change this how tall you want each grid box to be
var boxWidth = 10; //same for width
gridtop = top;
gridleft = left;
while (gridtop < top + height); {
gridtop += boxHeight;
$('body').append('<div></div>').css('position', 'absolute').css('width', width).css('top', gridtop).css('left', left);
}
while (gridleft < left + width); {
gridleft += boxWidth;
$('body').append('<div></div>').css('position', 'absolute').css('height', height).css('left', gridleft).css('top', top);
}

Categories

Resources