Images don't get displayed before a pop-up box - javascript

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

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

Related

Weird action by javascript for onclick event

Hi! I'm trying to create a carousel/image slider which is automatic and reactable to onclick event but for somereason the onclick event messesup the automatic flow of the slider even though the code makes perfect sens!
Could someone tell me whats wrong in this code and a solution to fix it please! thank you!
var i = 0;
var images = [];
var time = 3000;
images[0] = "https://cache.lovethispic.com/uploaded_images/162514-Just-Breathe.jpg";
images[1] = "https://cache.lovethispic.com/uploaded_images/162513-Be-Someone-s-Sunshine.jpg";
images[2] = "https://cache.lovethispic.com/uploaded_images/162508-Don-t-Cry-.jpg";
var nextbutton=document.querySelector("#rightbutton");
nextbutton.addEventListener("click",rightbuttonclick);
var prevbutton=document.querySelector("#leftbutton");
prevbutton.addEventListener("click",leftbuttonclick);
function rightbuttonclick(){
i++;
changeImg();
}
function leftbuttonclick(){
i--;
changeImg();
}
function changeImg(){
document.getElementById('startersliders').src = images[i];
if(i < images.length - 1){
i++;
}
else {
i = 0;
}
// Run function every x seconds
setTimeout("changeImg()", time);
}
function changenext(){
i++;
changeImg();
}
// Run function when page loads
window.onload=changeImg;
<button id="leftbutton">left</button>
<img id="startersliders" width="400" height="200"/>
<button id="rightbutton">right</button>
here is a code that can help you,
var prevbutton=document.querySelector("#leftbutton");
//nextbutton.addEventListener("click",leftbuttonclick);
prevbutton.addEventListener("click",leftbuttonclick);
Keep a variable eg: setTime that decides whether to call setTimeout again or not.
function rightbuttonclick() {
i++;
changeImg(false);
}
function leftbuttonclick() {
i--;
changeImg(false);
}
function changeImg(setTime) {
document.getElementById('startersliders').src = images[i];
if (i < images.length - 1) {
i++;
} else {
i = 0;
}
// Run function every x seconds
if (setTime !== false)
setTimeout("changeImg()", time);
}
var i = 0;
var images = [];
var time = 3000;
images[0] = "https://cache.lovethispic.com/uploaded_images/162514-Just-Breathe.jpg";
images[1] = "https://cache.lovethispic.com/uploaded_images/162513-Be-Someone-s-Sunshine.jpg";
images[2] = "https://cache.lovethispic.com/uploaded_images/162508-Don-t-Cry-.jpg";
var nextbutton = document.querySelector("#rightbutton");
nextbutton.addEventListener("click", rightbuttonclick);
var prevbutton = document.querySelector("#leftbutton");
prevbutton.addEventListener("click", leftbuttonclick);
function rightbuttonclick() {
i++;
changeImg(false);
}
function leftbuttonclick() {
i--;
changeImg(false);
}
function changeImg(setTime) {
document.getElementById('startersliders').src = images[i];
if (i < images.length - 1) {
i++;
} else {
i = 0;
}
// Run function every x seconds
if (setTime !== false)
setTimeout("changeImg()", time);
}
// Run function when page loads
window.onload = changeImg();
<button id="leftbutton">left</button>
<img id="startersliders" width="400" height="200" />
<button id="rightbutton">right</button>
Or you can use setInterval instead of setTimeout as shown below:
var i = 0;
var images = [];
var time = 3000;
images[0] = "https://cache.lovethispic.com/uploaded_images/162514-Just-Breathe.jpg";
images[1] = "https://cache.lovethispic.com/uploaded_images/162513-Be-Someone-s-Sunshine.jpg";
images[2] = "https://cache.lovethispic.com/uploaded_images/162508-Don-t-Cry-.jpg";
var nextbutton = document.querySelector("#rightbutton");
nextbutton.addEventListener("click", rightbuttonclick);
var prevbutton = document.querySelector("#leftbutton");
prevbutton.addEventListener("click", leftbuttonclick);
function rightbuttonclick() {
i++;
changeImg(false);
}
function leftbuttonclick() {
i--;
changeImg(false);
}
function changeImg(setTime) {
document.getElementById('startersliders').src = images[i];
if (i < images.length - 1) {
i++;
} else {
i = 0;
}
}
window.onload = changeImg();
setInterval(function() {
changeImg()
}, time);
<button id="leftbutton">left</button>
<img id="startersliders" width="400" height="200" />
<button id="rightbutton">right</button>
add a clearTimeout function to chageImg() and it will work,
as to why it was behaving strangely is because setTimeout was been called multiple times. you should always be careful when using setInverval or setTimeout. here is a code snippet
function changeImg(){
clearTimeout(interval);
document.getElementById('startersliders').src = images[i];
if(i < images.length - 1){
i++;
}
else {
i = 0;
}
// Run function every x seconds
interval = setTimeout("changeImg()", time);
}

