Javascript: edit an images height in a for loop - javascript

I'm trying to edit an images height that is repeating in a for loop in javascript but I can't figure out where I would need to add it in.
Here are the variables if it's important:
var i;
var start = 1;
var seg = document.getElementById("selSegs").value;
var parent = document.getElementById("divInch"), //parent for appendChild
imagePath = 'InchwormSegment.gif', //variable for image
img; //adding img element
Here is my loop:
for(i = start; i<=seg; i++) {
img = new Image(); //creating new image object
img.src = imagePath; // element src = imagePath
img.style.height = "215px"; // sets the height of all in loop
// img.style.height = (img.style.height * .9) + "px"; - does nothing
parent.appendChild(img); //appendChild adds another child (img) object
}
I've tried adding in some math but I just can't figure out where it is supposed to go

Let me know if this fiddle accomplishes what you are trying to do: http://jsfiddle.net/AyNY5/. A few things to remember:
You can edit the image "height" attribute directly, no need to go through style (You don't even need to add px!)
Don't use new Image() - use document.createElement('img'). That's the W3C supported standard.
If I'm off let me know - otherwise, you were on the right track!
JS Code in Fiddle:
var parent = document.getElementById("imgholder")
for (i=0;i<3;i++) {
var img = document.createElement('img');
img.src = "http://bit.ly/1975WKA"
img.height = "200"
parent.appendChild(img)
}

At this point image does not have style.height assigned. It does have height attribute though.
Instead of
img.style.height = (img.style.height * .9) + "px";
try
img.style.height = (img.height * .9) + "px";

Related

Set height of Img via JavaScript

I am currently running into a problem with my code. I am attempting to set the height of an image through JavaScript in a check that its less than 600 pixels. I have tried a plethora of alternatives to the general "this.height = 600" but none have resulted successfully. I am really hoping someone can help me fix this problem.
<div id="cursedframe">
<img src="" id="cursedimg">
</div>
<script>
function setImage() {
var img = new Image();
var images = [
"bean.jpg",
"xxx-edit-parallax/Images/xxx-5.jpg"
];
var chosen = images[Math.floor(Math.random() * images.length)];
img.onload = function(){
if (this.height > 600) {
console.log("more than");
this.height = 600;
console.log(img.height);
} else {
console.log("less than");
this.height = "auto";
console.log(this.height);
}
};
img.src = chosen.toString();
document.getElementById("cursedimg").src = img.src;
}
</script>
It successfully passes the "if" but never actually sets the height.
EDIT: Unaware of the CSS property of max-height and max-width at the time. Was brought to my attention by Lain. Thank you
It would be much easier to use the css property max-height.
Just to show the actual flaw with the approach in javascript: you have to pass the height on to the actual image. Currently you merely set it to the img object yet never to the shown image <img src="" id="cursedimg">.
var img = new Image();
var images = ['https://logosmarken.com/wp-content/uploads/2018/05/Google-Logo.png'];
var maxHeight = 200; //REM: For my test image
img.onload = function(){
if (this.height > maxHeight) {
console.log("more than");
this.height = maxHeight;
console.log(img.height);
} else {
console.log("less than");
this.height = "auto";
console.log(this.height);
};
//REM: Here you need to assign the src along with the height
document.getElementById("cursedimg").src = this.src;
document.getElementById("cursedimg").style.height = this.height + 'px';
};
//REM: No need for toString() - it already is.
img.src = images[Math.floor(Math.random() * images.length)];
<div id="cursedframe">
<img src="" id="cursedimg">
</div>
Even easier would be to not create a new object at all and just assign it as is:
var img = document.getElementById("cursedimg");
By running the following code, you are assigning the only the src attribute to the img element
img.src = chosen.toString();
document.getElementById("cursedimg").src = img.src;
If you want to set the height and src of the image element using javascript,
you can do the following:
var image = document.getElementById("cursedimg");
if ( image.height > 600 ){
image.height = 600;
}
else{
image.style.height = "auto"; // since 'auto' is a styling value
}
image.src = chosen.toString();

Dynamically adjust font size by pure javascript

I have a code similar to this:
var a = document.createElement('div');
a.style.width = '200px';
a.style.fontSize = fontSize(a.offsetWidth, 5);
a.innerHTML = 'Example';
document.body.appendChild(a);
function fontSize(reference, factor){
return (reference*factor)/100 + 'px';
}
However when I run it, the element font size appears to be 0px. The console.log returns expected value tho.
Similar code works on an javascript object that I tried:
var Object = function(target){
var default = {
fontSize: fontSize(target.clientWidth, 5);
}
}
jsFiddle here
What did I do wrong?
The HTMLElement.offsetWidth read-only property returns the layout width of an element. Typically, an element's offsetWidth is a measurement which includes the element borders, the element horizontal padding, the element vertical scrollbar (if present, if rendered) and the element CSS width.
Your newly created div element has not been appended to the document when you try to read the offsetWidth, consequently it has a layout width of 0 so you end up with a font-size of 0px.
You need to put the div in the document before you measure how much space it takes up in the document.
Alternatively, you need to use a value other than offsetWidth (such as style.width.
Your logic is good, but you should append your element to the DOM before trying to retrieve its size:
var a = document.createElement('div');
a.style.width = '200px';
a.innerHTML = 'Example';
document.body.appendChild(a);
a.style.fontSize = fontSize(a.offsetWidth, 5);
function fontSize(reference, factor) {
return (reference * factor) / 100 + 'px';
}
Forked your Fiddle here
Just put a.style.fontSize = fontSize(a.offsetWidth, 5); after document.body.appendChild(a);.
var a = document.createElement('div');
a.style.width = '200px';
a.innerHTML = 'Example';
document.body.appendChild(a);
a.style.fontSize = fontSize(a.offsetWidth, 5); // <--- Move here
function fontSize(reference, factor){
return (reference*factor)/100 + 'px';
}
In fact, there's CSS properties you can't edit while the element is not added to the DOM. Font-size is one of them.
You need to append "a" to document first before you calculate its offsetWidth.
Refer - http://www.w3schools.com/jsref/prop_element_offsetwidth.asp
var a = document.createElement('div');
a.style.width = '200px';
document.body.appendChild(a);
a.style.fontSize = fontSize(a.offsetWidth, 5);
a.innerHTML = 'Example';
function fontSize(reference, factor){
return (reference*factor)/100 + 'px';
}

Resize image before loading - jquery

I'm using this plugin to create image zoom and gallery, yet I want to scale all images to fit with the container (using ratio algorithm).
Here is ratio function :
function scaleSize(maxW, maxH, currW, currH){
var ratio = currH / currW;
if(currW >= maxW && ratio <= 1){
currW = maxW;
currH = currW * ratio;
} else if(currH >= maxH){
currH = maxH;
currW = currH / ratio;
}
return [currW, currH];
}
And this is how the gallery load images :
var img = $('<img>').load(function(){
img.appendTo(a);
image_container.html(a);
}).attr('src', src).addClass(opts.big_image_class);
What I've tried :
var newSize = scaleSize(300, 320, $(".simpleLens-big-image").width(), $(".simpleLens-big-image").height());
var img = $('<img>').load(function(){
img.appendTo(a);
image_container.html(a);
}).attr('src', src).addClass(opts.big_image_class).width(newSize[0]).height(newSize[1]);
But scaleSize is not working properly since the current width and height is not yet defined (image not yet exist in dom).
Thanks for any pointers.
I took a look into plugin code and think you call your scaleSize() too early. An image with class simpleLens-big-image exists first after var img is set up and addClass() is done.
Try following:
var img = $('<img>').load(function(){
img.appendTo(a);
image_container.html(a);
}).attr('src', src).addClass(opts.big_image_class);
// at this point img should contain $(".simpleLens-big-image") so we can refer to img
var newSize = scaleSize(300, 320, img[0].naturalWidth, img[0].naturalHeight());
img.width(newSize[0]).height(newSize[1]);
Try something like this and call the onload method. This will make sure that the image is loaded to the DOM before you resize
var img = $('<img>');
img.src = src ;
img.onload = function() {
// Run onload code.
} ;

Spawn a image on another image giving a coordinate

I have some image coordinates and I want to use them to put a small image on those with javascript. Can this be accomplished with javascript or I need to create the div and modify it's css attributes? By the way: the image can be placed anywhere on the page.
Here is a fully working code: Live Demo
CSS
.overlays{
position:absolute;
}
JS
function showImage() {
// myImage : ID of image on which to place new image
var image = document.getElementById('myImage');
console.log(image.width);
margin = 20;
l = image.offsetLeft;
t = image.offsetTop;
w = image.width;
h = image.height;
// Location inside the image
offX = parseInt(Math.random() * w);
offY = parseInt(Math.random() * h);
if(offX > margin) offX -= margin;
if(offY > margin) offY -= margin;
l += offX;
t += offY;
var newImage = document.createElement("img");
newImage.setAttribute('src', '1.jpg');
newImage.setAttribute('class', 'overlays');
newImage.style.left = l + "px";
newImage.style.top = t + "px";
document.body.appendChild(newImage);
}
Try this to place the new image on coordinates (X,Y) of a parent image:
var newImg = document.getElementById('newImg'), // your new (small) image
img = document.getElementById('parentImg'); // parent image
document.body.insertBefore(newImg, img); // Insert the new image before the image
document.body.insertBefore(img, newImg); // Then switch places (So the small image is after the big one in the DOM)
newImg.style.position = 'relative';
newImg.style.left = X + "px";
newImg.style.top = (Y - img.height)+"px"; // Substract the height of the source image to get the position relative to the top left.
The double insertBefore is to insert the new image after the bid one, by first inserting it before the big one, then moving the big one in front of it.
Then, it's just a matter of setting the new image's coordinates relative to the big image.
Working Example (Set to display the overlay after 2 seconds to show the difference)
css:
#yourId{
position: absolute;
}
js:
var img = document.getElementById('yourId'), // or any other selector
x = x, // your data
y = y; // your data
img.style.left = x+"px";
img.style.top = y+"px";

How to move around an image with javascript?

I'm developing a simple web quiz and using javascript, I would like to create an effect that displays a small image (1UP) that wanders around the "game deck" when users reach a specific level or score; user could gain an extra life simply clicking on it in time.
Do you know any Jquery plugin or javascript snippet to achieve an effect like this?
It's actually surprisingly easy to do this:
Create the element:
img = document.createElement('img');
Set its source:
img.src = "myimage.png";
Position it absolutely and such:
img.style.position = "absolute";
img.style.left = "50px";
img.style.top = "50px";
img.style.width = "50px"; // Make these match the image...
img.style.height = "50px"; // ...or leave them off
(Obviously, use whatever coordinates and size you want.)
You may want to make sure it appears above other things:
img.style.zIndex = 100; // Or whatever
Add it to the document:
document.body.appendChild(img);
Move it around
Use window.setInterval (or setTimeout depending on how you want to do it) to move it around by changing its style.left and style.top settings. You can use Math.random to get a random floating point number between 0 and 1, and multiply that and run it through Math.floor to get a whole number for changing your coordinates.
Example
This creates an image at 50,50 and animates it (in a very jittery random way; I didn't spend any time making it look nifty) every fifth of a second for 10 seconds, then removes it:
function createWanderingDiv() {
var img, left, top, counter, interval;
img = document.createElement('img');
img.src = "myimage.png";
left = 200;
top = 200;
img.style.position = "absolute";
img.style.left = left + "px";
img.style.top = top + "px";
img.style.width = "200px"; // Make these match the image...
img.style.height = "200px"; // ...or leave them out.
img.style.zIndex = 100; // Or whatever
document.body.appendChild(img);
counter = 50;
interval = 200; // ms
window.setTimeout(wanderAround, interval);
function wanderAround() {
--counter;
if (counter < 0)
{
// Done; remove it
document.body.removeChild(img);
}
else
{
// Animate a bit more
left += Math.floor(Math.random() * 20) - 10;
if (left < 0)
{
left = 0;
}
top += Math.floor(Math.random() * 10) - 5;
if (top < 0)
{
top = 0;
}
img.style.left = left + "px";
img.style.top = top + "px";
// Re-trigger ourselves
window.setTimeout(wanderAround, interval);
}
}
}
(I prefer re-scheduling on each iteration via setTimeout [as above] to using setInterval, but it's totally your call. If using setInterval, remember the interval handle [return value from setInterval and use window.clearTimeout to cancel it when you're done.)
The above is raw DOM/JavaScript; jQuery offers some helpers to make it a bit simpler, but as you can see, it's pretty straightforward even without.
There's also a jQuery function that can be used to move thing's around.
See this for examples:
http://api.jquery.com/animate/

Categories

Resources