Images are not displayed in front of the popup

I was just starting to learn Javascript by doing a simple card game and I had a problem. I want to show four cards as an image before the user can select a trump card in a pop-up window. But every time I run the code, map images are displayed during the popup, and not earlier. Please check the appropriate 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 a few things already (jQuery load handlers; window.setTimeout), but nothing worked and I am not getting the problem. So thank you very much for any hint!

BR Kajajer

+4
source share
1 answer

In the Dealcards () function, you may have to wait for the images to load first before handling the cards. You can use addhandler 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

0
source

Source: https://habr.com/ru/post/1496306/


All Articles