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);
}
}
Related
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)};
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
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 .
I have some divs that has a class named class='tweetCon'
each containing 1 image and I want to check if the image source exist or not so if it is available I dont do anything but if not I will change the image source with an appropriate image my code is as follow:
$('.tweetimgcon').children('img').each(function () {
imageExists($(this).attr("src"), function (exists) {
if (exists == true) {
} else {
$(this).attr("src", "https://pbs.twimg.com/profile_images/2284174758/v65oai7fxn47qv9nectx.png");
}
}, function () {
});
});
and also imageExists() is as follow:
function imageExists(url, callback,callback2) {
var img = new Image();
img.onload = function() { callback(true);callback2(); };
img.onerror = function() { callback(false);callback2(); };
img.src = url;
}
now the problem is that the src for the images that are not available does not set properly though when I check the src of those images by console.log it shows that they are properly set but it is not shown and when I use inspect element of chrome I can see that src is not set . Can anyone help me?
The point is $(this) doesn't point to your object, because you call $(this) inside your imgExists callback function but NOT the jQuery callback function each, so the this object doesn't point to your original img tag!
The solution should be save the object reference first, try the below:
$('.tweetimgcon').children('img').each(function () {
var _this = $(this);
imageExists($(this).attr("src"), function (exists) {
if (exists == true) {
} else {
_this.attr("src", "https://pbs.twimg.com/profile_images/2284174758/v65oai7fxn47qv9nectx.png");
}
}, function () {
});
});
Just for a little tip for a better callback function use call.
function imageExists(url, cb, ecb) {
var img = new Image();
img.onload = function() { cb.call(img,true,url); };
img.onerror = function() { ecb.call(img,false,url); };
img.src = url;
}
I added img as the first argument and that will then be your this keyword instead of window.
Testing Bin
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?