0
Always get an undefined right after loading an image changer JS on my website
I watched this ytb where he wrote a code for image onclick changer and he did some math.floor equation but that var kept showing up as undefined. Is it the JS? cdn? Or my path? Whats the problem?
11 Respuestas
+ 4
This is an example that might help you
https://code.sololearn.com/WG2q115sEC8z
+ 5
Jessica Zarate ,
Can you share the code??
+ 3
You forgot the last part of the code
# Display the message
print (message)
if you have a question don't put it as a reply to another question make a new question yourself
Abduljunju
+ 1
Thank you SoloProg <3
+ 1
Jessica Zarate defining variable using let keyword within the function make it non accessible by outer code.
So in the second code you provide you are referencing random_index variable from outside of the function when you have declaring it inside the function.
So you need either to move this part that refers to rabdom_index, inside the function which declare the variable random_infex, or you must declare random_index using var not let keyword which make it global variable, then you can access it within the function and out of it
O hope that my explanation is clear enough, if you need any further help contact me
0
// Get all the images
image_array = [
'1.jpg',
'2.jpg',
'3.jpg',
'4.jpg'
]
function get_random_image(){
// Get a random index
random_index = Math.floor(Math.random() * image_array.length);
// Get an image at the random_index
selected_image = image_array[random_index]
// Display the image
document.getElementById('image_shower').src = `./images/${selected_image}`
}
0
That was his code. But i get undefine in my console marking my random_index red with error. eg. inside here; image[random_index] where random_index is undefined
0
Oh I'll give it a go
0
image_array = ["Union.png", "Union1.png", "Union2.png"];
function get_random_image() {
let random_index = Math.floor(Math.random() * image_array.length);
}
selected image = image_array[random_index];
document.getElementById("col1").src = "./assets/imagejs/coli/s(selected_image)";
0
I still got an 'Uncaught ReferenceError: random_index is not defined
Any suggestion is welcome