Problem with "document.write()" an Image Array in JavaScript - javascript

Am trying to write using document.write() an image at the time from my array. However it does not display any...
// *** Temporal variables
var i = 0;
var j = 0;
var x = 0;
// Create basic linear array
var ImgArray = []
// Do the 2D array for each or the linear array slots
for (i=0; i < 4 ; i++) {
ImgArray[i] = []
}
// Load the images
x = 0;
for(i=0; i < 4 ; i++) {
for(j=0; j < 4 ; j++) {
ImgArray[i][j] = new Image();
ImgArray[i][j] = "Images/" + x + ".jpg";
document.write("<img id= " + x + " img src=ImgArray[i][j] width='120' height='120'/>");
x = x + 1;
}
document.write("<br>");
}
What am I doing wrong?

Looks like your JavaScript isn't quite right...
document.write('<img id="' + x + '" src="' + ImgArray[i][j] + '" width="120" height="120"/>');

It looks like you're trying to do image preloading by using new Image(), but then you immediately write out an image element with the same src using document.write(), so the image will not have preloaded and you get no benefit. I also suspect you're missing a .src on one line in the inner loop:
ImgArray[i][j].src = "Images/" + x + ".jpg";
This looping to create image elements would be best done server-side when generating the HTML, but assuming that's not an option, you could lose the ImgArray variable completely:
x = 0;
for(i=0; i < 4; i++) {
for(j=0; j < 4; j++) {
document.write("<img id='" + x + "' src='Images/" + x + ".jpg' width='120' height='120'>");
x = x + 1;
}
document.write("<br>");
}

document.write writes any input the the location of script element. Try this instead:
in body
<div id="imageContainer"></div>
in your script, gather all output to a variable, say contentVariable, and then
document.getElementById("imageContainer").innerHTML = contentVariable;
note:
It's bad practice to use document.write and even innertml for appending elements to dom. use document.createElement and element.appendChild for dom manupilation.

Related

Dynamic Color-Thief / Get dominant color