JavaScript Image Gallery 2

I don't know if this question has been asked before or not. But...
I have the following JavaScript code in my HTML file:
<img id="imageDisplay">
<script type="text/javascript">
var displayImage = document.querySelector( '#imageDisplay' );
var imageArray = [ 'http://www.joongcho.com/Images/30th-Bday-Party-01.jpg',
'http://www.joongcho.com/Images/30th-Bday-Party-02.jpg',
'http://www.joongcho.com/Images/30th-Bday-Party-03.jpg',
'http://www.joongcho.com/Images/30th-Bday-Party-04.jpg',
'http://www.joongcho.com/Images/30th-Bday-Party-05.jpg',
'http://www.joongcho.com/Images/30th-Bday-Party-06.jpg' ];
var imageCount = 0;
var imageLength = imageArray.length;
displayImage.setAttribute( 'src', imageArray[ imageCount ] );
function nextImage(imageCount) {
}
function previousImage(imageCount) {
}
</script>
I'm trying to put a next Image and a previous Image function for this HTML.
For the next image, if there are more than 1 images and the image is not the last image, then there should be a link that allows a user to click through the array forwards. Also, if the image is the last image in the array, then the link is hidden.
For the previous image, if the image is not the first image of the array, then there should be a link that allows a user click through the array backwards. if the image is the first image, then the previous link should be hidden.
Any help is appreciated.
You have to attach event listeners to buttons or links (I used buttons):
var displayImage = document.getElementById('imageDisplay');
var buttonPrev = document.getElementById('button-prev');
var buttonNext = document.getElementById('button-next');
var imageArray = [ '../Images/30th-Bday-Party-01.jpg',
'../Images/30th-Bday-Party-02.jpg',
'../Images/30th-Bday-Party-03.jpg',
'../Images/30th-Bday-Party-04.jpg',
'../Images/30th-Bday-Party-05.jpg',
'../Images/30th-Bday-Party-06.jpg' ];
var imageCount = 0;
var imageLength = imageArray.length;
function nextImage () {
imageCount++;
if (imageCount >= imageLength - 1) {
buttonNext.style.display = 'none';
imageCount = imageLength - 1;
}
if (imageCount < imageLength) {
displayImage.setAttribute('src', imageArray[imageCount]);
}
if (imageCount > 0) {
buttonPrev.style.display = 'inline';
}
}
function previousImage () {
imageCount--;
if (imageCount <= 0) {
buttonPrev.style.display = 'none';
imageCount = 0;
}
if (imageCount >= 0) {
displayImage.setAttribute('src', imageArray[imageCount]);
}
if (imageCount < imageLength) {
buttonNext.style.display = 'inline';
}
}
displayImage.setAttribute('src', imageArray[imageCount]);
displayImage.textContent = imageCount;
buttonPrev.style.display = 'none';
buttonNext.addEventListener('click', nextImage);
buttonPrev.addEventListener('click', previousImage);
<img id="imageDisplay" />
<button id="button-prev">Back</button>
<button id="button-next">Forward</button>
Of course, you can't look at the images yet.

How to interchange between 2 logos?

