I'm trying to replace all img src's on my page, when they have a certain url in them. So far I'm able to log all the replaced img src's, but my final step would be to change them on my page.
function replaceMyImgs() {
// put live url here
var liveUrl = "via.placeholder.com";
// find the local url
var localUrl = "testdomain.com";
// replace the local url for the live url
var newUrl = localUrl.replace(/testdomain.com/g, liveUrl);
// console.log(newUrl);
// get all images and push them in an empty array
var imgs = document.getElementsByTagName("img");
var imgSrcs = [];
for (var i = 0; i < imgs.length; i++) {
imgSrcs.push(imgs[i].src);
}
imgSrcs.forEach(function(src) {
// log all the found img srcs
var newSrc = src.replace(/testdomain.com/g, liveUrl);
imgs.src = newSrc;
console.log(imgs.src);
});
}
window.onload = replaceMyImgs;
See my pen: https://codepen.io/kleefaan/pen/yqzBVv
Instead of pushing all elements into an array you can do the replace in the for loop like this:
// get all images
var imgs = document.getElementsByTagName("img");
for (var i = 0; i < imgs.length; i++) {
var newSrc = imgs[i].src.replace(/testdomain.com/g, liveUrl);
imgs[i].src = newSrc;
console.log(imgs[i].src);
}
Related
I have two arrays.One of videos and one of images. I need to play only one video at a time when image is clicked. Like if clicked on img[1] then it should play video[1] and if img[2] then video[2].
I need to do something like this : IMAGE
I have gone through few examples but didn't find any similar answer using only javascript. Now when i click on image it opens anchor tag link which i have added for testing but not able to play videos.
var videosList = [
"http://media.w3.org/2010/05/sintel/trailer.mp4",
"http://media.w3.org/2010/05/bunny/trailer.mp4",
"http://vjs.zencdn.net/v/oceans.mp4"
];
var allVideos = videosList.length;
var i = 0;
for (; i < allVideos; i++) {
var vid = document.createElement('source');
vid.src = videosList[i];
document.getElementById('myVideo').appendChild(vid);
}
var images = [
'https://picsum.photos/200/300',
'https://picsum.photos/id/237/200/300',
'https://picsum.photos/200/300?grayscale',
'https://picsum.photos/id/237/200/300',
'https://picsum.photos/200/300'
];
var allPics = images.length;
var i = 0;
for (; i < allPics; i++) {
var a = document.createElement('a');
a.href = 'example.html';
var img = document.createElement('img');
img.src = images[i];
a.appendChild(img);
document.getElementById('myImg').appendChild(a);
}
Here is running code as example:codepen
// JavaScript can be change in the following way
// Assuming that the video to be played is the same as index of the image clicked
// make it as global to access in all functions
var videosList = [
"http://media.w3.org/2010/05/sintel/trailer.mp4",
"http://media.w3.org/2010/05/bunny/trailer.mp4",
"http://media.w3.org/2010/05/bunny/movie.mp4",
"http://vjs.zencdn.net/v/oceans.mp4"
];
window.onload = function() {
// for videos
var vid = document.createElement('source');
vid.src = videosList[0]; // playing first video in the array by default
document.getElementById('myVideo').appendChild(vid);
// for images
var images = [
'https://picsum.photos/200/300',
'https://picsum.photos/id/237/200/300',
'https://picsum.photos/200/300?grayscale',
'https://picsum.photos/id/237/200/300',
'https://picsum.photos/200/300'
];
var allPics = images.length;
var i = 0;
for (; i < allPics; i++) {
var a = document.createElement('a');
// a.href = 'example.html';
var img = document.createElement('img');
img.src = images[i];
img.id = i; // for the reference of clicked image
a.appendChild(img);
a.addEventListener("click", clickFn, false);
document.getElementById('myImg').appendChild(a);
}
}
/**click function for the image of the image */
clickFn = function(e){
var video = document.getElementById('myVideo');
video.src = videosList[parseInt(e.srcElement.id,10)];
video.play();
}
Hope it helps ..!!
modified code in codepen
I'm trying to save all the link strings into a text document, but it only saves the last link in the document (in this case Youtube.com).
I want it to save all the links to the saved txt document, what am I doing wrong?
https://jsfiddle.net/zfL2hzvp/4/
var links = document.querySelectorAll('a');
// Loop through all links
for (var i = 0; i < links.length; i++) {
// Store links in variable
var linksArray = links[i];
// Works fine in console
console.log(linksArray);
}
// Create text document — only saves 1st link in text doc
var textDoc = document.createElement('a');
textDoc.href = 'data:attachment/text,' + encodeURI(linksArray);
textDoc.target = '_blank';
textDoc.download = 'myFile.txt';
textDoc.click();
Can someone help me out here?
Thank you! :-)
(function() {
var links = document.querySelectorAll('a');
var linksArray = [];
// Loop through all links
for (var i = 0; i < links.length; i++) {
// Store links in variable
linksArray.push(links[i]);
// Works fine in console
console.log(linksArray);
}
// Create text document — only saves 1st link in text doc
var textDoc = document.createElement('a');
textDoc.href = 'data:attachment/text,' + encodeURI(linksArray.join('\n'));
textDoc.target = '_blank';
textDoc.download = 'myFile.txt';
textDoc.click();
})();
https://jsfiddle.net/um4qhsks/1/
I am trying to get to the img.src of these table cells, but am going wrong somewhere.
var cell = newTable.rows.cells;
var content = newTable.getElementsByTagName('img');
var nodeArray = [];
for(var i = 0; i < content.length; ++i)
{
nodeArray[i] = content[i];
}
var listThem = $(this).attr('src');
console.log(listThem);
Use this :
var content = newTable.getElementsByTagName('img');
for(var i = 0; i < content.length; i += 1) {
var source = content[i]['src'];
//do something
}
getElementsByTagName() returns an array of dom elements.
To access the "src" attribute of a dom element, you can do this : element.src or element['src'];
source will contain the image source.
with ajax i get an array of pictures URL and then I need to create from them the gallery. I also need to make a counter that shows the number of downloaded images, it looks like this:
var images;
var load_image = new Image();
load_image.onload = function(){
myPhotoSwipe.show(0);
}
$.each(images['images'], function(key, value) {
load_image.src = ('index.php?load_image=' + value);
$('#image_count').remove();
$('span[class="loading"]').after('<div id="count"><h6>Images: ['+key+' / '+images_array['images'].length+']</h6></div>');
images+= '<li><img src="index.php?load_image='+value+'" /></li>';
});
The problem is that the counter is always loaded at penultimate element and stay there until all images are loaded, but I need to show the load of each like a progress.
P.S.
I also tried complete, but it didn't help.
This should fix it. The reason is because the load handler was being bound to only 1 image object.
var images;
$.each(images['images'], function(key, value) {
var load_image = new Image();
load_image.src = ('index.php?load_image=' + value);
$('#image_count').remove();
$('span[class="loading"]').after('<div id="count"><h6>Images: ['+key+' / '+images_array['images'].length+']</h6></div>');
images+= '<li><img src="index.php?load_image='+value+'" /></li>';
load_image.onload = function(){
myPhotoSwipe.show(0);
}
});
You are almost there.
The problem is that you are re-using the same image object. You need to create an array of load_image instances and increment your counter inside onload, when each of them returns.
function load(){
var imageUrls = [];
imageUrls.push('http://www.nasa.gov/images/content/690106main_iss033e005644_full.jpg');
imageUrls.push('http://www.nasa.gov/images/content/690669main_201209210010_full.jpg');
imageUrls.push('http://www.nasa.gov/images/content/691806main_hs3_full_full.jpg');
imageUrls.push('http://www.nasa.gov/images/content/689231main_Webb_Mirror_Cans_orig_full.jpg');
var images = [];
var i;
var counter = 0;
var mainDiv = document.getElementById('somediv');
var counterDiv = document.getElementById('counter');
for (i = 0; i < imageUrls.length; i++)
{
images[i] = new Image();
images[i].width = 100;
images[i].height = 100;
images[i].onload = function () {
counter++;
counterDiv.innerText = counter;
}
mainDiv.appendChild(images[i]);
images[i].src = imageUrls[i];
}
}
I have following code to use google images search API:
google.load('search', '1');
function searchComplete(searcher) {
// Check that we got results
if (searcher.results && searcher.results.length > 0) {
// Grab our content div, clear it.
var contentDiv = document.getElementById('contentimg');
contentDiv.innerHTML = '';
// Loop through our results, printing them to the page.
var results = searcher.results;
for (var i = 1; i < results.length; i++) {
// For each result write it's title and image to the screen
var result = results[i];
var imgContainer = document.createElement('div');
var newImg = document.createElement('img');
// There is also a result.url property which has the escaped version
newImg.src = result.tbUrl;
imgContainer.appendChild(newImg);
// Put our title + image in the content
contentDiv.appendChild(imgContainer);
The problem is, it gives me 3 image results. How to break a loop and show only the 1st one instead of 3 images?
if I change for (var i = 1; i < results.length; i++) to for (var i = 3; i < results.length; i++) it shows only one image, but image shown is the 3rd one and I need to show 1st one :)
Please advice
Don't use a for loop at all. Just replace all instances of i with 0.
google.load('search', '1');
function searchComplete(searcher) {
// Check that we got results
if (searcher.results && searcher.results.length > 0) {
// Grab our content div, clear it.
var contentDiv = document.getElementById('contentimg');
contentDiv.innerHTML = '';
var result = searcher.results[0];
var imgContainer = document.createElement('div');
var newImg = document.createElement('img');
// There is also a result.url property which has the escaped version
newImg.src = result.tbUrl;
imgContainer.appendChild(newImg);
// Put our title + image in the content
contentDiv.appendChild(imgContainer);
0 means the first item returned (almost all number sequences in programming start at 0!) so all other results will be ignored.
When you only want one element, you don't need a for loop. You can access the first element of an array with
result = results[0];
Arrays are zero-based. So when it contains three images, the images are named results[0], results[1] and results[2].
use break statement. It will terminate the loop once the image is found and hence you will have only the first one.
for (var i = 1; i < results.length; i++) {
// For each result write it's title and image to the screen
var result = results[i];
var imgContainer = document.createElement('div');
var newImg = document.createElement('img');
// There is also a result.url property which has the escaped version
newImg.src = result.tbUrl;
imgContainer.appendChild(newImg);
// Put our title + image in the content
contentDiv.appendChild(imgContainer);
//Berore the end of the loop
if(i==1)
{
break;
}
}