Passing image objects as Function & Class Arguments - javascript

How do you pass an image as argument in a function/class or is this impossible and if it is how would I fix it? For example:
var tree = new Image();
tree.src = "img/statobj/tree.png"
function additem(dimage){
document.getElementById("myitems").rows[0].insertCell(0).innerHTML ='<div id="invetoryitem" >'+ this.dimage + '</div>'
console.log(dimage) //gets undefined
}
I've tried dimage.src and other methods but nothing I use seems to work :/

Pass it like you would any other, but to display it, use appendChild not innerHTML:
var tree = new Image();
tree.src = "https://upload.wikimedia.org/wikipedia/commons/thumb/e/eb/Ash_Tree_-_geograph.org.uk_-_590710.jpg/220px-Ash_Tree_-_geograph.org.uk_-_590710.jpg";
function showTree(dimage) {
document.getElementById("div").appendChild(dimage);
console.log(dimage);
}
showTree(tree);
<div id="div"></div>
If you do want to use innerHTML, make an <img> with the src being dimage.src:
var tree = new Image();
tree.src = "https://upload.wikimedia.org/wikipedia/commons/thumb/e/eb/Ash_Tree_-_geograph.org.uk_-_590710.jpg/220px-Ash_Tree_-_geograph.org.uk_-_590710.jpg";
function showTree(dimage) {
document.getElementById("div").innerHTML = "<img src='" + dimage.src + "'>";
console.log(dimage);
}
showTree(tree);
<div id="div"></div>

You have to name the function and call it by passing the image as an argument. If you are using innerHTML you have to create the image tag and add the source of the image received to the function as argument
var tree = new Image();
tree.src = "img/statobj/tree.png"
function a(dimage){
document.getElementById("myitems").innerHTML ='<div id="invetoryitem" ><img src="'+dimage.src+ '"></div>'
console.log(dimage) //gets undefined
}
a(tree);
<body id="myitems"></body>

Related

Dynamically add <img> tags with via PHP loop, via calling a JavaScript function on each loop

