kfir
kfir

Reputation: 745

javascript to load image source keeps the page blinking

I am new to Javascript, I try to make a simple program which changes image source on button click. the image is being loaded but immediately deleted. it works only if I call the image source loading function from the onload event of the body. but than the result is wromg: it loads all the page with the wrong image source and than call the onload function -> resulted in page that blinks twice until fully loaded. My final goal is to allow one initial images loading and than change images on button click from javascript (not calling the server). Thanks in advance

function load() {
        document.getElementById("mainImg").src = 'Koala.jpg';
    }

<button type="submit" name="btn0101" value="btn" onclick="load()" >
                            <img src="iconUnavail.png" id="mainImg" />
                            </button>

Upvotes: 0

Views: 333

Answers (3)

dijipiji
dijipiji

Reputation: 3109

The "submit" call in your <button> will force the page reload - try removing that.

Upvotes: 0

Canvas
Canvas

Reputation: 5897

What you can do is bind your event to the onclick event in the button itself like so

jsFiddle https://jsfiddle.net/a3pv8j71/1/

Html

<img id="mainImg" src="http://www.squirrelsandmore.com/media/wysiwyg/feline_cat_img.jpg">
<button type="submit" onclick="changeImage()">Change img
    </button>

Javascript

function changeImage() {
    document.getElementById("mainImg").src = 'http://photos.jibble.org/Experimental/Flying%20Cat/IMG_4821%20Flying%20cat%20.JPG';
}

Upvotes: 0

potatopeelings
potatopeelings

Reputation: 41075

I assume you are trying to preload images. This is how you do that.

var myImage = new Image(100, 100)
myImage.src = "mainImg"

Then when you are ready (button click), just swap out the src and the image will appear immediately.


That said, a better way would be to use sprites.

Upvotes: 1

Related Questions