Add unique ID to containing div of file input thumbnail image - javascript

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

Related

Cannot create multiple list items in javascript

I have the following array:
["uploads-1462948491987.png", "uploads-1462948492004.png"]
What I want to achieve is have an unordered list of anchors (inside list items) with image names. I have done the following:
var uploadsList = document.querySelector('ul'),
imageitem = document.createElement('li'),
anchorTag = document.createElement('a');
anchorTag.setAttribute('href',"#");
var imagesNamesString = "<%= uploads %>";
var imageNames = imagesNamesString.split(',');
imageNames.forEach(function(image) {
anchorTag.innerHTML = image;
uploadsList.appendChild(imageitem.appendChild(anchorTag));
});
console.log(imageNames);
Problem is, the last image is the only one which appears on the list, what may be causing this? Thanks in advance.
Cannot create multiple list items in javascript
Because you're not creating multiple list items. You're creating one:
imageitem = document.createElement('li')
...and then using it:
uploadsList.appendChild(imageitem.appendChild(anchorTag));
where first you append anchorTag to the li, then immediately move it to the uploadsList (because appendChild returns the node appended, not the node you called it on). The same for the anchor, you're reusing one, not creating one for each image.
You need to create the li and anchor in the loop, and append the li, not the anchor:
imageNames.forEach(function(image) {
var li = document.createElement('li');
var anchor = document.createElement('a');
anchor.href = "#"; // No need for `setAttribute
anchor.appendChild(document.createTextNode(image));
li.appendChild(anchor);
uploadsList.appendChild(li);
});
var imageNames = ["uploads-1462948491987.png", "uploads-1462948492004.png"];
var uploadsList = document.querySelector('ul');
imageNames.forEach(function(image) {
var li = document.createElement('li');
var anchor = document.createElement('a');
anchor.href = "#"; // No need for `setAttribute
anchor.appendChild(document.createTextNode(image));
li.appendChild(anchor);
uploadsList.appendChild(li);
});
document.body.appendChild(uploadsList);
<ul></ul>
Note that I replaced the use of innerHTML with:
anchor.appendChild(document.createTextNode(image));
You probably don't want to interpret the image names as HTML. But if you do, just change it back to:
anchor.innerHTML = image;
Or at that point, really, just
imageNames.forEach(function(image) {
var li = document.createElement('li');
li.innerHTML = "<a href='#'>" + image + "</a>";
uploadsList.appendChild(li);
});
var imageNames = ["uploads-1462948491987.png", "uploads-1462948492004.png"];
var uploadsList = document.querySelector('ul');
imageNames.forEach(function(image) {
var li = document.createElement('li');
li.innerHTML = "<a href='#'>" + image + "</a>";
uploadsList.appendChild(li);
});
document.body.appendChild(uploadsList);
<ul></ul>
But I recommend not treating the image names as HTML (unless you actually put HTML in them).
Note that I changed the name anchorTag to anchor. An element is not a tag. A tag is how we define elements textually in HTML. <a> and </a> are tags (a start tag and an end tag, respectively); a is an element.

Img src argument in function. not displaying image

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;

Replacing an image with another in jquery using classes and IDs

