Break javascript loop - javascript

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;
}
}

Related

How to get the index of a string in google docs using google App Script

I want to search for a string and then replace it with an image on google docs. For that, I want to get the index of the string and then replace it with an image. But I'm unable to get the index of the string so far.
Below is a snippet of what I am doing:
var element = '<<19>>';
options = {muteHttpExceptions: true};
var resp = UrlFetchApp.fetch(mylist[x-1], options);
var image = resp.getBlob();
//getting the index of element and then replacing it with image
var rangeElement = body.findText(element);
var foundElement = rangeElement.getStartOffset();
body.replaceText(element, body.insertImage(foundElement, image));
I've tried using findText(searchPattern) but it didn't work as it returns a range element and I'm getting output as 0 everytime.
This is how you find text on your document and replace it with an image:
function findAndReplaceWithImage() {
var element = "<<19>>";
var doc = DocumentApp.getActiveDocument().getBody();
var image = "your image url";
var blob = UrlFetchApp.fetch(image).getBlob();
var paragraphs = doc.getParagraphs();
for (var i = 0; i < paragraphs.length; i++) {
var text = paragraphs[i].getText();
if (text === element) {
//Found your match
doc.removeChild(paragraphs[i]);
doc.insertImage(i, blob);
}
}
}
Hope this helps!

Replace all img src on page load - Javascript

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);
}

Inserting text after a certain image using javascript

In one function I have a loop that creates 10 images using the createElement();. In the other function I have another loop that contains info that I need to add text after each picture but my code adds it at the end of all 10 pictures I need them to be after every corresponding picture.
This is the function that displays the text:
function displayAlbum(json){
for (var x = 0; x<json.length;x++){
var span1 = document.createElement("span");
span1.innerText = json[x].album;
console.log(json[x].album);
var display = document.getElementById("results");
display.appendChild(span1);
}
}
I cant individually set the id of each image because i created them in js. Thanks for the help in advance and no jquery please
for (var x = 0; x<json.length;x++){
var image = document.createElement("img");
image.id = "picture";
image.width = 100;
image.height = 100;
image.src = json[x].cover;
var display = document.getElementById("results");
display.appendChild(image);
var a = document.getElementById("artist");
var y = document.getElementById("year");
var artist = document.getElementById("artist").selectedIndex;//index of value of the switch statement
var year = document.getElementById("year").selectedIndex;//index of value of the switch statement
var realYear = y[year].text;//Value of the selected text
var realArtist = a[artist].text;//Value of the selected text
var display = document.getElementById("Results");
}
This is my second loop. I want displayalbum to appear after every picture. I cannot combine them because of other complications in the code
Try to do something like that: plunker
function displayAlbum(){
for (var x = 0; x < 10 ; x++){ // change to json.length
var span1 = document.createElement("span");
span1.innerText = 'json[x].album';
span1.id = 'span'+x;
var display = document.getElementById("results");
display.appendChild(span1);
}
}
The loop where you are creating images, give a unique id to image like image.id = "picture" + x;
Then change displayAlbum() function to use corresponding image to place the span tag.
function displayAlbum(json){
for (var x = 0; x<json.length;x++){
var span1 = document.createElement("span");
span1.innerText = json[x].album;
console.log(json[x].album);
var display = document.getElementById("results");
var img = document.getElementById("picture" + x); // use unique id of img to access it
if(img.nextSibling) { // if img is not the last node in 'results'
display.insertBefore(span1, img.nextSibling);
} else { // if img is the last node in 'results'
display.appendChild(span1);
}
}
}
You can achieve your goal with single loop and using Figure and FigCaption element , specifically created for this kind of display image with its description
var json = [{cover:"https://upload.wikimedia.org/wikipedia/commons/thumb/d/da/Internet2.jpg/440px-Internet2.jpg", album:"test1"},{cover:"https://upload.wikimedia.org/wikipedia/commons/thumb/d/da/Internet2.jpg/440px-Internet2.jpg", album:"test2"}];
for (var x = 0; x<json.length;x++){
var fig = document.createElement("figure");
var figCap = document.createElement("figcaption");
figCap.innerText = json[x].album;
var image = document.createElement("img");
image.id = "picture";
image.width = 100;
image.height = 100;
image.src = json[x].cover;
var display = document.getElementById("results");
fig.appendChild(image);
fig.appendChild(figCap);
display.appendChild(fig);
}
<div id="results">
</div>

Why can't I get my images to appear in table cells/nodes.. maybe I can get some closure?

