Change image in html keeping size javascript - javascript

I am experimenting an issue while changing an image in a img tag of html.
I did an example in fiddle which works as my webpage with images I found on internet so they are not equal:
http://jsfiddle.net/kZp7V/
This is the script code:
var counterImage = 0;
var ccI = new Array('http://tiendas.fnac.es/la-canada/files/2010/12/Peque%C3%B1a-orquesta-mediterr%C3%A1neo-300x286.jpg',
'http://muack.es/wp-content/uploads/2013/04/smalldata1.jpg',
'https://pbs.twimg.com/profile_images/604644048/sign051.gif'
);
window.image = function(element){
if(counterImage < 3){
document.getElementById("EJ_test").setAttribute('src', ccI[counterImage]);
counterImage++;
}
else{
document.getElementById("EJ_test").setAttribute('src', ccI[0]);
counterImage = 1;
}
}
I want that all images to have the same aspect of the first one, I mean, same hight and width. Is is possible?
I was asked to do it with photoswipe but I find it a little bit difficult so I want to do this now and then, read carefully everything about photoswipe for next week.
EDIT: I changed the class="cropTest" to the div instead of the image and now all images are "resized". I use "" because they are smaller. The img tag adjust to the image but I don't want this happends. I want to have a diferent image but keeping the size. I don't mind the image looks blur or pixelated.

you can use getComputedStyle to get the current size of the image, and use that information once, for example by checking if the width style has already been set by you. Example:
window.image = function(element){
if (!document.getElementById("EJ_test").style.width) {
var currentStyle = window.getComputedStyle(document.getElementById("EJ_test"));
document.getElementById("EJ_test").style.width =
currentStyle.width;
document.getElementById("EJ_test").style.height =
currentStyle.height;
}
if(counterImage < 3){
document.getElementById("EJ_test").setAttribute('src', ccI[counterImage]);
counterImage++;
}
else{
document.getElementById("EJ_test").setAttribute('src', ccI[0]);
counterImage = 1;
}
}

Related

Containing element's width is not displayed correctly

Several images are placed into an element whose display is flex and flex-wrap set to nowrap. The images don't fit into the element's width and extend beyond the screen width.
I am trying to calculate the width of the element that includes the images. However the width of element is always equal to screen width whereas it should be much greater than screen width.
Several threads have advised to first check if all the images have been loaded. Following is the code used to check the loading of the images.
let len = allCarousalImagesList.length,
counter = 0;
[].forEach.call( allCarousalImagesList, function( img ) {
if(img.complete)
incrementCounter();
else
img.addEventListener( 'load', incrementCounter, false );
} );
function incrementCounter() {
counter++;
if ( counter === len ) {
let carousalWidth = carousalElement.offsetWidth;
let browserWidth = window.innerWidth;
console.log(browserWidth, carousalWidth);
}
}
Inspite of checking for the loading of images, the width of the element containing unwrapped images is not being displayed correctly and is equal to screen width. I am using offsetWidth to get the width. Please help with this issue.
The code has been uploaded on the codesandbox here
So I created a solution to your problem:
And make sure to add position:absolute; to your carousal class
window.addEventListener("load", function () {
let carousalElement = document.getElementsByClassName("carousal")[0];
var width_of_img_container = window.getComputedStyle(carousalElement).width;
console.log(width_of_img_container);
},false);
Hope I could help.

jQuery gallery code only works after refresh