I understand that this question has been answered before, but even after consulting those links, I am still unable to solve my problem. I want to replace my image (assets/img/social-mail.jpg) to another (assets/img/social-mail-hover.jpg), with a single class, because I have multiple images I would like to do this to. My basic thought process is this: When the class is hovered, take the ID, and replace its image with another by adding "-hover" to its image link.
HTML:
<img id="social-mail" class="box-social" src="assets/img/social-mail.jpg">
JS:
$(".box-social").hover(function(e) {
var id = $(this).attr("id");
var icon = id.split("-")[1];
var image = "img/social-" + icon + "-hover.jpg";
$(id).find("img").attr("src", image);
});
I've tested id, icon, and image; and they all give me exactly what I want. However, when I hover over the image, it still isn't being replaced. I'm not getting any errors either. What am I doing wrong? Thank you so much!
I think there are at least four problems with your function:
To select by element id you need the # prefix, so $("#" + id) not $(id).
You don't want .find() because this is already the image in question.
Your image path in the html begins with "assets" but you don't include that in your Javascript.
If you only supply one funtion to .hover() that function will be called both when the mouse moves in and when it moves out. So you never change the image back.
The four lines of your function can be replaced with one line:
$(".box-social").hover(function(e) {
this.src = "assets/img/" + this.id + "-hover.jpg";
});
This fixes problems 1-3 above. To fix problem 4 just supply a second function to change the src back when the mouse leaves:
$(".box-social").hover(function(e) {
this.src = "assets/img/" + this.id + "-hover.jpg";
}, function(e) {
this.src = "assets/img/" + this.id + ".jpg";
});
You need to correct your selector.
JS:
$(".box-social").hover(function (e) {
var id = $(this).attr("id");
var icon = id.split("-")[1];
var image = "assets/img/social-" + icon + "-hover.jpg"; //make sure the path is correct
$('#' + id).attr("src", image); //Changed the selector.
});
Demo:http://jsfiddle.net/GCu2D/521/
try this
$(".box-social").hover(function(e) {
var id = $(this).attr("id");
var icon = id.split("-")[1];
var image = "assets/img/social-" + icon + "-hover.jpg";
$("#"+id).attr("src", image);
});
you forgot "assets/" in your image link and your img selector is not corresct

HTML elements created by the content script are not accessible by the content script

Within content script I use on.Message.addListener to add images with a class name to the currently active web page.
chrome.extension.onMessage.addListener(function (message, sender, sendResponse) {
// Selecting HTML tags
var divs = document.getElementsByTagName("div");
// Creating a full URL to use icon1
var imageUrl = chrome.extension.getURL("icons/icon1.png");
// Function to create an image
function PlaceImage(source_x, source_y, imageUrl) {
var newImage = document.createElement("img");
newImage.src = imageUrl;
newImage.style.position = "absolute";
newImage.style.left = source_x + 'px';
newImage.style.top = source_y + 'px';
// Assigning a class name
newImage.className = "label-key";
// Add an element to the HTML document
document.body.appendChild(newImage);
}
// Divs
for(var j=0; j<divs.length; j++) {
// Get the position of an element with getBoundingClientRect
var position = divs[j].getBoundingClientRect();
var x = position.left;
var y = position.top;
y -=32;
// Create comment image
PlaceImage(x, y, imageUrl);
}
});
Later I try to write to console by clicking on one of just created images by:
$(".label-key").click(function () {
console.log("hello");
});
There is no reaction of the browser.
I tried to write to console by accessing some class element with a different name, which was part of the original web page(received from the server). It worked fine.
More over I created another element within content script, but this time outside of onMessage.AddListener:
var newDiv = document.createElement("div");
document.body.appendChild(newDiv);
newDiv.style.width = "100px";
newDiv.style.height = "100px";
newDiv.style.backgroundColor = "red";
newDiv.className = "label-key";
It also worked fine. jQuery was able to access this element.
Therefore, I think there is something wrong with html elements created by the onMessage.addListener part of content script.
For additional reference: when I right-click on the newly created element "Inspect element" - I can see that the element is part of the html document. However, if I click "View page source" the element is not there.
Well, you are creating a new element of the class label-key, but the click handler assignment does not automagically extend to newly-created elements.
$(".label-key").click(...) is not behaving like a CSS rule despite looking like one: it collects all elements that match at the time of invocation and binds a listener for them.
So, if you add more images later, you need to add a click handler again:
function PlaceImage(source_x, source_y, imageUrl) {
var newImage = document.createElement("img");
newImage.src = imageUrl;
newImage.style.position = "absolute";
newImage.style.left = source_x + 'px';
newImage.style.top = source_y + 'px';
// Assigning a class name
newImage.className = "label-key";
newImage.click(function () {
console.log("hello");
});
// Add an element to the HTML document
document.body.appendChild(newImage);
}

Show image in JavaScript

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

Categories