JavaScript function not working in HTML page - javascript

HTML code for browse file button
<input type="file" multiple="false" accept="image/*" id="filein" onclick="filo()">
JavaScript
function filo(){
var canin= document.getElementByID("c5");
var imgin = document.getElementById("filein");
var xct = canin.getContext("2d");
var img = new Image(filein);
xct.drawImage(canin);
}

There are several problems.
You need to use the onchange event not the click event
<input type="file" multiple="false" accept="image/*" id="filein">
You add the event listener using script rather than in line.
<script> // this script must be place after the element filein or use an onload event.
filein.onchange = filo();
</script>
The function getElementById returns an element not a string. You need to get the filename (URL) from the element's files property
Change the image construction as it does not take the image URL as an argument. You set the img.src to the url then wait for the image to load.
The function drawImage function requires the image and at least 2 arguments that are the location to draw at.
Example of changes.
function filo () {
// Get the filename of the input element
var imgin = document.getElementById("filein").files[0]; // <<Get the file URL
// Typo its getElementById not getElementByID
var canin= document.getElementById("c5");
var xct = canin.getContext("2d");
// Image does not take a URL via the constructor
var img = new Image();
// set the URK here
var img.src = imgin;
// you need to wait for the image to load then you can draw it
img.onload = function () {
// drawImage function requires the image and at least 2 arguments
// that are the location to draw at
xct.drawImage(this, 0, 0); // this is the image in the onload event
}
}

Related

Hide img when alternate image not exists

In asp.net img tag I need to set gif image. I set gif image for src of the img and if gif doesn't exist I need to set jpg for the img. But if the jpg also not exists I need to hide the img from the page.
I used onerror event of the img tag for this with the javascript function. But at sometimes it saying the function not found.
Is there ay easy way to do this. My need is to set gif to img and if the gif not exists set jpg to it and if jpg also not exists need to hide the img.
I tried like this
<img src="mygif.gif" onerror="setJpg($(this));">
function setJpg(source) {
var file = source[0].src;
var jpgFile = file.substr(0, file.lastIndexOf(".")) + ".jpg";
var img = document.createElement('img');// new Image();
img.onload = function () { source[0].src = jpgFile; };
img.onerror = function () { source.parent().hide() };
img.src = jpgFile;
}
The onerror event eventually gets recalled after changing the src of the image. So you do not have to create another img and can resue the same event. Like set a new handler or check for the ending.
//REM: Note that "img" is an element and not jquery wrapped.
function setJpg(img){
console.log('Called onerror');
//REM: If image ends with ".gif"
if(img.src.toLowerCase().endsWith('.gif')){
//REM: Change ".gif" to ".jpg", whatever your logic is.
//REM: This is going to call onerror again if not found
img.src = img.src.replace('.gif', '.jpg');
console.log('Changed src', img.src)
}
else{
//REM: Remove the event
img.onerror = null;
//REM: Remove the image or do whatever you want with it
img.remove();
console.log('Removed element')
}
}
<img src = 'wayne.gif' onerror = 'setJpg(this)'>

Image Swap on MouseOut (JavaScript, not JQ)