I want to add a new image in each cell of the new table and give it the same source as the old table, and then make it clickable. Firstly, I did this:
function showData() {
if (localStorage.getItem(name) !== null) {
var showme = localStorage.getItem(name);
alert("I got the table");
var newTable = document.createElement('table');
newTable.innerHTML = showme;
newTable.id = "newTable";
newNumRows = newTable.getElementsByTagName('tr').length;
newNumCells = newTable.getElementsByTagName('td').length;
newNumCols = newNumCells / newNumRows;
alert(newNumRows);
alert(newNumCells);
alert(newNumCols);
var newImages = newTable.getElementsByTagName('img');
for (var i = 0; i < newImages.length; i += 1) {
var picSource = newImages[i]['src'];
console.log(picSource);
}
function addNewImage(newNumCols) {
var newImg = new Image();
newImg.src = picSource;
col.appendChild(newImg);
newImg.onclick = function() {
alert("WOW");
};
}
for (r = 0; r < newNumRows; r++) {
row = newTable.insertRow(-1);
for (c = 0; c < newNumCols; c++) {
col = row.insertCell(-1);
addNewImage(newNumCols);
}
}
var showIt = document.getElementById('holdTable');
showIt.appendChild(newTable);
}
}
This works to a certain extent, but, unfortunately, only the last image was displaying. So, I did a bit of looking around and I think it has to do with closure (apologies for any duplication), but it's a concept I am really struggling to understand. So then I tried this:
function showData() {
if (localStorage.getItem(name) !== null) {
hideTaskForm();
var showme = localStorage.getItem(name);
var oldTable = document.createElement('table');
oldTable.innerHTML = showme;
newTable = document.createElement('table');
newTable.id = "newTable";
var i, r, c, j;
newNumRows = oldTable.getElementsByTagName('tr').length;
newNumCells = oldTable.getElementsByTagName('td').length;
newNumCols = newNumCells / newNumRows;
var newTableCells = newTable.getElementsByTagName('td');
var getImages = oldTable.getElementsByTagName('img');
for (r = 0; r < newNumRows; r++) {
row = newTable.insertRow(-1);
for (c = 0; c < newNumCols; c++) {
makeNodes = row.insertCell(-1);
}
}
for (var j = 0; j < newTableCells.length; j++) {
var theNodeImage = document.createElement("img");
newTableCells[j].appendChild(theNodeImage);
alert(newTableCells[j].innerHTML); //This gives me img tags
}
for (i = 0; i < getImages.length; i += 1) {
var oldSource = getImages[i]['src']; //gets the src of the images from the saved table
console.log(oldSource);
//alert(oldSource);//successfully alerts the image paths
var newPic = new Image(); //creates a new image
(function(newPic, oldSource) {
newPic.src = oldSource;
alert(newPic.src); //gives the same image paths
newTable.getElementsByTagName('img').src = newPic.src; //This doesn't work - table is blank???
})(newPic, oldSource);
}
var showIt = document.getElementById('holdTable');
showIt.appendChild(newTable);
}
}
Now, this doesn't throw any errors. However, nor does it fill the table. It does give me the source and I think I have created the new image objects to attach to the img tags in the newTableCells, but the table is showing up blank. I don't know where I am going wrong. All help really welcome.
Note: Even as a hobbyist, even I know there are probably tons of more efficient ways to do this, but I purposely did it this way to try and help me understand the logic of each step I was taking.
In your code you have:
var newImages = newTable.getElementsByTagName('img');
for (var i = 0; i < newImages.length; i += 1) {
var picSource = newImages[i]['src'];
console.log(picSource);
}
At the end of this, picSource has the value of the last image's src attribute. Then there is:
function addNewImage(newNumCols) {
var newImg = new Image();
newImg.src = picSource;
col.appendChild(newImg);
newImg.onclick = function() {
alert("WOW");
};
}
A value is passed to newNumCols but not used in the function. The value of picSource comes from the outer execution context and is not changed, so it's still the last image src from the previous for loop.
for (r = 0; r < newNumRows; r++) {
row = newTable.insertRow(-1);
for (c = 0; c < newNumCols; c++) {
col = row.insertCell(-1);
addNewImage(newNumCols);
}
}
This loop just keeps calling addNewImage with a single parameter that isn't used in the function, so you get the same image over and over.
For the record, the addNewImage function does have a closure to picSource, but it also has a closure to all the variables of the outer execution contexts. This isn't the issue, though it perhaps masks the fact that you aren't setting a value for picSource on each call, so you get the left over value from the previous section of code.
You haven't provided any indication of the content of showme, so it's impossible to determine if this approach will work at all.
Note
Where you have:
var showme = localStorage.getItem(name);
alert("I got the table");
var newTable = document.createElement('table');
newTable.innerHTML = showme;
newTable.id = "newTable";
IE does not support setting the innerHTML property of table elements, though you can create an entire table as the innerHTML of some other element and set the innerHTML of a cell (tr, th). If you want to use this approach, consider:
var div = document.createElement('div');
div.innerHTML = '<table id="newTable">' + showme + '<\/table>';
var newTable = div.firstChild;

Setting a the background image of a div from an array

I have to make a div and set the background image from an array of images, and make a two buttons that will change the picture to the next image in the array, or the previous image of the array. I've been looking around stackoverflow and w3 schools, but I don't know why it's not working.
var backgroundImage = new Array();
backgroundImage[0] = "np.jpg";
backgroundImage[1] = "putin.png";
backgroundImage[2] = "fob.jpg";
function nextImage()
var img = document.getElementById(element);
for(var i = 0; i < backgroundImage.length;i++)
for(var i = 0; i < backgroundImage.length;i++) {
document.getElementById(element).src = [0].src;
document.style.backgroundImage="url(backgroundImage[0])";
}
You are not evaluating the array, you are creating a literal you want
document.style.backgroundImage="url(" + backgroundImage[0] + ")";

Categories

Resources