Hi i found this code online, its for a memory game created in JavaScript,
I want to be able to put images in the array instead of the letters that are there, how do I do it?
Thank You
you must add image source (src) to array, not images.
and if you want to change image , just change src.
<img id="myImage" />
<script>
var x = new Array('1.jpg', '2.jpg', '3.jpg');
var img = document.getElementById("myImage");
img.setAttribute("src", x[0]);
</script>
Related
I have an assignment where I need to make a photo appear when I click on another photo. I need to put each image in an array and call on it to appear when I click on the corresponding photo. When I click on another photo, I need to remove the existing photo and replace it with another one. I need to do it with Javascript and the DOM. I'm unsure how exactly I would do this. Here's my code so far:
var photoDiv = getElementById("photos");
document.getElementById("0").addEventListener("click", function () {
var img = createElement("img");
photoDiv.appendChild(img);
})
I know it's completely wrong but I don't know what to do to fix it :(
You have to add the image source of your image.
After this line:
var img = document.createElement("img");
img.src = 'pathto/yourimg.png_or_jpg'; // You need this.
Also, it's always a good practice to use document.getElementById() (or putting the parent) instead of just getElementById().
Instead of creating a new image you can also replace only the src of the image element, something like this:
// get the image
var imgElement = document.getElementById("myImage");
// add the listener
imgElement.addEventListener("click",
function () {
// update the src of the image
imgElement.src = "https://www.w3schools.com/html/img_girl.jpg";
});
and that's all, you should not create a new element and append it to the DOM element.
I want to show a random picture with every refresh but I don't know why my code is not working... probably because I'm bad at javascript, haha.
I tried "3" instead of "imgs.length", but it's still not working - I too don't really want to give an exact number, because the image count may vary.. only for my example I use three images.
var imgs = ['img1','img2','img3'];
function getRandomImage(){
var rnd = Math.floor(Math.random()*imgs.length);
document.getElementById('pr_randImage').src = imgs[rnd];
}
</script>
<img id="pr_randImage">
Quellcode is just not showing any src at all for the img. What am I doing wrong? I'm thankful for every help.
change this
var imgs = ['img1','img2','img3'];
to something like this depending on extension of the image you are using
var imgs = ['img1.png','img2.png','img3.jpg'];
If that still doesn't work then you need to include the path of where the images are
Something like this
document.getElementById('pr_randImage').src = "/images/" + imgs[rnd];
I am learning to code in JavaScript and my assignment was to find out what each line of this code means. I've tried to figure out some of the code but the part which confuses me most is the functions,'div classes',document.createElement('something') and the append.Child('something').I have researched on the internet but it is vaguely explained. Please can someone explain each line of the code;here is the code:
<!DOCTYPE html>
<html>
<head>
<title>Traffic lights</title>
</head>
<script>
var images = ['redlight.jpg', 'Red -yellow light.jpg', 'Green Light.jpg', 'Amber Light.jpg'];
var index = 0;
function buildImage() {
var img = document.createElement('img')
img.src = images[index];
document.getElementById('content').appendChild(img);
}
function changeImage() {
var img = document.getElementById('content').getElementsByTagName('img')[0]
index++;
index = index % 4;
img.src = images[index];
}
</script>
<body onload="buildImage();">
<div class="contents" id="content"></div>
<button onclick="setInterval(changeImage, 3000)">NextImage</button>
</body>
Thanks in advance
First Part:
function buildImage() {
var img = document.createElement('img')
img.src = images[index];
document.getElementById('content').appendChild(img);
}
This function
first create dynamic html tag of image
Assign Image src/path that contained in the var images =
['redlight.jpg', 'Red -yellow light.jpg', 'Green Light.jpg', 'Amber
Light.jpg'];
first get html tag that has id name content then append it means
to hold the previous and next images
Second Part:
function changeImage() {
var img = document.getElementById('content').getElementsByTagName('img')[0]
index++;
index = index % 4;
img.src = images[index];
}
This function
first initialize the img variable with the content/image that hold
in content div by access through an array index Increment to
access other image
using Modulus logic to get images that are on 4 index
Relace srcwith existing
This code displays an image when the page is loaded, then changes the image every 3 seconds after the user clicked the button once. Here is how it works:
buildImage is a function that creates an <img /> element (document.createElement) and set the source (img.src) attribute to one of the sources listed in the array images. Which one exactly depends on the index variable. It then adds the element to the html page, under the div with the id content (getElementById('content').appendChild(img)). So you end up with:
<div class="contents" id="content">
<img src="redlight.jpg" />
</div>
The function is called only once, when the page is loaded (see the onload attribute).
changeImage changes the image source (img.src). the code
document.getElementById('content').getElementsByTagName('img')[0]
means "get the div with id = content, then find all the html tags "img" and return the first one".
the code
index++; index = index % 4;
increments the index variable, but ensure it is never more than 4 (the size of your array, see the modulo operator).
Finally, the setInterval is a function which takes a function name and a duration in milliseconds. Once called, it will run the function every X ms.
!!
In this code, the setInterval function is called on every click. It might be problematic. I would change it if I were you.
document.createElement('img') creates a new <img /> tag. img.src = images[index] takes the path of the first element inside images (because index is set to 0 at the beginning) and sets the source (='redlight.jpg'). With document.getElementById('content').appendChild(img) you add the created <img src='redlight.jpg' /> tag inside your <div> with id = 'content'.
div class='contents' defines that your div is using the css class 'contents'. This css class handles the styling of your div element.
There are really good explanation for this all at http://www.w3schools.com/. You should study that page.
For the parts that you are insecure about.
Function
Functions is a big subject itself. It's a huge part of about every programming language. It's a way to in an effective way do something that you might want to do more than one time. Lets say you want to make a function that subtracts two values, but you want to use it for any value. Then you can create a function that takes two parameters and do the calculation...
function sub(x, y)
{
return x-y;
} // Very basic example
In that way you can send any values.
document.createElement('img')
Will simply just create an HTML-tag. In this case an 'img' tag. In your case they want to create one in order to place it inside another element.
Div classes(?) No idea what this is. Any examples?
document.getElementById("something").append.Child('something2')
What this will do is simply take an element by it's id. It can be a DIV or List etc. Then you simply put your element "something2" inside that element. So if something2 is an img, and something is a div. The result would be like:
<div>
<img>
</div>
Onload i.e when the page has being loaded it calls buildImage() function of javascript.This function creates a img tag and appends to the div which is of class 'contents'(Since index is 0 it loads a first image i.e img.src = images[index]).
And once you click on button every 3000 milliseconds its changes the image source to different image based on the index
I have a html snippet being returned through ajax. The snippet is an <img> tag.
<img src="image.jpg" />
I need to extract the value of the src attribute without loading the image initially. The reason for this is the src attribute contains a partial path that I need to manipulate in my app to load the image properly.
I have the following code currently extracting the src attribute:
var src = $(value).attr('src');
However, this causes the image to load, resulting in a 404. I would like to avoid this unnecessary request.
How can I extract the value of the src attribute without causing the browser to load the image?
I solved this by changing the name of the src attribute before loading it into jquery.
value = value.replace('src', 'data-src');
var src = $(value).attr('data-src');
Doing this allows me to extract the value without causing the browser to attempt to load the images.
Your best bet is probably to output a data tag on the image. You can then manipulate this using jQuery and then use it to write the final image path.
So you'd do something like this in your HTML:
<img data-img-src="abc.jpg" class="my-image" />
Then in your jQuery:
var path = $('.my-image').data('img-src');
console.log(path); // Do something here, then write the new path with:
$('.my-image).attr('src', new_path);
EDIT: Sorry I just re-read the bit where it's coming via AJAX. In that case, you can probably use the data callback of your ajax request to strip the src from the image.
$.ajax('someURL.html', function(data){
var html = data.replace(/\ssrc/g, ' data-src'),
img = $(html),
src = 'some/path/' + img.data('src');
img.attr('src', src);
$('#container').append(img);
});
If you just have the string , like <img src="image.jpg" /> why dont you go for regex?
Something like: /[\"\'][a-z0-9A-Z\.]*/.
PS:My regex skills are poor,so you could manipulate it accordingly.
Use
var string = '<img src="image.png">';
var matches = string.match(/src\=("|')(.*?)\1/);
console.log(matches[2]);
You can simply remove the attribute after accessing it.
This will not load the invalid image, as you can confirm in your console:
var s= $('<img src="invalidURL.jpg">'),
src= s.attr('src');
s.removeAttr('src');
console.log(src);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Remove removeAttr(), and it will attempt to load the image.
I'm trying to make some basic image slider as a part of JS excersises, and I've noticed something weird when I ran this script.
The source of an image stored in array under the 0 index is changing when I'm trying to change source image in html code with 'setAttribute' method, so when I want to get back from fifth image to one, this proto-slider (nothing is sliding at the moment) is stuck at second image.
My files are named 0.jpg - 5.jpg.
I've preloaded the images to be displayed smoothly without flicker and I'm displaying one image after the page loads, and then I'm trying to change source of this image to source of next image in array of images. Is this the right way to do it?
Here's the code:
var images = new Array(5);
var i=0;
function addImages(){
for (var j=0;j<images.length;j++){
images[j] = new Image();
images[j].src = j+".jpg";
console.log(images[j].src);
}
var article = document.getElementById("article");
article.insertBefore(images[0], document.getElementById("nav"));
}
function next(){
if (i<images.length-1){
document.getElementsByTagName('img')[0].setAttribute('src',images[++i].src);
console.log(images[0].src);
}}
function prev(){
if (i>0){
document.getElementsByTagName('img')[0].setAttribute('src', images[--i].src);
console.log(images[0].src);
}
}
What is the best way to do such a this as dynamically changing image sources?
I've thought about this:
article.removeChild(document.getElementsByTagName("img")[0]);
article.insertBefore(images[++i], document.getElementById("nav"));
I want to know if this isn't considered as a bad practice and what are the other ways to do it in single line of code.
Thanks in advance and sorry for grammar mistakes.
You could just insert empty image
<img id="someid">
and then use document.getElementById("someid").src=images[0].src
If you'd like to be sure that images[0] is completely loaded, use onload function, like:
images[0].onload=function()
{
document.getElementById("someid").src=images[0].src;
}