I'm having trouble implementing a gallery/portfolio, just like the ones pictured in the portfolio templates of Wix. In my HTML I have set up three div columns, in which I add images, and my thought process was to create a script which adds each image (from a list of images) to the column which currently has the smallest height.
I've already used CSS to ensure that the images are full width in the columns and have margins between each other.
The problem I've been having is that the script seems to work but only after I refresh the page--otherwise the heights returned are nonsense values like 0px and 20px, where they should be 356.2px, 306.4px, etc, or arbitrary image height values. Since 0px is being returned, the images go into the same column.
Some visuals to better describe what I mean:
What I get after the first refresh
vs What I get before the first refresh
I've looked at some questions with similar problems, and many explain that the image might not have been loaded yet. I've tried $(window).on('load', function... , $(img).onload, $('#gallery-holder-1').ready, ... and a bunch of other random stuff but nothing seems to work.
My code looks like the following:
/* List of images */
const images = ["img1.png", "img2.png", "img3.png", "img4.png", "img5.png"];
$(document).ready(function() {
var holder = 0; // to determine which holder to add to
var height1 = 0; // heights of each gallery-holder
var height2 = 0;
var height3 = 0;
// add all the images to the holders
for (const image of images) {
// get height of each holder
height1 = $('#gallery-holder-1').css("height");
height2 = $('#gallery-holder-2').css("height");
height3 = $('#gallery-holder-3').css("height");
// find smallest height
if(height3 < height2) {
if (height3 < height1) { holder = 3; }
else { holder = 1; }
}
else {
if (height2 < height1) { holder = 2; }
else { holder = 1; }
}
// create image and append
var img = document.createElement("img");
img.src = image;
$(`#gallery-holder-${holder}`).append(img);
}
});
Does anyone know what might be the problem or, alternatively, a better way to implement a portfolio like the kind on Wix?

How can I animate a recently created DOM element in the same function?

I'm working to create an image gallery where the images will be composed by progressively fading in layers one on top of the other to form the final image.
I have many such layers so instead of loading them into many different <img> elements all at once (which would slow load time) I want to start off with a single <img id="base"> and then progressively add image elements with the jQuery .after() method, assign them the relevant sources and fade them in with a delay.
The problem is that I can't attach animations to the newly created elements because (I'm assuming) they don't exist yet within the same function. Here is my code:
HTML
<div id="gallery">
<img id="base" src="image-1.jpg">
</div>
CSS
#base {
opacity: 0;
}
.layers {
position: absolute;
top: 0;
left: 0;
opacity: 0;
}
JavaScript
$(document).ready(function () {
$("#base").animate({opacity: 1}, 300); //fade in base
for (var i = 1; i <= numberOfLayers; i++, gap += 300) {
// create a new element
$("#base").after("<img class='layers' src='" + imgName + ".png'>");
// fade that new element in
$("#gallery").children().eq(i).delay(gap).animate({opacity: '1'}, 300);
}
}
Please note that I've altered my actual code to illustrate this better. I'm fairly new at JavaScript but I'm a quick learner so I'd appreciate if you could tell me what I'm doing wrong and what solution I should pursue.
EDIT: I've included my code inside your JSFiddle (all you need to do is add the library-X.jpg images) : http://jsfiddle.net/pgoevx03/
I've tried to replicate the intent of the code in a cleaner/more flexible way. Please let me know if I can do anything else to help.
I'm not saying this is the best way to do it, but it should be easy enough to understand and use.
The code is untested, but should work just fine. The comments should help you out if there's any compilation error.
Note that I removed the first image in the gallery (with ID "base") from the HTML file. It will be appended the same way as the rest.
// Array storing all the images to append to the gallery
var galleryImages = [
"image-1.jpg",
"image-2.jpg",
"image-3.jpg",
"image-4.jpg",
"image-5.jpg",
"image-6.jpg",
"image-7.jpg",
"image-8.jpg",
"image-9.jpg",
"image-10.jpg"
];
// Index of the image about to be appended
var imgIndex = -1;
var baseID = "base";
$(document).ready(function() {
// Start appending images
appendAllImages();
});
// Append the images, one at a time, at the end of the gallery
function appendAllImages() {
//Move to the next image
imgIndex++;
//We've reached the last image: stop appending
if (imgIndex >= galleryImages.length) return;
//Create image object
var img = $("<img>", {
src: galleryImages[imgIndex],
});
if (imgIndex === 0) { // It's the base!
//Give the base ID to the first image
img.attr("id", baseID);
//Append the image object
$("#gallery").append(img);
} else { // It's a layer!
//Give the base ID to the first image
img.attr("class", "layers");
//Append the image object
$("#" + baseID).after(img);
}
//Fade in the image appended; append the next image once it's done fading in
img.animate({
opacity: 1,
}, 300, appendAllImages);
}

Creating Image slider using only jQuery

I'm trying to create an image slider using Jquery.
What I have is a main div with 3 sub divs with images.
Take a look at this fiddle. FIDDLE
Ok now i got the design just the way I want it. What is missing is the functionality.
When i hover over the div or the images, I want it to act like a clockwise slider.
This may look a bit confusing. Take a look at this demo. This is what i want.
DEMO
This is what i want.The right div gets filled with the middle image src , the middle div gets the left div src. The left div get an new src from an array of images i have defined. Currently i can only change one image div at a time.
However I don't want to use any more plugins. Only Jquery plugin. A CSS only solution would be the best but I do not think it will be possible.
JQUERY
$('.maindiv img').mouseover(function () {
var image = this;
loop = setInterval(function () {
if (i < images.length - 1) {
i++;
$(image).attr('src', images[i]);
} else {
i = 0;
$(image).attr('src', images[i]);
}
}, 1500);
EDIT: I managed to get one part of this working. CHECK THIS.Just need to add fade effect Now the problem is after the images in the array end the first images dont loop back... Had not thought of this before.Does Anybody know how i can get over this issue?
Mabye something like this:
jQuery(document).ready(function () {
var images = [];
var loop;
var i = 0;
images[0] = "https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcQ1GfA01TRDgrh-c5xWzrwSuiapiZ6b-yzDoS5JpmeVoB0ZCA87";
images[1] = "https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcQQSyUWiS4UUhdP1Xz81I_sFG6QNAyxN7KLGLI0-RjroNcZ5-HLiw";
images[2] = "https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcT_E_OgC6RiyFxKtw03NeWyelfRgJ3Ax3SnZZrufNkUe0nX3pjQ";
$('img', '.maindiv').mouseover(function () {
//Get divs inside main div and reverse them, so right is first
var divs = $($('div','.maindiv').get().reverse());
//Set up loop
loop = setInterval(function(){
divs.each(function(key, div){
if (divs[key+1])
{
//All divs gets image src from previous div > img
$('img', div).attr('src', $('img', $(divs[key+1])).attr('src'));
}
else
{
//This is left div
if (images && images[i])
{
//If picture url not in array then add it
if ($.inArray($('img', div).attr('src'), images) == -1)
{
images.push($('img', div).attr('src'));
}
$('img', div).attr('src', images[i]);
i++;
if (i>= images.length) i = 0;
}
}
});
}, 1500);
}).mouseout(function(){
clearInterval(loop);
});
});
Fiddle

How to change the height of div with the content of other div

I have two div in my website page one beside the other(one left and one right),I want to change the height of the left one with the content of the right one using javascript
I tried to have the dynamic height of the right div :
function getHeight() {
var doc = document.getElementById('div.right');
if (document.all) // ok I.E
{
H = doc.currentStyle.height;
}
else // ok FF
{
H = document.defaultView.getComputedStyle(doc, null).height;
}
}​
But I stopped here because I don't know how to pass the javascript variable to my page of style CSS,I mean I dont know how to apply this value in the other div(left div) in the same page automatically.
Any Idea?
Just use
document.getElementById('div.left').style.height = H;
Edit
AFAIK you cant modify an external stylesheet from javascript
Is the height of the div determined at the time the document is served, loaded or or any arbitrary time after the document has loaded?
The code I suggested above was to be used like this(I'm assuming your IE code is correct)
function getHeight() {
var doc = document.getElementById('div.right');
if (document.all) // ok I.E
{
H = doc.currentStyle.height;
}
else // ok FF
{
H = document.defaultView.getComputedStyle(doc, null).height;
}
document.getElementById('div.left').style.height = H;//✔
}
Just to help people I found a great code to change the height of two div autoamtically using a little of Jquery :
<script type='text/javascript'>
$(window).load(function(){
var lh = $('#div.right').height();
var rh = $('#div.left').height();
if (lh >= rh){
//alert('left : ' + lh);
$('#div.left').height(lh);
} else {
//alert('right : ' + rh);
$('#div.right').height(rh);
};
});
</script>
It's works for all navigators.

Categories

Resources