Biribu
Biribu

Reputation: 3823

Change image in html keeping size 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.

Upvotes: 0

Views: 74

Answers (1)

Tewr
Tewr

Reputation: 3853

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;
        }
    }

Upvotes: 1

Related Questions