"Cannot read property 'length' of undefined" when calling function - javascript

I get the following error when I click my refresh button:
caught TypeError: Cannot read property 'length' of undefined
at getRandomImage (index.html:85)
at HTMLInputElement.onclick (index.html:11)
See this snippet:
var myArray = new Array();
getRandomImage(myArray, "");
function getRandomImage(imgAr, path) {
path = path || 'C:/Users/Owen/Desktop/1-800MemeLine-master/memes/'; // default path here
var num = Math.floor( Math.random() * imgAr.length );
var img = imgAr[ num ];
var imgStr = '<img src="' + path + img + '" alt = "">';
document.write(imgStr); document.close();
}
<form>
<INPUT TYPE="button" onClick="getRandomImage()" VALUE="More MEME plz">
</INPUT>
</form>
It works fine with the button refreshing the page but most of the people on my website have bad internet which takes a long time to reload the page so only loading the image and not the background and text and unnecessary things.
Link to github REPO: https://github.com/odude102/1-800MemeLine/blob/master/index.html

This is not the best solution, but it fixes your problem:
var myArray = new Array();
var path = 'C:/Users/Owen/Desktop/1-800MemeLine-master/memes/';
getRandomImage();
function getRandomImage() {
var num = Math.floor( Math.random() * myArray.length );
var img = myArray[ num ];
var imgStr = '<img src="' + path + img + '" alt = "">';
document.write(imgStr);
document.close();
}

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

how to make javascript random image with hyperlink with array

i want to make random image with link, but i didnt understand. anyone can help me?
this is the javascript in header
<script type="text/javascript">
var random_images_array = ['banner/headline/chrome.png','banner/headline/thunderbird.png','banner/headline/vlc.png'];
function getRandomImage(imgAr, path) {
path = path || 'images/';
var num = Math.floor( Math.random() * imgAr.length );
var img = imgAr[ num ];
var lnk = imgAr[ num ];
var imgStr = '<img src="' + path + img + '" alt="" class="img-responsive">';
document.write(imgStr); document.close();
}
</script>
this is the javascript in body
<script type="text/javascript">
getRandomImage(random_images_array, 'images/')
</script>

Read GET value on JavaScript src attribute using JavaScript

I am using this code and my file name is ads.js
function getUrlVars() {
var vars = {};
var parts = window.location.href.replace(/[?&]+([^=&]+)=([^&]*?)[#.]/gi, function(m, key, value) {
vars[key] = value;
});
return vars;
}
var pic = getUrlVars()["pic"];
var random_ads_array = ["visitors.jpg", "payouts.jpg", "logos-icon.jpg"];
function getRandomAds(imgAr, path) {
path = path || 'buycimg/'; // default path here
var num = Math.floor(Math.random() * imgAr.length);
var img = imgAr[num];
var imgStr = '<img src="' + path + img + '" alt = "">';
document.write(imgStr);
document.close();
}
And in html part I am using this code
<script type="text/javascript" src="ads.js?pic=45bus67"></script>
<script type="text/javascript">getRandomAds(random_ads_array);</script>
Out put is showing an image but not showing the correct link
Output is like this
http://appricart.com/undefined.html
I want to show
http://appricart.com/45bus67.html
Help related this thankx
Why don't you just put the pic value into the function?
<script type="text/javascript" src="ads.js"></script>
<script type="text/javascript">getRandomAds(random_ads_array, "45bus67");</script>
ads.js
var random_ads_array = ["visitors.jpg", "payouts.jpg", "logos-icon.jpg"];
function getRandomAds(imgAr, pic, path) {
path = path || 'buycimg/'; // default path here
var num = Math.floor( Math.random() * imgAr.length );
var img = imgAr[ num ];
var imgStr = '<img src="' + path + img + '" alt = "">';
document.write(imgStr); document.close();
}
Perhaps you could give it an ID - and then:
src = document.getElementById("scriptId").getAttribute("src");
src = src.split("?pic=");
src = src[1];
And voila! You can do what you need to do with src

Javascript (onclick) pop up bigger image window from image array

