4

I just started learning Javascript by doing a simple card game and I'm stucked at a problem. I want to show four cards as an image before a user can select a trump by a popup box. But, everytime I run the code the cards images get displayed AFTER the popup box and not before. Please have a look at the relevant code:

function preloadImages() {
    var imgs = [];
    for (var i = 0; i < max_length_deck; i++) {
        imgs[i] = new Image();
        imgs[i].src = 'img/' + deck[i] + '.png';
    }
}

function generateDeck() {
    for (i = 0; i < colour.length; i++) {
        for (x = 0; x < number.length; x++) {
            deck.push(colour[i] + '' + number[x]);
        }
    }
}

function shuffleCards() {
    cards.length = 0;
    for (i = 0; i < max_length_deck; i++) {
        var random = Math.floor(Math.random() * deck.length);
        cards.push(deck[random]);
        deck.splice(random, 1);
    }
}

function dealCards() {
    generateDeck();
    preloadImages();
    shuffleCards();
    for (var i = 0; i < 4; i++) {
        window.document.images[i].src = 'img/' + cards[i] + '.png'; //I defined four image tags at html file
    }
    selectTrump();
}

function selectTrump() {
    var result = false;
    while (result != true) {
        trump = prompt("Please enter trump:", "");
        result = checkTrump(trump);
    }
}

I searched and tried several things already (jQuery load handlers; window.setTimeout), but nothing worked and I don't get problem. So, thank you very much for any hint!

BR Kjaer

putvande
  • 15,068
  • 3
  • 34
  • 50
Kjaer
  • 41
  • 2

1 Answers1

0

In the function Dealcards() you probably have to wait for the images to be loaded first, before dealing the cards. You can use add an eventhandler for this:

<html>
<head>
<script>
function loadImage()
{
alert("Image is loaded");
}
</script>
</head>

<body>
<img src="w3javascript.gif" onload="loadImage()" id="myImage">
</body>
</html>

//Or use:
// example

function addEvent(element, evnt, funct){
  if (element.attachEvent)
   return element.attachEvent('on'+evnt, funct);
  else
   return element.addEventListener(evnt, funct, false);
}

addEvent(
    document.getElementById('myImage'),
    'load',
    function () { alert('image loaded!'); }
);

addEventListener vs onclick

Community
  • 1
  • 1
  • Thank you very much for your input, it works! Just because I'm curious: Is there any reason why the function preloadImages() doesn't solve this issue? I read at several pages that this would be a solution for caching all the images? Or is there a difference between caching the images in the browser and actually loading the images at the web page? – Kjaer Aug 11 '13 at 16:30