I have searched for a solution to this problem but couldn't find anything specific. I am writing a javascript memory card game using a deck of cards thats i have individual images for. In the html table thats printed I have an img with an onlick event that calls my selectCard() function. this function takes the argument (img id) and uses that id to change the img src from back.gif to the corresponding front card (as stored in an array called preloadImages)
My problem is that when this happens the image src becomes [object%20HTMLImageElement].png instead of 0.png or 23.png or whichever card was clicked.
Can someone please help? Codeblock below
//sets up the table for the game
function setGame(){
document.getElementById("gameArea").innerHTML = "";
var newTable = "<table border ='1' align='center'><tr>";
for(i=0; i<4; i++){
newTable +="<tr>";
for(j=0; j<13; j++){
var cardId = j+i*13;
newTable += "<td><img id = "+cardId+" src='back.gif' width='100' height='140' onclick='selectCard("+cardId+")'/></td>";
}
newTable += "</tr>";
}
newTable += "</table>";
document.getElementById("gameArea").innerHTML = newTable;
}
//selectCard Function
function selectCard(Id){
var imageRef = document.getElementById(Id);
if (imageRef.src.match("back.gif")) {
imageRef.src = preloadImages[imageRef]+'.png';
}
else {
imageRef.src = "back.gif";
}
}
I'm pretty sure [object%20HTMLImageElement] is an HTML element, not the ID of an image. If I understand what you are trying to do correctly, you are taking the ID of the image and adding the extension ".png" to the end of it before setting the src of the image to that value. Whatever you are doing in your code is changing the src of imageRef to imageRef itself, not it's ID. Try this:
function selectCard(Id){
var imageRef = document.getElementById(Id);
if (imageRef.src == "back.gif") {
imageRef.src = Id + ".png";
} else {
imageRef.src = "back.gif";
}
}
I was able to resolve this by using the following code line
imageRef.src = preloadImages[Id].src;
Related
I have thumbnail previews of a users selected images prior to upload. It will also allow a user to re-arrange the order of the images using jQuery UI. I want to track the order of the images by adding a unique ID to each thumbnails containing div, but I am not able to generate a unique ID. See Code below. Ideally I would like the div ID to match the image name, so then after the form post I use it to match to the filename in the IEnumerable<HttpPostedFileBase>. For example, if the uploaded image is called pic1.jpg, the div containing the thumbnail would be <div id = "pic1">. The line in question would seem to be div.id = File.name, but I am unable to generate a unique ID of any kind?
CODE
//jQuery UI sort
$(function () {
$("#upload-thumbnails").sortable();
$("#upload-thumbnails").disableSelection();
});
//Thumbnail preview
jQuery(function ($) {
var filesInput = document.getElementById("ImageUploads");
filesInput.addEventListener("change", function (event) {
var files = event.target.files; //FileList object
var output = document.getElementById("upload-thumbnails");
for (var i = 0; i < files.length; i++) {
var file = files[i];
var picReader = new FileReader();
picReader.addEventListener("load", function (event) {
var picFile = event.target;
var div = document.createElement("div");
div.id = File.name;
div.innerHTML = "<img class='thumbnail' src='" + picFile.result + "'" +
"title='" + picFile.name + "'/><a href='#' class='remove_pict'>Remove</a>";
output.insertBefore(div, null);
div.children[1].addEventListener("click", function (event) {
div.parentNode.removeChild(div);
});
});
//Read the image
picReader.readAsDataURL(file);
}
});
});
In most cases while we uploading images we rename them as the time stamp because of the uniqueness. But for searching, dealing with time stamp is much harder, then add a class name of the div as the file name.
...
var div = document.createElement("div");
div.id = Date.now();
div.className += ' ' + File.name;
...
I am sure this will be help full.
Thanks
Not sure I get the question :)
Try instead:
$(div).attr('id', 'yourIDHere')
Or you never use your defined var file , could it not be?
div.id = file.name;
You can generate UUIDs via JS see here
The code below gets info from xml file.
I succesfully presents the id and name of each planet with a button.
I want to add an onclick event on the button.
Problem now is: it does add the onclick event but only on the last button created in the loop.
What am i doing wrong? Why doesnt it create a onclick event for each button, but only for the last one in loop?
function updatePlaneten() {
var valDiv, planets, valButton, textNode;
// Get xml files
planets = this.responseXML.getElementsByTagName("planeet");
// loop through the <planet> tags
for (var i = 0; i < planets.length; i++) {
valDiv = ''; // clear valDiv each time loop starts
// Get the id and the name from the xml info in current <planet> tag
valDiv += planets[i].getElementsByTagName("id")[0].childNodes[0].nodeValue + "<br>";
valDiv += planets[i].getElementsByTagName("name")[0].childNodes[0].nodeValue + "<br>";
document.getElementById("planetenID").innerHTML += valDiv + "<br>";
// Create button with a value and pass in this object for later reference use (valButton.object=this)
valButton = document.createElement("input");
// valButton.setAttribute("planeetID", planets[i].getElementsByTagName("id")[0].childNodes[0].nodeValue);
valButton.setAttribute("value", 'Meer info');
valButton.setAttribute("type", 'button');
valButton.id = (i + 1);
valButton.object = this;
//
// Here is the problem i cant get fixed
//
//valButton.onclick = function(){ showinfo(); }
valButton.addEventListener('click', showinfo);
// Place the button on screen
document.getElementById("planetenID").appendChild(valButton);
}
}
// simple function to check if it works
function showinfo() {
console.log(this.object);
console.log(this.id);
}
The trouble is this line:
document.getElementById("planetenID").innerHTML += valDiv + "<br>";
When you set innerHTML the content currently in there gets destroyed and replaced with the new html, meaning all your old buttons are now destroyed and new ones are created. The previously attached event listeners do not get attached to the new buttons.
Instead simply create a div/span or whatever container would best help, add your planet text or whatever to it and then use appendChild
valDiv = document.createElement("div");
var id = planets[i].getElementsByTagName("id")[0].childNodes[0].nodeValue;
var name = planets[i].getElementsByTagName("name")[0].childNodes[0].nodeValue;
valDiv.innerHTML = id+"<br>"+name+"<br>";
document.getElementById("planetenID").appendChild(valDiv);
You could also use insertAdjacentHTML
var id = planets[i].getElementsByTagName("id")[0].childNodes[0].nodeValue;
var name = planets[i].getElementsByTagName("name")[0].childNodes[0].nodeValue;
valDiv = id+"<br>"+name+"<br>";
document.getElementById("planetenID").insertAdjacentHTML("beforeend",valDiv);
function updatePlaneten() {
var valDiv, planets, valButton, textNode;
// Get xml files
planets = this.responseXML.getElementsByTagName("planeet");
// loop through the <planet> tags
for (var i = 0; i < planets.length; i++) {
(function(num){
valDiv = document.createElement("div");
// Get the id and the name from the xml info in current <planet> tag
var id = planets[num].getElementsByTagName("id")[0].childNodes[0].nodeValue + "<br>";
var name = planets[num].getElementsByTagName("name")[0].childNodes[0].nodeValue + "<br>";
valDiv.innerHTML = id+"<br>"+name+"<br>";
document.getElementById("planetenID").appendChild(valDiv);
// Create button with a value and pass in this object for later reference use (valButton.object=this)
valButton = document.createElement("input");
// valButton.setAttribute("planeetID", planets[i].getElementsByTagName("id")[0].childNodes[0].nodeValue);
valButton.setAttribute("value", 'Meer info');
valButton.setAttribute("type", 'button');
valButton.id = (num + 1);
valButton.object = this;
// FIX: PASS showinfo TO AN ANONYMOUS FUNCTION CONTAINING THE OBJECT
valButton.addEventListener('click', function(){
showinfo(valButton);
});
// Place the button on screen
document.getElementById("planetenID").appendChild(valButton);
}(i));
}
}
// simple function to check if it works
function showinfo(valButton) {
console.log(valButton.object);
console.log(valButton.id);
}
JS only. On mouseover I'm calling a function I made that creates a div element with an image inside.
I pass (this) as a parameter to the function. The function works and onmouseover it creates a child element and I can click it. However, If I add on mouse out of the div to remove itself, it will only do so if I hovered over it. If I didn't, the div stays and on next hover it adds another one. If I add on mouse out of the parent element to remove the div, I cannot get to hover over the child div, cause as soon as I leave the parent, the child div is removed. The parent element is an (a href) inside a "TD" in a table. The code goes like this:
<script type="text/javascript">
function PopPanel(ownerElem) {
var myParent = ownerElem.parentNode;
var popanel = document.createElement("div");
popanel.className = "divPopPanel";
popanel.setAttribute("display", "block")
var phoneimg = document.createElement("img");
phoneimg.src = '/images/ImageAdditions/Phone.png';
phoneimg.className = "popupPhone";
popanel.appendChild(phoneimg);
phoneimg.onclick = function () {
try {
location.replace("Mylauncher:\\\\nas\\vol5\\SYSTEM\\ITR\\Scripts\\SomeProgram.exe" + " " + ownerElem.innerText);
}
catch (err) {
}
};
myParent.appendChild(popanel);
popanel.onmouseout = function (e) { this.parentNode.removeChild(this) }; //this removes itself on mouseout.
myParent.onmouseout = function (e) { popanel.parentNode.removeChild(popanel) }; // this removes the child element of the parent (which is the same element as above) on mouse out.
};
Well, after a long and miserable trial and error session, I've figured this out.
First I've modified the code that generates and populates the gridview with data, like this:
VB.net
dt.Columns.Add("InternalPhoneDialer", Type.GetType("System.String"))
Dim rn As New Random
Dim randNum As Integer = rn.Next(12, 428)
Dim internalphone As String = dr("InternalPhone").ToString
If internalphone.Contains(" ") Then
internalphone = internalphone.Substring(0, internalphone.IndexOf(" "))
internalphone = internalphone & randNum.ToString()
Else
internalphone = internalphone & randNum.ToString()
End If
//Substitute the current column with the newly created one above
dr("InternalPhoneDialer") = "<div id='popPanelWrapper" & internalphone & "' onmouseover='PopPanel(" & "popPanelWrapper" & internalphone & ");' onmouseleave='PopPanelClose(" & "popPanelWrapper" & internalphone & ");'> <a class='popPanelLink' href='javascript:void(0);' >" & dr("InternalPhone") & "</a> </div>"
I have made sure that I concatenate a unique id to each div in case the phone number is the same for another column (where I implement the same solution). So I added the column inner content + a random number and concatenated it to the DIV name.
Then, on client side I've modified my script like this:
JavaScript
<script type="text/javascript">
function PopPanel(ownerElem) {
var myParent = ownerElem;
var phoneimgexist = !!document.getElementById("popupPhone");
if (phoneimgexist) {
return
} else {
var phoneimg = document.createElement("img");
phoneimg.src = '/_layouts/15/images/ImageAdditions/Phone.png';
phoneimg.id = "popupPhone";
phoneimg.setAttribute("display", "block")
myParent.appendChild(phoneimg);
}
phoneimg.onclick = function () {
try {
location.replace("launcher:\\\\drive01\\vol1\\SYSTEM\\ITR\\Scripts\\Jabber.exe" + " " + ownerElem.innerText);
}
catch (err) {
}
};
};
function PopPanelClose(ownerElem) {
var myParent = ownerElem;
var phoneimg = document.getElementById("popupPhone");
var phoneimgexist = !!document.getElementById("popupPhone");
if (phoneimgexist) {
phoneimg.parentNode.removeChild(phoneimg);
} else {
return
}
};
Now, on mouse over a GridVew cell that contains a phone number I get an icon. By clicking it I can call the number.
In my opinion this solution is much better suited for the task, instead of creating a hidden div with image and data for every row in what could be thousands of entries in the GridView.
This no doubt saves a lot of resources.
I got a litlle js code that is showing me updates from a feed
google.load("feeds", "1");
function initialize() {
var feed = new google.feeds.Feed("http://google.com/");
feed.setNumEntries(1);
var count = 1;
feed.load(function(result) {
if (!result.error) {
var container = document.getElementById("feed");
var html = "";
for (var i = 0; i < result.feed.entries.length; i++) {
var entry = result.feed.entries[i];
html = "<h5>" + count++ + ". <a href='" + entry.link + "'>" + entry.title + "</a></h5>";
var div = document.createElement("div");
div.innerHTML = html;
container.appendChild(div);
}
document.write(html);
}
});
}
google.setOnLoadCallback(initialize);
What i want to do is to show the first image from the posts from the feed. i would also like to have the title so entry.title and entry.content
Even though parsing html with regx is big dodo, I will still advise you this, parse your content html with /<img\s+src\s*=\s*(["'][^"']+["']|[^>]+)>/
Or a lazy way is to have a hidden div and do this
var temp = document.createElement( 'div' );
temp.innerHTML = html_str;
var images = temp.getElementsByTagName( 'img' );
First, you must use entry.content instead of entry.title in order to get the full HTML content of the entry. You may have something like this:
var content = entry.content;
var imgArray = content.match( /<img\s+src\s*=\s*(["'][^"']+["']|[^>]+)>/ );
// imgArray[0] would contain the first image (more likely the one that better describe the post)
P.S.: I didn't steal this Regex from actual answer, but it seems that we've got to the same reference for it :-)
UPDATE:
Then, to display it in a container, I would advise you to dynamically create DOM elements to gain more control over it, and in which you will be able to easily associate a value. Something like this:
var dom_h5 = document.createElement('h5');
var dom_entryTitle = document.createElement('div');
dom_entryTitle.className = 'title-classname';
dom_entryTitle.innerHTML = entry.title;
dom_h5.appendChild(dom_entryTitle);
container.appendChild(dom_h5);
To simplify the image part, you could create a separate div and inject the image tag as his innerHTML.
This may help you:
Web API Reference - document.createElement
I want to add Rows to a Table that already exists and each row has a onclick attribute. The problem is that each row needs to call the function with another parameter. At The moment no matter in what row i click the function is called with the parameter of the last row in the table.
This is how i add the rows to the table :
table = document.getElementById('ProgramTable');
table.style.visibility = "visible";
tableBody = document.getElementById('ProgrammTableBody');
tablelength = jsonObj0.data.map.programs.length;
// Check if there is already a Table, if so
// remove the Table
if (tableexists) {
removetable();
}
for ( var i = 0; i < tablelength; i++) {
channel = jsonObj0.data.map.programs[i].programServiceName;
frequency = jsonObj0.data.map.programs[i].programIdentifier;
imagelink = "../image/image.jsp?context=tuner&identifier="
+ channel;
var row = document.createElement("tr");
row.setAttribute("id", i);
row.onclick = function() {
tuneProgram(frequency)
};
var channelCell = document.createElement("td");
var imageCell = document.createElement("td");
var imageElement = document.createElement("IMG");
var frequencyCell = document.createElement("td");
channel = document.createTextNode(channel);
frequency = document.createTextNode(frequency);
channelCell.appendChild(channel);
frequencyCell.appendChild(frequency);
imageElement.setAttribute("src", imagelink);
imageElement.setAttribute("width", "40");
imageElement.setAttribute("height", "40"); // TODO OnError
// hinzufügen und evtl
// Css Style für Texte
// siehe Tabellencode
imageCell.appendChild(imageElement);
row.appendChild(channelCell);
row.appendChild(frequencyCell);
row.appendChild(imageCell);
tableBody.appendChild(row);
}
So the tune function should be called with the specific frequency parameter but it seems like he is overwriting the onclick parameter everytime so the last one is in there for every row. But why is that so? is he adding the onclick Attribute to every row in that table? I don't get it.
Thanks for your help!
Replace
row.onclick = function() {
tuneProgram(frequency)
};
with
row.onclick = (function(frequency) {return function() {tuneProgram(frequency);};})(frequency);
This "anchors" the value of frequency by creating a new closure for it.
You need to do something like this:
for (var i = 0; i < tablelength; i++) {
(function(i) {
//your code here
})(i);
}
Frequency is being referenced when you click - so if the variable changes, it changes every click element. For example, the first row sets a frequency of one and the last row sets a frequency of two. When the onclick runs it isn't referenced to a value, its referenced to a variable in the chain and gets the current value of two.
because your frequency is a global value, so there is only one frequency that every function refer to it;you can cache it in a closure
something like this:
var programTable = document.getElementById('ProgramTable');
programTable.style.visibility = "visible";
programmTableBody = document.getElementById('ProgrammTableBody');
tablelength = jsonObj0.data.map.programs.length;
if (tableexists) {
removetable();
}
function newTabRow ( table, name, identifier ) {
var link = "../image/image.jsp?context=tuner&identifier=" + name,
row = table.insertRow();
row.innerHTML = '<td>' + name + '</td><td><img width="40" height="40" src="'+link+'" alt="''" /></td><td>'+ identifier +'</td>';
row.onclick = function ( ) {
tuneProgram ( identifier );
}
}
for (var i = tablelength; i-- > 0; ) {
program = jsonObj0.data.map.programs[i];
newTabRow ( programTable, program.programServiceName, program.programIdentifier );
}
Be careful I have a function on top of my page with name "show_field_setting". my function get to value and do something. I have a for loop and in my loop i change 'type' and 'id' for each element. you can see one part inside of my for loop below. finally I add my new element to my div with element id 'my_element_id'. If you want to set a function to your created element you need use something like this:
var new_child = document.createElement('div');new_child.id = id;
new_child.href = "javascript:;";
new_child.onclick = (function (type, id) {
return function() {
show_field_setting (type, id);
};
})(type, id);
document.getElementById('my_element_id').appendChild(new_child);
if you have on argumant in your function only, use this:
var new_child = document.createElement('div');
new_child.href = "javascript:;";
new_child.onclick = (function (your_value) {
return function() {
your_function_name (your_value);
};
})(your_value);
document.getElementById('your_element_id').appendChild(new_child);
finally i don't know why. any way if you are not in loop condition like "while", "for" or even "switch" you can use easy below code line:
var new_child = document.createElement('div');
new_child.href = "javascript:;";
new_child.onclick = function(){your_function_name (your_value_1, your_value_2 , ...)};
document.getElementById('your_element_id').appendChild(new_child);
Have Fun ;) :)