2 Questions:
What will be the most officiant way to loop through all of the Images on a given page and open each one in a new tab.
Same idea but instead open in a new tab I would like to push different images instead of the given ones. The idea is to build a widget that will inject cat photos instead of the normal photos of websites.
I answered 2 in the code, and 1 in the comment of the first code block
var allImages = document.getElementsByTagName('img');
for(var i = 0; i < allImages.length ; i++) {
// to open all photos in new tabs:
// window.open(allImages[i].src, '_blank');
allImages[i].src = 'url_to_cat_image';
}
you can also do the same with jquery:
// change all photos to the same one:
var allImages = $('img');
allImages.attr('src', 'url_to_cat_image');
If you want each photo to be a different image, just replace the url_to_cat_image with a function that returns a random cat image in the first code block. For jquery, you can use .each and a random cat url function.
Here's a way of doing it with vanilla js. As mentioned in the comments, using the document.images node-list is the best method for getting the images, since it's a static list and need not be assembled in response to dom queries.
As mentioned, browsers will block the attempts to open new windowss, labelling them as pop-ups.
Here's a demo:
function forEachNode(nodeList, func) {
for (var i = 0, n = nodeList.length; i < n; i++) func(nodeList[i], i, nodeList);
}
function onBtnClicked() {
var diskUrl =
"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAA4AAAAOCAYAAAAfSC" +
"3RAAABdElEQVQoU22SLX/CMBCH/3E4IueorKNysh+hH6ESR93mqBuOuuEWiYyczB" +
"zycJPBIa+uU9nvmlD2wonmLulz78q+c4DIMH7Hk0UfOJ5/75KtrOWg9RxEwHqdfr" +
"xz9F9AXX9Ag8fXG3jssX6a3yUFwtCjqgnsDbK8gjIHDtnDHM6dsdks/oFXSNKuVg" +
"5VXoA+HZQxHLJsDvt+xu7lN/gTYgbqxqHMM3hPUGbvQ5YvYO0Ju91yivgX4oETWI" +
"AvBNV1PhTFAuZwwttrBO9B0u2qkVSzBG4jKL2yhxNYtDSSmx5HM0LyxgTVthEUkT" +
"qY+2mO0cHVUZrrOF8P1T5TKIpl8tTDHdvfnZ0BeqbBXN6WYiCoRsB8OUUiamEPHY" +
"qyhNlbYAZ0+w6eirRFUpSHapoIeu5Hj/TZwV8I5WOFZlUn0MA5DS3lANCSarOikE" +
"nRzDBHAi4dum1MV1IcI25beK6mvdUgKLHqlQsCSsRJpAlXIzUomvH+G/9qC1CEZi" +
"AJAAAAAElFTkSuQmCC";
forEachNode(document.images, function(elem) {
elem.oldSrc = elem.src;
console.log(elem.src);
window.open(elem.src);
elem.src = diskUrl
});
}
function onResetBtn() {
forEachNode(document.images, function(elem) {
if (elem.oldSrc != undefined) elem.src = elem.oldSrc;
});
}
<button onclick='onBtnClicked()'>Open pop-ups, change image sources</button>
<button onclick='onResetBtn();'>Reset</button>
<br>
<img src='data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAQAAAAHCAYAAAAvZezQAAAAKElEQVQIW2MUder+/3pfKSMDFDCCBEBsmCBcACaIIgASxK0CxQxkWwA6axnpT9J3PwAAAABJRU5ErkJggg==' />
<img src='data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAQAAAAHCAYAAAAvZezQAAAAJElEQVQIW2NkQAKiTt3/GWF8EAfEBgvAOGABZA52FVjNQBYEAPsjDS+SFXnjAAAAAElFTkSuQmCC' />
This is how you loop through all the images in a page.
I've also added example of opening in a new tab or replacing the source.
using native JavaScript no dependencies required.
// Array of cat photos
var arr = ['cat1.jpg', 'cat2.jpg', 'cat3.jpg'....]
var elem = document.getElementsByTagName('img');
for (var i = 0; i < elem.length; i++) {
var src = elem[i].getAttribute('src');
// Open in a new tab
if (src) window.open(src);
// Replace with a random cat photo
elem[i].src = arr[Math.floor(Math.random() * arr.length)];
}
Using vanilla javascript :
var images = document.querySelectorAll("img");
for(var i = 0;i < images.length;i++){
var image = images[i];
window.open(image.src,"_blank");
}
// changing for a kitty image
var images = document.querySelectorAll("img");
for(var i = 0;i < images.length;i++){
var image = images[i];
image.src = "http://placekitten.com/600/338";
}
However, if there are more than 1 image the browser will prevent that (see the popup message and allow that behaviour).
Related
// this code is meant to create an array of two images and just circle through them to make it appear that a lightbulb is flashing on and off.
var imageArray = new Array();
var numImages=2;
// create new array to hold preload images; call this array imageArray
// create (global!) variable called numImages to hold total number of images;
//use for loop to populate imageArray
for (var i = 0; i < numImages; i++) {
imageArray[i] = new image();
imageArray[i].src="images/brightIdea"+(i+1)+"png"
//set image src property to image path, preloading image in the process
}
var i4_circleThru = 0; // global variable ( be careful) use for the function CicleThru()
function circleThru() {
//if browser does not support the image object, exit.
// write images, from imageArray to HTML doc
// call the setTimeout method on circleThru
}//end circleThru()
Because your end result is an html image, why not do it this way:
First, in your HTML:
<img id="imageID">
Then in your script:
var imageArray = [];
var numImages = 2;
for (var i = 0; i < numImages; i++) {
imageArray[i] ="images/brightIdea"+(i+1)+".png"
}
var i4_circleThru = 0;
var image = document.getElementById("imageId");
image.src = imageArray[i4_circleThru];
window.setInterval(function(){
i4_circleThru = (i4_circleThru+1)%numImages;
image.src = imageArray[i4_circleThru];
},1000);
A more complete example can be found here:
https://jsfiddle.net/FrancisMacDougall/fseswsro/
I made this code to take images from the page, convert them into data:url (what was it again... base64 encoded string), and save into localStorage. Then when the page is reloaded it should load the images from the localstorage and set the now empty image placeholders with the data:url image.
Issue now is that the images do not load and if you check the dimensions for the data:url image it is 300x150 when it was originally 40x40.
Here's the code:
var isChached, // Checks is the page's images have been chached into localStorage
isChangesd; // Checks if any images have been deleted or added to the
var img = [], // Used for loading from saved. img[] holds data:url image versions of the...
src = [], // ...images in src[]
saved = [], // All images that are to be saved are placed here
add = [], // New images are placed here
rem = []; // Images to be removed are placed here
var cnv = document.createElement("canvas");
ctx = cnv.getContext("2d");
if (window.localStorage) {
// Base Object
function Saver (width,height,path) {
this.width = width;
this.height = height;
this.src = path;
}
// These fucnctions will help you save, load, and convert the images to data:url
function save (_str) { // Saves to localStorage. _str is the key to which to save to. _path is the value that you plan on saving
var str = _str;
str += ""; // This way even if I input a none string value it is still converted into string
localStorage.setItem(str,JSON.stringify(saved));
} // Checks if this image isn't in the saved cache
function singleLoad(a,b) {
}
function loader (_str) { // Loads images from localStorage. _str is the key to be loaded
var str = _str;
str += ""; // This way even if I input a none string value it is still converted into string
var val = JSON.parse(localStorage.getItem(str)); // Save the now loaded and parsed object str into val
console.log('val '+JSON.stringify(val));
val.splice(0,1);
console.log('val2 '+JSON.stringify(val));
for (var i in val) { // Take loaded information and place it into it's proper position
img[i] = new Image(val[i].width,val[i].height);
img[i].src = val[i].src;
setTimeout(function () {
var imgs = document.getElementsByTagName("img"); // Get all images
for (var k = 0; k < imgs.length; k++) {
if (imgs[i].id == i) { // If the id is equal to the index name of the src[]
imgs[k].src = val[i].src;
imgs[k].height = img[i].height;
imgs[k].width = img[i].width;
console.log("array: "+imgs[i]+". img[i]"+img[i]);
}
}
},2000);
}
}
function addToAdd(_id,_path) { // Places on-page images into src[]
var id = _id;
id += ""; // Makes sure that the id variable is a string
var path = _path;
path += ""; // Makes sure that the path variable is a string
add[id] = new Image();
add[id].src = path;
var imgs = document.getElementsByTagName("img");
console.log(imgs);
for (var i = 0; i < imgs.length; i++) { // adds width and height attributes
if (imgs[i].id == id) {
setDim(add[id],imgs[i].width,imgs[i].height); // Send info to setDim()
}
}
}
// Not using this
function apply() { // takes images from img after being loaded and adds them to the page.
var images = document.getElementsByTagName("img");
for (var i = 0; i < images.length; i++) { // Check through the page's images
for (var k in img) { // Check through the img[] where the loaded images are now saved
if (images[i].id = k) { // Check if the id of the image on the page is
images[i].width = img[k].width;
images[i].height = img[k].height;
images[i].src = img[k].src;
console.log("source: "+images[i].src);
console.log("images: "+images[i]+". saved images "+img[k]);
}
}
}
}
function setDim(obj,w,h) { // Sets the dimension(width = w; height = h;) for obj (image object)
obj.width = w;
obj.height = h;
}
function saveToSrc(_id,_path,w,h) { // Places on-page images into src[]
var id = _id,data;
id += ""; // Makes sure that the id variable is a string
var path = _path;
path += ""; // Makes sure that the path variable is a string
src[id] = new Image();
src[id].src = path;
console.log("src image " + src[id]);
var imgs = document.getElementsByTagName("img");
console.log("page images " + imgs);
for (var i = 0; i < imgs.length; i++) { // adds width and height attributes
if (imgs[i].id == id) {
setDim(src[id],imgs[i].width,imgs[i].height); // Send info to setDim()
src[id].addEventListener("load",function() { // We convert images to data:url
console.log("saved image " + src);
ctx.drawImage(src[id],0,0,w,h);
data = cnv.toDataURL();
console.log("saved src " + data +" src width and height: "+src[id].width+","+src[id].height);
saved[id] = new Saver(src[id].width + "px",src[id].height + "px",data);
console.log("saver array: "+saved[id]);
})
}
}
}
function loadToPage(a) {
var imgs = document.getElementsByTagName("img"); // Get all images. Use this to change image src and dimensions
for (var i in a) { // Go through the a[] and load all the images inside onto page
for (var k = 0; k < imgs.length; k++) {
if (imgs[k].id == i) {
imgs[k].src = a[i].src;
imgs[k].height = a[i].height;
imgs[k].width = a[i].width;
}
}
}
}
// Here you place ID and path/location values into the src[] using the saveToSrc(). You can place the parameters in with quotation marks or without quotation marks
// **N.B** the location link will have to be changed to it's absolute form so that even if a 'scraper' gets our webpage the links still come to us \o/
if (localStorage.getItem("cached") == null) { // Check if the "cached" key exists.
// If it doesn't exist...
isCached = false;
localStorage.setItem("cached","true");
} else {
// ...If it does exist
isCached = true;
}
if (!isCached) {
// Now you take images from server and load onto page. And then save them.
window.onload = function() {
saveToSrc("1","img/1.png",40,40);
saveToSrc("2","img/2.png",40,40);
saveToSrc("3","img/3.png",40,40);
saveToSrc("4","img/4.png",40,40);
console.log("src "+src);
console.log("saved array " + saved);
loadToPage(src);
setTimeout(function() {
save('saved');
},3000)
}
}
/* Will Be Added Later. Same time as local host */
else {
window.onload = function (){
setTimeout(function() {
loader("saved");
apply
},3000)
}
}
}
I'm quite new to javascript(started using javascript this June, or was it May. anyways...) so please relax on the terminology.
To recap: Images saving correctly(-ish), not loading, and wrong image sizes saved
I'm using plain Javascript in a 3d art gallery. I have an image source array and am populating certain columns by pulling from this array. I need to get the index of the image on click so that I can use that to pull further information from said array...Titles, Descriptions.
I could do this with jQuery but I am trying to learn plain Javascript. I already have event listeners on all the images. Here is the current code:
var preview = document.getElementById('preview');
var subwrap = document.getElementById('subwrap');
var indexMatch;
for (var i=0; i <= imgList.length; i++){
document.images[i].addEventListener("click", srcSend, false);
}
function srcSend(){
var previewTitle = "Test Title";
var previewText = "Test Description";
var imgSrc = this.src;
console.log('Image Source ='+''+imgSrc+'');
if (imgSrc !== "file:///D:/Projects/mpaccione/img/navicon.png"){
preview.className = " ";
subwrap.className = "hide";
preview.className = "show";
preview.innerHTML = '<img src='+imgSrc+'><p id="title">'+previewTitle+'</p><p id="description">'+previewText+'</p>'; }}
You should be able to use the Array.indexOf on the images collection.
function srcSend(){
var index = Array.prototype.indexOf.call(document.images, this);
}
You can send the index to the srcSend function.
for (var i=0; i <= imgList.length; i++){
document.images[i].addEventListener("click", function(){
return (function(index) {
srcSend(index);
})(i);
}, false);
}
I'm hacking together a little Dropbox image slideshow. I use the Dropbox Public folder to share the index.html file which looks in the 'img' folder for a bunch of images to create slides.
I do this with the following, it's hacky but works
var findFiles = function(slideLimit){
var limit = slideLimit;
var img = [];
for(var i = 1; i < limit; i++){
var src = "<li class='slide slide-"+i+"'><img src='img/"+i+".png' onerror='imgError(this);''></li>"
$('.frame ul').append(src);
}
}
That works great, but I'd like to provide a solution that doesn't rely on the user having to use .png.
I was hoping omitting the extension would work on Dropbox but turns out no:
var src = "<li class='slide slide-"+i+"'><img src='img/"+i+"' onerror='imgError(this);''></li>"
I've been racking my brains, ideally I'd like
if( mimeType = png)
i + '.png'
else if (mimeType = gif)
i + '.gif'
etc
Bit stuck for solutions. Anyone got any good ideas? Might require me taking different a different direction...
Best way, make the users tell you the extension
var findFiles = function(slideLimit, ext){
var limit = slideLimit,
img = [],
lis = [];
ext = ext || "png";
for (var i = 1; i < limit; i++) {
lis.push("<li class='slide slide-"+i+"'><img src='img/"+i+"."+ext+"' onerror='imgError(this);''></li>");
}
$('.frame ul').append(lis.join(""));
}
Ping the server for the file, downside it takes time to keep hitting the server to see if the file it there
var findFiles = function(slideLimit){
var limit = slideLimit,
img = [],
lis = [],
extList = ["png","gif"];
function testExt () {
var ext = extList.shift();
if (ext) {
var img = new Image();
img.onload = function () {
load(ext);
};
img.onerror = testExt;
img.src="img/1." + ext;
}
}
function load (ext){
for (var i = 1; i < limit; i++) {
lis.push("<li class='slide slide-"+i+"'><img src='img/"+i+"."+ext+"' onerror='imgError(this);''></li>");
}
$('.frame ul').append(lis.join(""));
}
testExt();
}
[note both code snipplets are untested, wrote them here in the editor]
Alright, I have been looking off and on for almost a year now (spent all of March trying to do this), and I simply CAN NOT find the code to make this work.
Here's my problem:
I have a code that retrieves my most recent upload for the player on my website (http://weapwn.com). This code only gives me the video, though.
I need code to get the description - not from any one video ID, but from the variable video ID - but all I have is this:
<script type="text/javascript">
function showMyVideos2(data) {
var feed = data.feed;
var entries = feed.entry || [];
var html = ['<ul>'];
for (var i = 0; i < entries.length; i++) {
var entry = entries[i];
var content = entry.content.$t;
html.push('<i>', content, '</i>');
}
html.push('</ul>');
document.getElementById('featdesc').innerHTML = html.join('');
}
</script>
Now - replacing "content" does nothing, unless I use "title" (which only retrieves the video title). I must know how to get this damn elusive code to work, because the parameters that Youtube lists are not working!
Am I going about this entirely the wrong way? Or is there simply an error to fix in my code?
Try this:
function showMyVideos2(data) {
var feed = data.feed;
var entries = feed.entry || [];
var html = ['<ul>'];
for (var i = 0; i < entries.length; i++) {
var entry = entries[i];
var title = entry.title.$t;
var description = entry.media$group.media$description.$t.replace(/\n/g, '<br/>');
var content = entry.content.$t;
html.push('<i>', content, '</i>','<i>', title, '</i>','<i>', description, '</i>');
}
html.push('</ul>');
document.getElementById('featdesc').innerHTML = html.join('');
}
Hope it helps...