Using a form to insert an image using Javascript - javascript

I'm using this javascript function to use a form to insert text into a set div.
I would like to be able to put an image url into a form and use this function to insert the url into an img tag instead of a div. What way could I achieve this?
Javascript:
function header01(){
var head01v = document.getElementById('head01i').value;
document.getElementById('head01c').innerHTML = head01v;
document.getElementById('head01c').style.display = "block";
return false;
}
I attempted to use the suggested solution, inputting the appropriate fields
function image01(){
var img = document.createElement('img');
img.src = document.getElementById('imag01i').value;
document.getElementById('imag01c').appendChild(img);
return false;
}
But to no avail, any additional help is greatly received.

Extending my comment to an answer:
It isn't that hard. First, check if you have a valid URL (more info on that here - first hit on Google), next, do this:
var img = document.createElement('img');
img.src = [the validated URL you obtained from the form];
document.getElementById('theElementYouWantToInsertTheImgIn').appendChild(img);

Related

Hide div based on different domains

I have two domains domainone.com and domaintwo.com both are aliases of one and another, however I'm wanting the logo of the site to change based on which URL is loaded.
The reason why is because it's a URL shortening script so there's no point me running multiple of the same scripts.
For example:
domainone.com/b should show logoone.png and domaintwo.com/b should show logotwo.png
Any help is greatly appreciated thanks.
You can probably do a switch statement or several if statements using window.location.hostname, which is the hostname of the current website (ie. domainone or domaintwo), and from there, change the source attribute of an image document.getElementById().src = whatever you want to put here
Well, you may want to use some javascript + css selectors for this.
First select your img element where you're changing the image:
let image = document.querySelector(".divClass img");
Or if you can set an id for image element that would be:
let image = document.getElementById("yourImgId");
Then check for the hostname with this:
let hostname = window.location.hostname;
And then use a regex to test domain names
if(/domain1.com/.test(hostname){
image.src = yourImage1Url;
}
else if(/domain2.com/.test(hostname){
image.src = yourImage2Url;
}
And so on you may do this further if someday there are more domains.
Edit: just to make sure everything happens when it's safe, you may wrap that code into a function and use it on an eventListener like this:
function YourFunctionName(){
let image = document.getElementById("yourImgId");
//or let image = document.getElementById("yourImgId");
let hostname = window.location.hostname;
if(/domain1.com/.test(hostname){
image.src = yourImage1Url;
}
else if(/domain2.com/.test(hostname){
image.src = yourImage2Url;
}
}
window.addEventListener("load", YourFunctionName);
I hope this helps you out.

Simple way to read one image from the JSON URL to HTML

Can someone please advise on a SIMPLEST way to show the email on HTML page from a JSON URL? I tried to run search, but everyone's advise is related to some complicated code that people have. I can read the data from the JSON URL, but I need to know how to instead of the url of the image show the image itself in my page.
JSON file has this location:
{"icon_url":"http://icons.wxug.com/i/c/k/icon.gif"}
if I use this JS format, It just reads the URL data into my HTML site.
document.getElementById('image').innerHTML = something.icon_url;
What would be the simple code, to have this gif actually show as picture on my test website?
There is no need to change the innerHTML attribute. Instead append an image with the DOM API.
//Assuming json_data is a variable containing the JSON in a string format.
json_data = JSON.parse(json_data);
var image = document.createElement("img");
image.onload = function() {
document.getElementById("image").appendChild(image);
}
image.src = json_data.icon_url;
Here's a quick snippet showing this functionality:
//You will probably fetch this not set it manually.
json_data = '{"icon_url": "http://i0.kym-cdn.com/photos/images/original/000/581/296/c09.jpg"}';
json_data = JSON.parse(json_data);
var image = document.createElement("img");
image.onload = function() {
document.getElementById("image").appendChild(image);
}
image.src = json_data.icon_url;
<!DOCTYPE html>
<html>
<body>
<div id="image"></div>
</body>
</html>

Receive text and picture from server in javascript

I need to refresh an img tag every second. so I wrote a little bit of code that changes src attribute of img tag and it loads the picture from image.php.
All good.
Sometimes the image.php doesn't have a picture, or sth went wrong in image.php. I need image.php to send a message along with the picture to determine validity of the picture, or tell me the error number.
so I need a php code that puts a text and a picture in it's output.
Right now I use
//code
header('Content-Type: image/jpeg');
imagejpeg($im);
imagedestroy($im);
and image.php acts like a .jpg file and I can use it in src attribute of img tag. But I need a way to find out if image.php is outputing a valid image and not a php error.
js code:
var newImage = new Image();
var count = 0;
function updateImage()
{
if(newImage.complete) {
document.getElementById("myimg").src = newImage.src;
newImage = new Image();
newImage.src = "socket.php?message=0&image" + count++ + ".jpg";
}
}
JavaScript-wise, you can find out about image failing to load via error event (jsfiddle).
Perhaps, you could request the same URL via Ajax if the image fails to load, to obtain the error message. Unless you'd want to encode error messages as images too (and decode them client-side), of course, which may, or may not be a good idea.
First method:
Using onerror property of the img element:
<img src="image.gif" onerror="alert('The image could not be loaded.')">
Source
You can use function as value of onerror property and use this function in java script. Example is below.
HTML:
<img src="image.gif" onerror="handleError();">
JS:
function handleError() {
// do something
}
Another way is to set onerror handler to instance of Image class:
var image = new Image();
img.src = /* url to the imgage */;
image.onload = function() {
// assign img.src to to src property of the `img` element
}
image.onerror = function() {
// do actions on error
}
Note:
2nd way is the way how to use new Image() correctly.
I would use Ajax for such a task, and send back the image path and any other added information from the server.
The Ajax response can be easily read by the client.

Changing image extension with javascript/jquery only?

I'm making a simple slider to show off artwork for a friend of mine. I'm really only familiar with javascript/jquery, so I'm not 100% comfortable using something else right now.
Since my friend doesn't have any programming knowledge, I'm trying to keep this really simple for her to update (i.e., automating creating new images whenever she adds a new one to the folder). She will upload images to a folder and will have to number them (i.e., 1.jpg, 2.jpg). My javascript uses a for loop to loop through numbers (she will have to update the loop whenever she adds a new image) and insert them into the file name. HOWEVER this limits her to only uploading one type of file. Is there someway to change the extension only using javascript?
This is what I have so far:
function callImages(){
//create the image div
$('.artslider').append('<div class="image"></div>');
//create the files array
var files = [];
//start the loop, starting position will have to be updated as images are added
for (i=8;i>=0;i--){
//create the img src for a jpg img
var imgJPG = 'arts/'+i+'.jpg';
//find the natural width of the image after it loads to see if it actually exists
var imgWidth = $('imgJPG').load().naturalWidth;
//if the width is undefined, replace the jpg extension with gif
if (imgWidth===undefined){
var imgGIF = imgJPG.replace('jpg', 'gif');
files[i] = '<img src="'+imgGIF+'" class="artsliderimg"/>';
}
//otherwise keep the jpg extension
else {
files[i] = '<img src="'+imgJPG+'" class="artsliderimg"/>';
}
//then add the images to the img div
$('.image').append(files[i]);
}
};
The problem with this if/else is that it will only create a gif image. If you switch the order, it will only create a jpg image.
edit: here's what this code produces: https://googledrive.com/host/0B1lNgklCWTGwV1N5cWNlNUJqMzg/index.html
The problem is with this bit of code:
var imgJPG = 'arts/'+i+'.jpg';
var imgWidth = $('imgJPG').load().naturalWidth;
imgWidth will always be undefined.
Firstly you are passing in the string 'imgJPG' instead of the parameter imgJPG. Secondly I think you have misunderstood jQuery selectors, this is used for selecting HTML elements, inputting a file path into here will not achieve anything. Thirdly I think you have misunderstood the load function, this is used for loading data from the server into a HTML element.
I would suggest using a function like below to check if the image exists:
function urlExists(url) {
var http = jQuery.ajax({
type:"HEAD",
url: url,
async: false
});
return http.status == 200;
}
Then in your code:
if (!urlExists(imgJPG)){
var imgGIF = imgJPG.replace('jpg', 'gif');
files[i] = '<img src="'+imgGIF+'" class="artsliderimg"/>';
}
else {
files[i] = '<img src="'+imgJPG+'" class="artsliderimg"/>';
}

Extract Tags From HTML using Javascript

I want to get the source of an image from html block and put it in a variable to send it to a remote function.
How can i extract img tag from html text :
var myImageSrc = document.getElementById('myImageId').src;
or similar.
var imgs=document.getElementsByTagName("img");
for(var i=0;i<imgs.length;i++){
var img=imgs[i];
//do something with img.src
}
-- edit --
to remove images from the text do something like this (at the comment):
img[i].parentNode.removeChild(img[i])
What's left is the text (access it using img[i].parentNode.innerHTML)
var imageSource = document["yourImage"].src;

Categories