I have a PHP function that loops through image results in a database, formats them with HTML, then returns the variable containing the HTML layout to my page.php. This is all working okay, but in the loop I have some script tags that call a function in my script.js file. It takes two parameters (url and count). I am trying to pass the url of the result from the database to the function, create a new img element, and append the passed url to the src attribute of the newly created img tag.
This appears to be working so far - when I console.log the result, I get a load of <img> tags, all with corresponding src attached to them.
I am having trouble with actually getting these back to the front end, though.
My code below shows the part of the php that gets looped through, followed be the Javascript function it calls on each loop.
public function getResultsHtml($page, $pageSize, $term) {
$fromLimit = ($page - 1) * $pageSize;
$query = $this->con->prepare("SELECT * FROM images
WHERE (title LIKE :term
OR alt LIKE :term) AND broken=0
ORDER BY clicks DESC
LIMIT :fromLimit, :pageSize");
$searchTerm = "%" . $term . "%";
$query->bindParam(":term", $searchTerm);
$query->bindParam(":fromLimit", $fromLimit, PDO::PARAM_INT);
$query->bindParam(":pageSize", $pageSize, PDO::PARAM_INT);
$query->execute();
$resultsHtml = "<div class='image-results'>";
$count = 0;
while($row = $query->fetch(PDO::FETCH_ASSOC)) {
$count++;
$id = $row["id"];
$imgUrl = $row["imgUrl"];
$siteUrl = $row["siteUrl"];
$title = $row["title"];
$alt = $row["alt"];
if($title){
$displayText = $title;
} else if ($alt) {
$displayText = $alt;
} else {
$displayText = $imgUrl;
}
$resultsHtml .= "<div class='grid-item image$count'>
<a href='$imgUrl'>
<script>
document.addEventListener('DOMContentLoaded', function() {
loadImage(\"$imgUrl\", \"image$count\");
});
</script>
<span class='details'>$displayText</span>
</a>
</div>";
}
$resultsHtml .= "</div>";
return $resultsHtml;
}
var loadImage = function(src, className){
var image = document.createElement("img");
var aTag = document.querySelectorAll("." + className + " a");
image.onload = function(){
aTag.innerHTML = image;
};
image.onerror = function(){
};
image.setAttribute("src", src);
}
At the moment I'm not geting any results at the front end. In the page source, I can see that inside each anchor tag are script tags, which show the function preloaded with the parameters (loadImage(http://www.com, image22)), but it isn't actually getting a return from the function.
The solution for this with jQuery is below, but I really don't want to use jQuery!
function loadImage(src, className) {
var image = $("<img>");
image.on("load", function() {
$("." + className + " a").append(image);
});
image.on("error", function() {
});
image.attr("src", src);
}
I know that there is some trouble with dynamically writing <script> tags with .innerHTML, but I don't think this is the problem as the script tags are written before the function is called.
I think I have something firing in the wrong order, or I'm missing something that jQuery handles automatically with the .append function.
I have also tried aTag.appendChild(image);, which also gives no results.
I have been using jQuery for a few months, but I am trying to learn Vanilla JS thoroughly - I'm trying to grasp how the jQuery functions actually work, rather than just relying on them blindly.
Any help is massively appreciated!
Beware of that querySelectorAll() returns an array-like NodeList (https://developer.mozilla.org/en-US/docs/Web/API/NodeList), so it should be like this:
(If you only want one element returned user querySelector(), then you don't need the loop)
function loadImage(src, className) {
var image = document.createElement("img");
image.src = src;
image.onload = function() {
var tags = document.querySelectorAll("." + className + " a");
for (var i = 0; i < tags.length; i++) {
tags[i].appendChild(image);
}
}
}
<div class='grid-item image2'>
<a href='https://cdn.pixabay.com/photo/2015/08/21/21/55/star-wars-899693_960_720.jpg'>
<script>
document.addEventListener('DOMContentLoaded', function() { loadImage("https://cdn.pixabay.com/photo/2015/08/21/21/55/star-wars-899693_960_720.jpg", "image2");
});
</script>
<span class='details'>Star Wars 1</span>
</a>
</div>
The problem is that you are using querySelectorAll, which returns a NodeList instead of a single DOM node. This means, you have to iterate over the NodeList and append the image to all the nodes within. For this, you have can either create new copies for each place you want to insert the image, or use cloneNode multiple times.
var each = function (xs, func) {
for (var i = 0; i < xs.length; i += 1) {
func(xs[i]);
}
return xs;
}
var loadImage = function(src, className){
var image = document.createElement("img");
var aTag = document.querySelectorAll("." + className + " a");
image.onload = function(){
each(aTag, function (a) {
a.appendChild(image.cloneNode());
});
};
image.onerror = function(){};
image.alt = '';
image.src = src;
}
loadImage('http://www.fillmurray.com/500/300', 'wrap')
<div class="wrap">
</div>

Replacing texts with emoticons in JavaScript from Json values

I am trying to replace text with images.For example, abc:) should be converted into abc(and the respective emoticon).And I am using contenteditable element for doing the same.But, nothing seems to work.I tried using the replace() and html() functions but they don't work.
The link to my Codepen is: Link
And I don't want to use regex as I have to do more additions in my json file.Thanks!
HTML Code:
<div contenteditable="true" id='text-box'>
</div>
JS Code:
document.body.onkeyup=function(e){
if(e.keyCode==32){
var contenteditable = document.querySelector('[contenteditable]'),
text = contenteditable.textContent;
var word=getWord(text);
console.log(word);
console.log(data.value);
if(word.includes(data.value)){
//alert("true");
var img=new Image();
img.src=data.image;
img.setAttribute("class","image");
//$("#text-box").append(img);
$("#text-box").html(function (_, html) {
return html.replace(data.value , img );
}
//$("#text-box").html(text.replace(data.value,img));
}
}
function getWord(text){
var word=text.split(" ").pop();
return word;
}
JSON data:
var data={
"value":":)",
"image":"persons-0016_large.png"
};
After the execution of my code,I get the output as abc[object HTMLImageElement] instead of the image itself.
Instead of creating an image object, replace the text by image tag like this.
var data={
"value":":)",
"image":"persons-0016_large.png"
};
document.body.onkeyup=function(e){
if(e.keyCode==32){
var contenteditable = document.querySelector('[contenteditable]');
var text = contenteditable.textContent;
var word=getWord(text);
console.log(word);
console.log(data.value);
if(word.includes(data.value)){
//alert("true");
//var img=new Image();
//img.src=data.image;
//img.setAttribute("class","image");
var img = "<img src='" + img.src +"' class='image' /> ";
//$("#text-box").append(img);
$("#text-box").html(function (_, html) {
return html.replace(data.value , img );
} );
//$("#text-box").html(text.replace(data.value,img));
}
};
};
function getWord(text){
var word=text.split(" ").pop();
return word;
}

JS: How to change the image reference ending value

Instead of having a ton of if statements, I would like the method to display the correlated image by name, fx. clicking BlackPicture4.gif will turn it into WhitePicture4.gif. The number of the picture is passed on to the method.
I'm new to javascript, so maybe indexes[] don't work as I thought they do.
I have an array of Whitepicures:
imgArray[1] = new Image();
imgArray[1].src = "WhitePicture1.gif";
...
function changePicture(int)
{
var image = document.getElementById('Img' + int); //works
image.src = imgArray[int] //doesn't work
var thefile = "imgArray" + int + ".gif" //also doesn't work
image.src = thefile;
}
I tried so many different ways, but could use help
html: //as requested, but that works fine
<img id="Img1" onclick="changePicture(1)" src="Blackpicture1.gif" width="50" height="50" >
<img id="Img2" onclick="changePicture(2)" src="Blackpicture2.gif" width="50" height="50" >
...
Edit: The problem is solved by adding .src to "= imgArray[int]"
Another thing I didn't think of was I had to assign the array elements INSIDE a function, rather than just on top of the file where I believe only declarations can be made.
This may work im not sure
imgArray[1] = new Image();
imgArray[1].src = "WhitePicture1.gif";
var x;
function changePicture(x) {
var image = document.getElementById('Img' + x);
image.src = imgArray[x].src;
}
I think what you're trying to do might be
function changePicture(int){
document.getElementById('Img'+int+'').setAttribute('src',imageArray[int].src);
}
In this example, the pic with id='1' will be converted into a pic with id='2':
$("img").click(function() {
var x = $(this).attr("id");
x++;
var y = $("#" + x).attr("src");
$(this).html("");
$(this).html("<img src='" + y "'>");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<img src="pic1.jpg" id="1">
<img src="pictobereplaced.jpg" id="2">

Appending new container on click

I'm trying to learn HTML and Javascript/jQuery. If I have a container which holds a title, an image, a description and a number, then I want to create a new container with the exact same format (except the values will be different), how is this commonly done?
This is an example of the format I'm looking for in each item.
<li>
<div>
<div>
Image Name
</div>
<div>
<a href=URL>
<img src='image_url'>
</a>
</div>
<div>
Description
</div>
<div>
num_comment Comments
</div>
</div>
</li>
Do I just create a string and concatenate with the actual values for the image, then add that string to some variable I've saved called html_content, and then set the html value to html_content? Is that the common way of doing this or is there a better way?
EDIT
To give a better idea of what I'm currently doing, here's the javascript:
var html1 = '<li><div><div>';
var html2 = '</div><div><a href="';
var html3 = '"><img src="';
var html4 = '"></a></div><div>';
var html5 = '</div><div>';
var html6 = '</div></div></li>';
function render(pics){
for (var i in pics){
html = html + html1 + pics[i].name + html2 + pics[i].image_url + html3 + ...
};
$('pics').html(html);
}
In jQuery you just have to use the append() function to add on to something.
You could do something like...
$('select element').append('<li><div>....etc.');
and where you want a different value you can use a variable.
You can use .clone() and create a copy of this, then iterate through the cloned object and change what you need:
var $objClone = $("li").clone(true);
$objClone.find("*").each(function() {
//iterates over every element. customize this to find elements you need.
});
To change the image source you can do:
$objClone.find("img").attr("src", "new/img/here.jpg");
Fiddle demoing the concept: http://jsfiddle.net/H9DnA/1/
You may find it useful to explore some of the JavaScript templating libraries. The essential idea is that you create a template of your markup:
<li>
<div>
<div>
{{name}}
</div>
<div>
<a href="{{url}}">
<img src="{{imageUrl}}">
</a>
</div>
<div>
{{description}}
</div>
<div>
{{comments}}
</div>
</div>
</li>
Then you merge it against some associated matching object and insert it into your document:
{ name: 'Image Name',
url: 'http://example.com',
imageUrl: 'http://example.com/image.jpg',
description: 'Description',
comments [ { text: 'Comment' } ]
}
function render(pics)
{
var theList = document.getElementByid("LIST ID");
for (var i in pics){
var listItem = document.createElement('li'); // Create new list item
var nameDiv = document.createElement('div'); // Create name DIV element
nameDiv.innerHTML = pics[i].name; // Insert the name in the div
var img = document.createElement('img'); // Create Img element
img.setAttribute('src',pics[i].src); // Assign the src attribute of your img
var imgDiv = document.createElement('div'); // Create Img Div that contains your img
imgDiv.appendChild(img); // Puts img inside the img DIV container
var descDiv = document.createElement('div'); // Create Description DIV
descDiv.innerHTML = pics[i].description; // Insert your description
listItem.appendChild(nameDiv); // Insert all of you DIVs
listItem.appendChild(imgDiv); // inside your list item
listItem.appendChild(descDiv); // with appropriate order.
theList.appendChild(listItem); // Insert the list item inside your list.
}
}
I think this will work just fine:
$('#button').click(function () {
var html1 = '<li><div><div>';
var html2 = '</div><div><a href="';
var html3 = '"><img src="';
var html4 = '"></a></div><div>';
var html5 = '</div><div>';
var html6 = '</div></div></li>';
function render(pics){
for (var i in pics){
html = html + html1 + pics[i].name + html2 + pics[i].image_url + html3 + ...
$("ul").append(html);
}
}
// call render
});
I didn't do a test run on your code so there might be an error somewhere. My tweak adds this line $("ul").append(html); inside your loop

How to display images using Javascript and JSON

I have to display images to the browser and I want to get the image from a JSON response and display it to the browser using Javascript. This is what the JSON response looks like:
[{
"0":"101",
"member_id":"101",
"1":"3k.png",
"image_nm":"3k.png",
"2":"\/images\/phones\/",
"image_path":"\/images\/"
},{
"0":"102",
"member_id":"102",
"1":"mirchi.png",
"image_nm":"mirchi.png",
"2":"images\/phones\/",
"image_path":"images\/phones\/"
},{
"0":"103",
"member_id":"103",
"1":"masti.png",
"image_nm":"masti.png",
"2":"images\/phones\/",
"image_path":"images\/phones\/"
}]
How do I do this (I am a beginner)?
here is the code what i wrote...
var jsonString = '[{"0":"101","member_id":"101","1":"3k.png","image_nm":"3k.png","2":"\/images\/phones\/","image_path":"\/images\/phones\/"},{"0":"102","member_id":"102","1":"mirchi.png","image_nm":"mirchi.png","2":"images\/phones\/","image_path":"images\/phones\/"},{"0":"103","member_id":"103","1":"masti.png","image_nm":"masti.png","2":"images\/phones\/","image_path":"images\/phones\/"}]';
var obj = JSON.parse(jsonString);
for(var i = 0, len = obj.length; i < len; i++){
var img = new Image();
img.setAttribute("src",obj[i][2] + obj[i][1]);
document.body.appendChild(img);
}
Assuming you parsed your json in a variable called json, this would add all images in a container with id yourcontainer:
var images = '';
for( var i=0, max<json.length; ++i ) {
images += '<img src="' + json[i]['image_path'] + json[i]['image_nm'] + '" />';
}
document.getElementById( 'yourcontainer' ).innerHTML = images;
Seems pretty straight forward. If this is json_encoded, then we can use json[key] to get the value, if you aren't familiar with the term 'key', json encodes arrays in the key:value, format, so for this, if we used json[member_id], we would get '101', if we used json[image_nm], we would get '3k.png', putting this all together it seems as if it's pretty well separated, you just have to know what goes where. I have an idea, but not 100%,I would expect you to do something like
var myImages = '';
for(var i = 0; i < json.length; i++){
myImages += '<img src="'+json[i]['image_path']+json[i]['img_nm']+'" />';
}
document.getElementById('myImgHolder').innerHTML = myImages;
Based on your json data, this would evaluate a variable and test it against the length of the json array. The statement also declares that while the variable is less than the total length of the json array, we will iterate to the next object. We would expect output along the format of -
<img src="/images/3k.png" />.
Then it would take the new images and place them in a Div with the id of myImgHolder.
Hope this helps.
EDIT 1
If you don't have a container to place these images inside of it, then you will need to create the container and place it somewhere.
var myImgHolder = document.createElement('div');
myImgHolder.setAttribute("id", "myImgHolder");
document.getElementById('ICanTargetThis').appendChild(myImgHolder);
The above code sets the variable myImgHolder to the creation of a new DIV element. Then, using the variable, we declare the attribute "id" to set as 'myImgHolder'. Now we have the element. But what do we do with it? Well we MUST target an existing element within our page, even if we're just targeting the tag...something. then we use the .appendChild method and use our variable...appendChild(myImgHolder);
You can use jQuery here.
Add following script in the head tag.
<script src="https://code.jquery.com/jquery-2.1.1.min.js"></script>
<script>
$(document).ready(function () {
var url = "entries.json";
$.getJSON(url, function (url){
var img= "";
$.each(url, function () {
img += '<li><img src= "' + this.images+ '"></li>';
});
$('body').append(img);
});
});
</script>

Categories