I have a very special problem with color-thief. I'm trying to load some data from my datatable containing a realtive path to a image stored on the same domain.
There are about 20 links where I have to grab the dominant color and push it to an array.
My problem is now, that when i load my data (with AJAX) and I try to grab the color, the image is not loaded jet and i get a "Uncaught DOMException: Failed to execute 'getImageData' on 'CanvasRenderingContext2D': The source width is 0."
So here is what i have tried so far:
METHODE 1: GetColor
// Create Objects for colorThief
var colorThief = new ColorThief();
var myImage = new Image();
var colors = [];
for (var i = 0; i < result.length; i += 3) {
labels.push(result[i]);
data.push(result[i + 1]);
myImage.src = result[i + 2];
var color = colorThief.getColor(myImage);
colors.push("#" + rgbToHex(color[0]) + rgbToHex(color[1]) + rgbToHex(color[2]));
}
METHODE 2: GetColorByUrl
// Create Objects for colorThief
var colorThief = new ColorThief();
var colors = [];
for (var i = 0; i < result.length; i += 3) {
labels.push(result[i]);
data.push(result[i + 1]);
//Also tried with a absolute path, not changing anything
var color = colorThief.getColorFromUrl(result[i + 2]);
colors.push("#" + rgbToHex(color[0]) + rgbToHex(color[1]) + rgbToHex(color[2]));
}
METHODE 3: Append Image to HTML
var colorThief = new ColorThief();
var colors = [];
var content = "<div id='temp' style='display:none'>";
//Create options
for (var i = 0; i < result.length; i += 3) {
options += "<option value='" + result[i] + "'>" + result[i + 1] + "</option>";
content += "<img src='" + result[i + 2] + "'>";
}
content += "</div>"
$("#contentRightTop").append(content);
var thisColor;
var theseColors = [];
$("#temp img").each(function () {
thisColor = colorThief.getColor(this);
theseColors.push(thisColor);
});
$("#temp").remove();
METHODE 4: Object.onload
// Create Objects for colorThief
var colorThief = new ColorThief();
var myImage = new Image;
var colors = [];
for (var i = 0; i < result.length; i += 3) {
labels.push(result[i]);
data.push(result[i + 1]);
myImage.onload = function() {
var color = colorThief.getColor(myImage);
colors.push("#" + rgbToHex(color[0]) + rgbToHex(color[1]) + rgbToHex(color[2]));
}
myImage.src = result[i + 2];
}
So how i told you, so far nothing really worked. I also tried to set absolute paths to my domain.
THE ONLY methode that worked, was a try catch, with repeating the whole for loop, what wasn't that nice.
So guys if you would have some ideas/inputs on how to solve this problem or also alternatives to color-thied (it's very heavy) would be great.
Mention, that i allready tried to combine/replace color-thief with this scipts:
ImagesLoaded - Very bugy in Google Chrome
Colorify - Didn't manage to change the script to what i need
[Dominant-Color - Has imagemagick dependencie, that i want to avoid]
[Adaptive Background - Same as Colorify]
[PrimaryColor - I have to give it a try again, think there was an error in my code]
(Only allowed to post 2 links^^)
Thanks so far
Martin

For loop exceeds the limit when using img src

I have an img_urls array which contains 2 image urls.
I use this array to loop img tag and using for loop.
But instead of having 2 images, i have 3 images in my output.
This is my code;
var img_urls = ["http://i.onionstatic.com/avclub/5648/48/16x9/1200.jpg", "https://www.scienceabc.com/wp-content/uploads/2016/05/horse-running.jpg"];
for (i = 0; i < img_urls.length; i++) {
$("div").append(
"<div><img src=' " + img_urls[i] + "'/></div>"
);
}
So, whats is wrong with my code?
JSFIDDLE
When adding the first image you generate a new div.
Then the second image if appended to existing divs.
You should have only one destination div. Add an id to the main div:
<div id="container"></div>
--
var img_urls = ["http://i.onionstatic.com/avclub/5648/48/16x9/1200.jpg", "https://www.scienceabc.com/wp-content/uploads/2016/05/horse-running.jpg"];
for (i = 0; i < img_urls.length; i++) {
$("div#container").append(
"<div><img src=' " + img_urls[i] + "'/></div>"
);
}
You need to use selector i.e. id class in the main div as when the next iteration occurs it contains two div in the body. Check this fiddle
Problem is that you have $("div") as selector. So when you append the first image, you also add new div. So the next image is appended to two divs. Probably you can add id to your div, so
<div id="test"></div>
...
$("#test").append
Reason is you are appending everything inside the loop.
$(function() {
var img_urls = ["url1", "url2"];
var html= ""
for (i = 0; i < img_urls.length; i++) {
html += "<div><img src=' " + img_urls[i] + "'/></div>";
}
$("div").append(html);
});
You are appending to global div element, you are appending div also, so generated html will append to generated div too.
Here is html,
<div class='test'></div>
Here is javascript code,
$(function() {
var img_urls = ["image_url1", "image_url2"];
var html = '';
for (i = 0; i < img_urls.length; i++) {
html += "<div><img src=' " + img_urls[i] + "'/></div>"
}
$("div.test").append(html);
});
Please find here working link here
I hope this will help
<div id="container"></div>
for (var i = 0; i < img_urls.length; i++) {
console.log(img_urls.length)
$("div#container").append(
"<div><img src=' " + img_urls[i] + "'/></div>"
);
}
when you append the first image you create a div in that div the horse is added and the first div is also populated by the horse
Try this and see Demo
<div></div>
$(function() {
var img_urls = ["http://i.onionstatic.com/avclub/5648/48/16x9/1200.jpg", "https://www.scienceabc.com/wp-content/uploads/2016/05/horse-running.jpg"];
for (i = 0; i < img_urls.length; i++) {
$("div").append(
"<img src=' " + img_urls[i] + "'/> </br>"
);
}
});

jquery for loop to create multiple buttons

I need to create a set amount of buttons using jquery. I've tried a for loop and a while loop but this isn't working.
I'm storing the amount of pages I need in a variable 'pages', which when using console.log(pages) correctly shows how many buttons I require yet I still can't get the loop to work.
while (i <= pages) {
pageButtons.append('<input type="button" id="button'+i+'" value="Random'+i+'"/>');
i = i + 1;
}
I currently have the above code..
What is pageButtons assigned to? If you contain all of the buttons in a div, this will work
var pages = 5;
var pageButtons = $('#pageButtons');
for (var i = 0; i < pages; i++) {
pageButtons.append('<input type="button" id="button' + i + '" value="Random' + i + '"/>');
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="pageButtons">
</div>
You would want to do something like this:
var pages = 5;
for (var i = 0; i <= pages; i++) {
$('#buttons').append('<input type="button" id="button' + i + '"value="Random' + i + '"/>');
}
http:////jsfiddle.net/clccmh/x545y8re/

JS - Clicking on thumbnail will display the right image

In javascript only, no librairies, I am trying to create a carousel.
I have 2 items:
One div for the main image and the caption (the images and captions are loaded dynamically one by one after a setTimeOut)
Another one with a list of thumbnails. I'd like to upon clicking on a thumbnail display the right image and caption.
Here is the html:
<div class="slide">
<h2 id="description" class="title">La Slide #0</h2>
<img id="largeImg" class="car" src="images/0.jpg" width="658" height="267" alt="" />
</div>
<ul id="thumbs">
</ul>
and here are my functions:
// Function to display the images and the captions switching from one to the other
function slideshowAuto() {
document.querySelector('div.slide').id = 'slide-' + i;
var caption = document.getElementById("description");
caption.innerHTML = data.slides[i].slide_name;
var img= document.getElementById("largeImg");
img.src = data.slides[i].image_src;
if (i < totalSlides) {
i++;
} else {
i = 0;
}
setTimeout("slideshowAuto()",3000);
}
// Function to display the images and the captions swaping from one to the other
function swapSlide() {
document.querySelector('div.slide').id = 'slide-' + i; // add an id on the current slide
var caption = document.getElementById("description");
caption.innerHTML = data.slides[i].slide_name;
var img = document.getElementById("largeImg");
img.src = data.slides[i].image_src;
if (i < totalSlides) {
i++;
} else {
i = 0;
}
setTimeout("swapSlide()",50);
}
// Function to display all the thumbnails
function displayAllThumbs() {
thumbs = document.getElementById('thumbs');
html = '';
for( i=0 ; i < totalSlides; i++) {
html += '<li><a onclick="swapSlide(slide-' + i + ')"><img src="' + data.slides[i].thumbnail_src + '" alt="' + data.slides[i].slide_name + '" title="' + data.slides[i].slide_name + '" /></a></li>';
}
thumbs.innerHTML = html;
}
My troubles:
The slide content display the last variables instead of the first one.
The clic on the thumbnails don't swap the "slide" content.
Here is a link of where I'm at...
Anyone can help me with that?
First,you used the global i which is changed to 7 by function preload and rechanged by function displayAllThumbs,So you got trouble 1.
Scond,you click function is swapSlide(slide-' + i + '),the parameter is a variable that doesn't exsits,also your swapSlide doesn't accept parameter.
Change to this will solve your problem:
function preload(images) {
if (document.images) {
var imageArray = data.slides[i].image_src;
var imageObjs = [];
var imageObj = new Image();
for(var j=0; j <= totalSlides - 1;j ++) {
imageObj.src = imageArray[j];
imageObjs.push(imageObj);
}
}
}
// Function to display the images and the captions switching from one to the other
function slideshowAuto() {
setSlide(i);
if (i < totalSlides) {
i++;
} else {
i = 0;
}
//document.getElementById('slide').style.webkitTransition = 'opacity 1s';
setTimeout("slideshowAuto()",3000);
}
// Function to display the images and the captions swaping from one to the other
function swapSlide(index) {
i=index; //change the current i
setSlide(index);
}
// Function to display all the thumbnails
function displayAllThumbs() {
thumbs = document.getElementById('thumbs');
html = '';
for( var k=0 ; k < totalSlides; k++) {
html += '<li><a onclick="swapSlide(' + k + ')"><img src="' + data.slides[k].thumbnail_src + '" alt="' + data.slides[k].slide_name + '" title="' + data.slides[k].slide_name + '" /></a></li>';
}
thumbs.innerHTML = html;
}
function setSlide(index){
document.querySelector('div.slide').id = 'slide-' +index; // add an id on the current slide
var caption = document.getElementById("description");
caption.innerHTML = data.slides[index].slide_name;
var img = document.getElementById("largeImg");
img.src = data.slides[index].image_src;
}
And can i get accepted?
I add a new function to avoid the repeat.

Changing the content of all <pre> tags using JavaScript

I want to know how I change all the pre tags inside a document...
I'm using this:
var preContent = document.getElementById('code').innerHTML;
but this only changes the content of 1 pre tag... the one with the ID 'code'.
If you can show me how i can change all the pre tags using JavaScript I appreciate
Here's all the code:
window.onload = function () {
var preContent = document.getElementById('code').innerHTML;
var codeLine = new Array();
var newContent = '<table width="100%" border="1" '
+ 'cellpadding="0" cellspacing="0" >';
codeLine = preContent.split('\n');
for (var i = 0; i < codeLine.length; i++) {
newContent = newContent + '<tr><td class="codeTab1" >'
+ i.toString() + '</td><td class="codeTab2">'
+ codeLine[i] + '</td></tr>';
}
newContent = newContent + '</table>';
document.getElementById('code').innerHTML = newContent;
}
PS: This is to make a look like a normal compiler with numbers before the line
PPS: Each pre tag will have a different content and I want the same script to change it (if possible).
You can use getElementsByTagName:
var preElements = document.getElementsByTagName('pre');
for(var i = 0; i < preElements.length; ++ i)
{
var element = preElements[i];
/* modify element.innerHTML here */
}
First problem in you code . No two elements in a document can have same id .
So you can change it easily with jquery . look at the code .
$('pre').html("what ever text you want to show ");
Or with javascript you can do like this :
var x = document.getElementsByTagName('pre');
for(var i = 0; i < x.length; ++ i)
{
x.innerHTML = "what ever text you want to show";
}

Categories