I am trying to create functions to mouseover and mouseout of images. The tricky part is this function needs to work for any image, and I cannot use direct image names. I have to therefore use variables.
The HTML code is as follows for the images:
The HTML for the images is like this, and there are 3 images:
<img src="images/h1.jpg" alt="" id="images/h4.jpg" onmouseover="swapToNewImage(this)" onmouseout="swapImageBack(this)">
I'm expecting that you have to reference the id for the new image, and then the src attribute for the previous image to revert when you mouseout.
The problem is that, if I reference the id attribute, the image no longer has information on the src attribute so I cannot call it to revert back.
Here is the JavaScript I have thus far. It works to swap the image to a new one, but not to swap it back :(
//FUNCTION
var $ = function (id) {
return document.getElementById(id);
}
//ONLOAD EVENT HANDLER
window.onload = function () {
//GET ALL IMG TAGS
var ulTree = $("image_rollovers");
var imgElements = ulTree.getElementsByTagName("img");
//PROCESS EACH IMAGE
//1. GET IMG TAG
for (var i = 0; i < imgElements.length; i++) {
console.log (imgElements[i]);
console.log (imgElements[i].getAttribute("src"));
//2. PRELOAD IMAGE FROM IMG TAG
var image = new Image();
image.setAttribute("src", imgElements[i].getAttribute("src"));
//3. Mouseover and Mouseout Functions Called
image.addEventListener("mouseover", swapToNewImage);
image.addEventListener("mouseout", swapImageBack);
}
}
//MOUSE EVENT FUNCTIONS
var swapToNewImage = function(img) {
var secondImage = img.getAttribute("id", "src");
img.src = secondImage;
}
var swapImageBack = function(img) {
var previousImage = img.getAttribute("src");
img.src = previousImage;
}
Let me know if you can help me figure out how to call the image's src attribute so it can be reverted back. Again, I cannot reference specific image names, because that would be a lot easier (: Thank you!
Well, You can use a data attribute to store your src, and a data attribute to store the image you want to swap when mouseover.
Please try the following example.
var swapToNewImage = function(img) {
var secondImage = img.dataset.swapSrc
img.src = secondImage;
}
var swapImageBack = function(img) {
var previousImage = img.dataset.src
img.src = previousImage;
}
<img src="https://images.pexels.com/photos/259803/pexels-photo-259803.jpeg?auto=compress&cs=tinysrgb&dpr=1&w=500" alt="" data-src="https://images.pexels.com/photos/259803/pexels-photo-259803.jpeg?auto=compress&cs=tinysrgb&dpr=1&w=500" data-swap-src="https://images.pexels.com/photos/416160/pexels-photo-416160.jpeg?auto=compress&cs=tinysrgb&dpr=1&w=500" onmouseover="swapToNewImage(this)" onmouseout="swapImageBack(this)">
I also notice that the image tag is generated by code, in order to set the dataset values, we can do this:
var image = new Image();
image.scr = [src]
image.dataset.src = [src]
image.dataset.swapSrc = [swap src]

How to set img src dynamically with a function

I want to set img src=" " with a function in javascript that changes the picture upon a variable and checks values:
javascript file code:
function myFunctionstatus(){
var ledactual=document.getElementById("ledonof").value
var image = document.getElementById('ledPic');
if (ledactual==ledon) {
image.src = "https://cdncontribute.geeksforgeeks.org/wp-c
content/uploads/OFFbulb.jpg";
}
if (ledactual==ledoff){
image.src = "https://cdncontribute.geeksforgeeks.org/wp-
content/uploads/ONbulb.jpg";
}
} };
img src in html file:
<img id="ledPic" [src]="myFunctionstatus()" >
but it didn't work with me and the picture didn't appear! the script is working, I tested with a button:
<input type="button" id="ledonof" onclick="myFunction();myFunctionstatus();" class="ledonoff" value="<?phpinclude ('ledstatus.php'); ?>">
how can I set img src with a function?
I can't comment on the php that you're using to get the status, but the below is a working javascript example:
function myFunctionstatus(){
var input = document.getElementById("ledonof");
var image = document.getElementById('ledPic');
if (input.value == "on") {
image.src = "https://cdncontribute.geeksforgeeks.org/wp-content/uploads/ONbulb.jpg";
input.value = "off"
} else if (input.value == "off"){
image.src = "https://cdncontribute.geeksforgeeks.org/wp-content/uploads/OFFbulb.jpg";
input.value = "on"
}
}
myFunctionstatus()
<img id="ledPic" />
<input type="button" id="ledonof" onclick="myFunctionstatus();" class="ledonoff" value="on">
As noted by others, src doesn't support function calls (and you don't even return anything from your function call), so you need to run the function once at the start to set the image to the initial status.
You need to set an initial state manually
function switchStatus() {
let switchButton = document.getElementById('ledonof');
let img = document.getElementById('ledPic');
if(switchButton.value == "ledon") {
img.src = "https://cdncontribute.geeksforgeeks.org/wp-content/uploads/OFFbulb.jpg";
switchButton.value = "ledoff";
} else {
img.src = "https://cdncontribute.geeksforgeeks.org/wp-content/uploads/ONbulb.jpg";
switchButton.value = "ledon";
}
}
<img id="ledPic" src="https://cdncontribute.geeksforgeeks.org/wp-content/uploads/OFFbulb.jpg" > <input type="button" id="ledonof" onclick="switchStatus();" value="ledoff">
img src attr does not support function call. Whatever you pass in the src will be considered as url(relative or otherwise).
Please refer https://developer.mozilla.org/en-US/docs/Web/HTML/Element/img#Attributes
So what you need to do is call the function before/loading your element and change the src then. The simplest form would be following
`<script>
(function() {
// your page initialization code here
// the DOM will be available here
// call the function here
})();
</script>`
You can't do this. The src attribute of an image element can't be interpreted as javascript when the HTML is interpreted.
initially, you need to set src, and on button click, you can toggle image by changing image src.

