How to change src with onclick? - javascript

How change the src of a image with user input src ?
Here is my current JS code ↓
function prmpt () {
var source = prompt ("Enter Image Source ↓")
}
var image = document.getElementById("img"); function changeColor()
{ if (image.getAttribute('src') == "https://api.sololearn.com/Uploads/Avatars/3401170.jpg") { image.src = source; }
else { image.src = "https://api.sololearn.com/Uploads/Avatars/3401170.jpg"; } }

Call the below function on an input of the image source, like onblur. Assign an id to your image for which the image needs to be changed
function imageChanger(newimage) {
document.getElementById("img").src=newimage;
}

You can do this if you prefer:
const changeImg = (newImg) => document.getElementById("img").src = newImg

Related

HTMLImageElement onclick

I am trying to add an onclick event that calls a function selectMain(name). When I run my project it doesn't seem to generate the onclick attribute from the image.
function previewFiles() {
var preview = document.querySelector('#preview');
var files = document.querySelector('input[type=file]').files;
function readAndPreview(file) {
if (/\.(jpe?g|png)$/i.test(file.name)) {
var reader = new FileReader();
reader.addEventListener("load", function() {
var image = new Image();
image.height = 100;
image.title = file.name;
image.src = this.result;
image.onclick = selectMain(file.name);
preview.appendChild(image);
}, false);
reader.readAsDataURL(file);
}
}
if (files) {
[].forEach.call(files, readAndPreview);
}
}
function selectMain(name) {
var files = document.querySelector('input[type=file]').files;
Array.from(files).forEach(file => {
if (file.name == name) {
document.getElementById("primaryPhoto").value = file;
}
});
}
Try thisimage.onclick = function(){ selectMain(file.name); };
In addition to what Gagik answered (the early selectMain call is definitiely an issue even if it doesn't fix the whole thing), what is
document.getElementById("primaryPhoto").value = file;
supposed to do? If primaryPhoto is a input[type=file] element, then that won't work due to security limitations
You cannot set the value of a file picker from a script
Source.
(/\.(jpeg?g|png)$/i.test(file.name))
In the existing code, function get invoked on the time of render on dom.
here is the correct way to bind event.
var image = new Image();
image.height = 100;
image.title = file.name;
image.src = this.result;
image.onclick =()=>{selectMain(file.name)};

Cannot get file size after uploading using JavaScript

I need to validate one file field with required width,height and if file has not uploaded using JavaScript but its not happening like this. Here is my code:
<input type="file" name="copImage" id="copImage" class="form-control" value="" onchange="setBackgroundImage(event);">
function setBackgroundImage(e){
var url = URL.createObjectURL(e.target.files[0]);
bg = new Image();
bg.src = url;
bg.onload = function () {
bgLoaded = true;
backImageHeight=this.height;
backImageWidth=this.width;
};
console.log('size bg',backImageHeight,backImageWidth);
}
Here I could not get the file height and width. I also to check the if file has not uploaded.
Pu the log statement inside the onload function. This is because you are trying to access the variable outside its scope, else define those variables outside onload function
bg.onload = function() {
var bgLoaded = true,
backImageHeight = this.height,
backImageWidth = this.width;
console.log('size bg',backImageHeight,backImageWidth);
};
DEMO
suppose i have one button and without selecting file if I am clicking
on the file alert should say to select the file.
Seems you cannot do that with onchange event handler because if file is not loaded. nothing has changed and so function wont fire. In that case you can create a variable & update its state on file upload. On clicking of the button check the variable state
var isFileLoaded = false;
function setBackgroundImage(fileValue) {
var url = URL.createObjectURL(fileValue.files[0]);
bg = new Image();
if (fileValue.value !== '') {
bg.src = url;
bg.onload = function() {
bgLoaded = true;
isFileLoaded = true;
backImageHeight = this.height;
backImageWidth = this.width;
console.log('size bg', backImageHeight, backImageWidth);
};
}
}
function buttonClick() {
if (isFileLoaded) {
} else {
alert('No file selected')
}
}
DEMO 2
Hello You just need to log your height and width inside bg.onload function.these are outside of the scope of variables.thats why you not getting the height and width like this
function setBackgroundImage(e){
var url = URL.createObjectURL(e.target.files[0]);
bg = new Image();
bg.src = url;
bg.onload = function () {
bgLoaded = true;
backImageHeight=this.height;
backImageWidth=this.width;
console.log('size bg',backImageHeight,backImageWidth);
};
}
Everything is fine in your code, you need to include console.log() within bg.onload block only like this .
function setBackgroundImage(e)
{
var url = URL.createObjectURL(e.target.files[0]);
bg = new Image();
bg.src = url;
bg.onload = function () {
bgLoaded = true;
backImageHeight=this.height;
backImageWidth=this.width;
console.log('size bg',backImageHeight,backImageWidth);
};
}
function isFileSelected()
{
return document.getElementById('copImage').files.length > 0;
}
You can use isFileSelected() function to know whether file is selected or not .

Swapping an img src with a function (JavaScript)

I'm trying to swap two imgs in my webpage and can't wrap my head around why this code doesn't work. Any help would be appreciated.
This is in the HTML file:
<img onclick="swap(); "src="LaptopThin.jpg" id="LaptopPicture" />
while this is in a seperate javascript file:
function swap()
{
var picture = document.getElementById('LaptopPicture').src;
if (picture === 'LaptopThin.jpg') {
picture.src = 'ServerRack.jpg';
} else {
picture.src = 'LaptopThin.jpg';
}
I changed the code to:
function swap()
{
var picture = document.getElementById('LaptopPicture');
if (picture.src === 'LaptopThin.jpg') {
picture.src = 'ServerRack.jpg';
} else {
picture.src = 'LaptopThin.jpg';
}
}
and the picture is still not changing at all in the html file. The img stays on Laptopthin.jpg
You can't set the src property of picture because you set picture to the src property of an element already.
Change these lines:
var picture = document.getElementById('LaptopPicture').src;
if (picture === 'LaptopThin.jpg') {
to these:
var picture = document.getElementById('LaptopPicture');
if (picture.src === 'LaptopThin.jpg') {
It is because, the src property will give the absolute value of the image source not just the value set by the src attribute
function swap() {
var picture = document.getElementById('LaptopPicture');
if (picture.src.indexOf('LaptopThin.jpg') > -1) {
picture.src = 'ServerRack.jpg';
} else {
picture.src = 'LaptopThin.jpg';
}
}
Another option to try is to use getAttribute
function swap() {
var picture = document.getElementById('LaptopPicture');
if (picture.getAttribute('src')== 'LaptopThin.jpg') {
picture.src = 'ServerRack.jpg';
} else {
picture.src = 'LaptopThin.jpg';
}
}

make an image 'onclickable' in a js object

The js object below will, after instantiation, produce the specified image. what I'd like is to get the image to execute sayQuote when clicked in the browser. Suggestions?
function CharType()
{
this.charImage = function(whichImage)
{
var image = document.createElement("img");
image.src = "characters/"+whichImage;
document.body.appendChild(image);
}
function sayQuote()
{
alert(getQuote());
}
// this.onclick = sayQuote(); // nope, that doesn't do it!
}
the instantiation:
var stickfigure = new CharType();
stickfigure.charImage("stickfigure.png");
try this.
function CharType()
{
function sayQuote()
{
alert(getQuote());
}
this.charImage = function(whichImage)
{
var image = document.createElement("img");
image.src = "characters/"+whichImage;
image.onclick = sayQuote;
document.body.appendChild(image);
}
}
Basically, the image created in this.charImage is your image object with the onclick property, not the new object surrounding it that you created.
function CharType()
{
function sayQuote()
{
alert(getQuote());
}
this.charImage = function(whichImage)
{
var image = document.createElement("img");
image.src = "characters/"+whichImage;
image.addEventListener("click", this.sayQuote, false);
document.body.appendChild(image);
}
}

Display a spinner as img src attribute is set using FileReader()

I'm using the following code to read a image file and set the result as the src for an image attribute,
document.getElementsByClassName("upload-image"),
function(fileElement) {
var previewElement = document.createElement("img");
previewElement.style.display = "block";
fileElement.parentNode.insertBefore(previewElement, fileElement);
var fileReader = new FileReader();
fileReader.onload = function(event) {
previewElement.src = event.target.result;
};
fileElement.addEventListener("change", updateImagePreview, false);
updateImagePreview();
function updateImagePreview() {
var file = fileElement.files[0];
if (file) {
fileReader.readAsDataURL(file);
} else {
var placeholderSrc = fileElement.getAttribute("data-placeholder");
if (placeholderSrc) {
previewElement.src = placeholderSrc;
} else {
previewElement.removeAttribute("src");
}
}
}
}
This works well, however I know that it takes some time for the actual image src to be set and for the image to be displayed.
Is there anyway for me to detect when the image src is set, and loaded, and ready to be displayed?

Categories

Resources