I have the following code:
var logo1 = "//cdn.shopify.com/s/files/1/0816/3411/t/3/assets/logo_2x.png";
var logo2 = "//cdn.shopify.com/s/files/1/0816/3411/t/3/assets/logo_hover_2x.png";
var images = new Array (logo1, logo2);
var index = 1;
function rotateImage()
{
$('.logoimage').fadeOut('fast', function()
{
$(this).attr('src', images[index]);
$(this).fadeIn('fast', function()
{
if (index == images.length-1)
{
index = 0;
}
else
{
index++;
}
});
});
}
$(document).ready(function()
{
setInterval (rotateImage, 5000);
});
var images = new Array (logo2);
var index = 1;
function rotateImage()
{
$('.logoimage').fadeOut('fast', function()
{
$(this).attr('src', images[index]);
$(this).fadeIn('fast', function()
{
if (index == images.length-1)
{
index = 0;
}
else
{
index++;
}
});
});
}
$(document).ready(function()
{
setInterval (rotateImage, 5000);
});
Its working well apart from the following bugs:
Image loads even though image already is showing on page.
I have an image onmousehover effect on that image and its causing bad effect.
Is it possible to interchange between the image src and the img onmousehover src?
Thanks
Alex
you can change the src of the img tag using JavaScript as below,
function hover(element) {
element.setAttribute('src', '//cdn.shopify.com/s/files/1/0816/3411/t/3/assets/logo_2x.png');
}
function unhover(element) {
element.setAttribute('src', '//cdn.shopify.com/s/files/1/0816/3411/t/3/assets/logo_hover_2x.png');
}
and the html be
<img id="my-img" src="http://dummyimage.com/100x100/000/fff" onmouseover="hover(this);" onmouseout="unhover(this);" />
After Edit :
If you want to change it on some timeout, You need to put your below code inside window.onload = function() {}
var images = new Array();
images[0] = "logo_1.png";
images[1] = "logo_2.png";
var images = new Array();
for (var i = 0; i < 2; i++) {
images.push("logo_" + i + ".png");
}
var x = 0;
function changeImage() {
document.getElementById('ad').src = images[x];
if (x < 8) {
x += 1;
} else {
x = 0;
}
if (window.addEventListener) {
window.addEventListener('load', changeImg, false);
}
function changeImg() {
var x = 0;
setInterval(function() {
changeImage()
},5000);
}
HTML:
<img id="ad" src="//cdn.shopify.com/s/files/1/0816/3411/t/3/assets/logo_2x.png" />
Use jQuery hover to run code when hovering in or out of an element. Also use setTimeout to run code after a delay.
var logo1 = "//cdn.shopify.com/s/files/1/0816/3411/t/3/assets/logo_2x.png";
var logo2 = "//cdn.shopify.com/s/files/1/0816/3411/t/3/assets/logo_hover_2x.png";
$(function() {
$('.logoimage').hover(function() {
setTimeout(function() {
$('.logoimage').attr('src', logo2);
}, 1000);
}, function() {
setTimeout(function() {
$('.logoimage').attr('src', logo1);
}, 1000);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<img class="logoimage" src="//cdn.shopify.com/s/files/1/0816/3411/t/3/assets/logo_2x.png">

Preload images image.onload script MVC

My application is a MVC, using MS SQL to get the image file names. I am using the following script to preload images; would like to know How I can display hourglass cursor while waiting to complete the preload.
function preload_images() {
var i, count = 0;
$('#selector').css('cursor', 'wait');
for (i = 1; i < sl; i++) {
images[i] = new Image();
images[i].onload = images[i].onerror = function () {
count++;
if (count == sl) {
$('#selector').css('cursor', 'default');
}
}
images[i].src = impath.toString() + im.toString() + i + ".jpg";
}
}
It works great first time, however, when I change the file name from a dropdownlist, the hourglass does not stop even all images are load. Thanks in advance.
From the code above you are loading sl-1 images, but the condition to stop the wait cursor is sl images(if (count == sl)), so change it to if (count == (sl-1))
Thanks to Musa for providing the initial solution, here is the way I got it to work, just in case someone is looking for it:
var images = [];
function preload_images() {
showLoadingImage();
$('#selector').css('cursor', 'wait');
for (i = tochar; i < sl; i++) {
images[i] = new Image();
var name = impath.toString() + imStart.toString() + i + ext;
images[i].src = 'ImageHandler.ashx?img=' + name + '&window=50&level=50 &slice=0';
if (i == sl - 1) {
images[i].onload = images[i].onerror = function () {
$('#selector').css('cursor', 'Default');
hideLoadingImage(this);
};
}
}
}
function showLoadingImage() {
$('#imagediv').append('<div id="imagediv1"><img src="../Content/images/ajax-loader2.gif" alt="Loading..." /></div>');
$('#imagediv1').show();
}
function hideLoadingImage(img) {
$('#imagediv1').hide();
img.onload = img.onerror = null;
}

How to get the number of the current image clicked on in javascript

Ok, so suppose. I have ten images in documents.images array. When I click on an image. How do I get an alert telling me what image I have clicked on.
EDIT
The reason that I want the index of the image I clicked on is because I am trying to bind it to an event and the previous way doesn't seem to work
document.images[i].addEventListener("click", function(){MakeMove(i)}, false);
This statement is in a for loop, and I intended it to bind to every image but that doesn't seem to be working.
Here is pure JavaScript way to do that:
window.onload = function() {
for (var i = 0; i < document.images.length; i++) {
var image = document.images[i];
image.setAttribute("index", i + "");
image.onclick = function() {
var index = this.getAttribute("index");
alert("This is image #" + index);
};
}
};
The trick is assigning custom attribute with the index, then read that attribute.
Live test case.
Put this at the bottom of the html file, just before the closing tag
<script type="text/javascript">
function listen(evnt, elem, func) {
if (elem.addEventListener) { // W3C DOM
elem.addEventListener(evnt,func,false);
} else if (elem.attachEvent) { // IE DOM
var r = elem.attachEvent("on"+evnt, func);
return r;
}
}
listen("click", document.getElementsByTagName("body")[0], function(event) {
var images = document.images,
clicked = event.target;
for(var i =0, il = images.length; i<il;i++) {
if(images[i] === clicked) {
return alert("You clicked on the " + (i + 1) + "th image");
}
}
});
</script>
window.onload = function() {
for (var i = 0; i < document.images.length; i++) {
var image = document.images[i];
image.onclick = function() {
var images = Array.prototype.slice.call(document.images);
alert(Array.indexOf(images,this));
}
};
};
JSFiddle: http://jsfiddle.net/kmendes/8LUzg/1/
If you want it to work on old browsers too add the function under Compatibility on https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/indexOf

Categories

Resources