Javascript image upload and display

My basic task is select image and display it,without saving it in database.
For this
1.I have made a select tag in html,through which I can upload the image.
2.I have made a blank image tag in which at there is no image source,alternate is upload image.
3.select tag has onchange javascript event handler which calls javascript function changeimage.
<script>
function changeimage()
{
document.form_name.imagetag.src=document.form_name.filetag.value;
}
</script>
In above Code
form_name : Is the name of my form
<form name = "form_name">
imagetag : Is the name of my Img tag
<Img src=" " name = "imagetag">
filetag : Is the name of my
<input type="file" name = "filetag" onchange="changeimage()">
I have save file using php extension.And when I try to print the value of filetag it shows "C:\fakepath\image.png",display this address for all image.
I have save my php file in www location.
I am using window 7,wamp server and chrome latest version.
You may want to checkout this solution (where my code derives from). It involves a little bit of jQuery but if you truly must write it out in pure JS, here you go.
Note: I modified your tags to conform to the JS below. Also try to stay away from writing any inline scripts. Always good to keep your HTML and JS loosely coupled.
var fileTag = document.getElementById("filetag"),
preview = document.getElementById("preview");
fileTag.addEventListener("change", function() {
changeImage(this);
});
function changeImage(input) {
var reader;
if (input.files && input.files[0]) {
reader = new FileReader();
reader.onload = function(e) {
preview.setAttribute('src', e.target.result);
}
reader.readAsDataURL(input.files[0]);
}
}
<input type="file" id="filetag">
<img src="" id="preview">
You can also use the Image() constructor. It creates a new HTML Image Element.
Example -
document.getElementById("filetag").addEventListener("change", function(e) {
let newImg = new Image(width, height);
// Equivalent to above -> let newImg = document.createElement("img");
newImg.src = e.target.files[0];
newImg.src = URL.createObjectURL(e.target.files[0]);
output.appendChild(newImg);
});
Reference - https://developer.mozilla.org/en-US/docs/Web/API/HTMLImageElement/Image
You need one input tag to upload file and a image tag to render on the site.
The HTML and Javascript should look like
const renderFile = () => {
const render = document.querySelector('img')
const file = document.querySelector('input[type=file]').files[0]
const reader = new FileReader();
reader.addEventListener('load' , ()=> {
render.src = reader.result;
}, false)
if(file){
reader.readAsDataURL(file);
}
}
<input type = 'file' onchange = 'renderFile()' >
<br>
<br>
<img src = "" alt='rendered image' id='rendered-image' >
Simply on every upload the web page will show the image uploaded
You can Style the height and width of the image according to the need

Javascript: How can I delay returning a value for img.complete

I've written a script to test for SVG support in the IMG tag:
function SVGinIMG() {
var SVGdata = 'data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHdpZHRoPSIyNzUiIGhlaWdodD0iMjc1Ij48L3N2Zz4%3D'
var i = document.createElement('img');
i.setAttribute('src',SVGdata);
return i.complete;
}
window.onload = function() {
var hasSVG = SVGinIMG();
alert(hasSVG);
}
This does what I want, except that when I run the script in WebKit browsers the complete property doesn't trigger the first time I load the page; when I refresh the page, it works as it should. The return function is running before the img has finished loading; what's the best method to delay this?
I was complicating things a little; all I really needed was the load event:
function SVGDetect() {
var testImg = 'data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHdpZHRoPSIyNzUiIGhlaWdodD0iMjc1Ij48L3N2Zz4%3D';
var img = document.createElement('img')
img.setAttribute('src',testImg);
img.addEventListener('load',setCSS,true);
}
This runs another function when the image loads, which is never in the case of browsers that don't support SVG in images.

Categories

Resources