I have an array of images that populate the page and what I am having trouble with is coming up with a way to create an ONCLICK popup image window from the thumbnails (but the popup window needs to be a bigger size image):
here is the js code:
var str = "<table>";
var imgFolder = "images/";
var cover = new Array();
cover[0] = "kitchenHouseSale.jpg";
cover[1] = "eatLive.jpg";
cover[2] = "loveAnthonySale.jpg";
var coverone = new Array();
coverone[0] = "casualVacancy.jpg";
coverone[1] = "quiet.jpg";
coverone[2] = "whirlAway.jpg";
var covertwo = new Array();
covertwo[0] = "everyLastSale.jpg";
covertwo[1] = "neilYoung.jpg";
covertwo[2] = "soupSisters.jpg";
var title = new Array();
title[0] = "The Kitchen House";
title[1] = "Eat to Live";
title[2] = "Love Anthony";
for (var i = 0; i < cover.length; i++)
{
str += "<tr><td colspan='2'><h2>" + category[i] + "</h2></td></tr>";
str += "<tr><td class='basket'><img src='" + imgFolder + cover[i] + "' width='108' height='159'>
}
str += "</table>";
var elem = document.getElementById("table");
elem.innerHTML = str;
Any help is appreciated. Thanks!
Do i get you right? You want the user to click on an image and a bigger version of the same image is supposed to appear in a popup-window?
Have a look at window.open() then: http://w3schools.com/jsref/met_win_open.asp
You must specify the absolute path of the image - file as the url for the popup, like http://your.domain.com/images/kitchenHouseSale.jpg.
you can then add an onclick-handler to the img-tag, something like this:
<img src='" + imgFolder + cover[i] + "' width='108' height='159' onclick="window.open('http://your.domain.com + this.src)" />

Javascript - onclick

first time posting here, but god know's I use this site to search for problems all the time :P Well, I'm having a problem of my own now that I can't seem to figure out easily searching around Google, and after playing with it for about 2 hours, I've finally decided to post a question and see what you guys think.
What I'm trying to accomplish here is to have a button that appears over a div when you hover over it that, when clicked, opens an editing pane. The button appears over the div correctly, but for some reason I cannot seem to make the onclick function work to save my life lol. Here's the code I'm working with. If it's not enough, please let me know and I'll add a little more sauce. :P
function place_widget(name, properties){
//bbox
var pleft = properties[0];
var ptop = properties[1];
var width = properties[2];
var height = properties[3];
var pright = pleft + width;
var pbottom = pleft + height;
var bbox = [pleft, ptop, pright, pbottom];
boxes[name] = bbox;
//ID's
var id = 'widget_' + name;
var editspanid = id + "_editspan";
var editbuttonid = id + "_editbutton";
var editpaneid = id + "_editpane";
//Creating Elements
var div = "<div id='" + id + "' class='widget' onmouseover='widget_hover(event);' onmouseout='widget_out(event);'>";
var editbutton = "<a id='" + editbuttonid + "' href='#'><img onclick='toggleEdit;' src='../images/edit_button.png'></a>";
var editspan = "<span id='" + editspanid + "' class='editspan'>" + editbutton + "</span>";
var editpane = "<span id='" + editpaneid + "' class='editpane'>:)</span>";
div += editspan + editpane + "</div>";
body.innerHTML += div;
//Configuring Elements
var editspanelement = document.getElementById(editspanid);
var editbuttonelement = document.getElementById(editbuttonid);
editbuttonelement.onclick = alert; //Does nothing.
var editpaneelement = document.getElementById(editpaneid);
var mainelement = document.getElementById('widget_' + name);
mainelement.style.left = (pleft + leftmost) + "px";
mainelement.style.top = (ptop + topmost) + "px";
mainelement.style.width = width;
mainelement.style.height = height;
getContentsAJAX(name);
}
Sorry for the ugly code :P Anyone have any idea why the onclick function isn't working?
Also, a bit of extra info: If I open up firebug and put in :
document.getElementById('widget_Text_01_editbutton').onclick = alert;
When I click the button, I get:
uncaught exception: [Exception... "Illegal operation on WrappedNative prototype object" nsresult: "0x8057000c (NS_ERROR_XPC_BAD_OP_ON_WN_PROTO)" location: "native frame :: <unknown filename> :: <TOP_LEVEL> :: line 0" data: no]
I'm not exactly sure what that means off hand.
Thanks!
Can you try changing:
<img onclick='toggleEdit;' src='../images/edit_button.png'>
to:
<img onclick='toggleEdit();' src='../images/edit_button.png'>
Also, is "alert" a function you wrote?
Start by changing this:
editbuttonelement.onclick = alert; //Does nothing.
to this:
editbuttonelement.onclick = function() {alert("Got a click");};
and then change this:
var editbutton = "<a id='" + editbuttonid + "' href='#'><img onclick='toggleEdit;' src='../images/edit_button.png'></a>";
to this:
var editbutton = "<a id='" + editbuttonid + "' href='#'><img onclick='toggleEdit();' src='../images/edit_button.png'></a>";
What you are clicking on? The image or the link or the span? Do you know which is getting the click event?
document.getElementById('widget_Text_01_editbutton').onclick = alert;
causes illegal invocation because it is trying to set this to something else (the element) than window inside alert.
alert.call( {} )
//TypeError: Illegal invocation
alert.bind( window ).call( {} )
//works
So either:
document.getElementById('widget_Text_01_editbutton').onclick = alert.bind( window );
or even better as the above will only work in some browsers:
document.getElementById('widget_Text_01_editbutton').onclick = function(){alert();};
It will help you in executing.
<img onclick='toggleEdit;' src='../images/edit_button.png'>

Categories