reference error not defined - javascript

create2.innerHTML = create2.innerHTML+ " <img onclick = 'a()' src =' "+ messages[msg].thumb + "' height='90' width='142'> </a> ";
function a (){
}
So I am trying to include an onlick event on image tag so that when it is click a function is called. However, I am getting the following error :
Uncaught ReferenceError: a is not defined onclick
Can somebody please explain why this is happening?

This is why using inline events is a bad idea. Your scope is window, so it looks for the click in the window. When the function is inside another, you have no access to it.
var img = document.createElement("img");
img.src = messages[msg].thumb;
img.style.height = "90px";
img.style.width = "142px";
img.onclick = a; //would be better to use addEventListener()
create2.appendChild(img);

Related

I need to keep element reference to pass on

When the user clicks on <a> tag it calls a function like the following:
<a href="#" onclick="func1(this)">;
This function generates HTML for a modal that needs to reference the first button.
func1(elem) {
html='<div class="modaldiv">' +
'<a href="#" onclick="func2(e.srcElement)">'+
'</div>';
}
When the link inside the modal is clicked, func2() should save text into a data attribute inside the first link, but this is not working, returning:
"Uncaught SyntaxError: Unexpected identifier "
First, don't use inline HTML event handling attributes (onclick, onmouseover, etc.), here's why.
But, your actual problem is that you are not properly declaring your function.
This: func1(elem)
Needs to be this: function func1(elem)
Next, you <a> elements must have some content for someone to see and click on and they must then be closed, which you didn't have.
function func1(elem) {
html='<div class="modaldiv">' + 'click me too'+ '</div>';
document.body.innerHTML += html;
}
click me
If you rework your answer to use modern standards, the proper modern way to do this would be:
// Get references to DOM elements
var a1 = document.getElementById("firstAnchor");
a1.addEventListener("click", func1);
// Callback for first link:
function func1(e) {
// Store original source element
var src = e.srcElement;
// Formally create new elements and configure them
var d = document.createElement("div");
d.classList.add("modaldiv");
var a = document.createElement("a");
a.href = "#";
a.textContent = "Click me too!";
// By hooking up to a wrapper function, we can have that function
// pass arguments to the actual callback function:
a.addEventListener("click", function(){
func2(src);
});
// Add new elements to the document
d.appendChild(a);
document.body.appendChild(d);
}
function func2(firstSrc){
console.log("func2 invoked and e.srcElement from first link is: ", firstSrc);
}
click me

Making a print of a canvas img

I am trying to create a button that when clicked:
opens a canvas img in a new window;
starts the print function;
closes the new page after using JS.
This is what I have so far:
function printCanvas() {
var canvas = document.getElementById("sidstemoned");
var img = canvas.toDataURL("image/png");
var newWin = window.open("");
newWin.document.write('<img src="' + img + '" />');
newWin.print();
newWin.close();
}
$(document).ready(function () {
$('#print_canvas').on('click', printCanvas);
});
Canvas:
<canvas
class='costumor_statistic col-lg-12 col-md-12 col-sm-12'
style='height:350px;'
id='sidstemoned'></canvas>
Button:
<button
class="btn btn-default hidden-print"
id="print_canvas">Print <span class="fa fa-print "></span></button>
The console prints this when I press the button:
Uncaught TypeError: Cannot read property toDataURL of null
at printCanvas
at HTMLButtonElement.
at HTMLButtonElement.dispatch (jquery.min.js:4)
at HTMLButtonElement.r.handle (jquery.min.js:4)
Does it work correct?
function printCanvas() {
var canvas = document.getElementById("canvasname");
var img = canvas.toDataURL("image/png");
var newWin = window.open("");
newWin.document.write('<img src="' + img + '" />');
newWin.print();
newWin.close();
}
UPD: Maybe you try find canvas before it was added to DOM. Try to wrap your onClick handler to $(document).ready
$(document).ready(function(){
$('#print_canvas').on('click', printCanvas);
});
The current problem is that the variable canvas you are using in the printCanvas function is null, which means that when you tried to fetch the element with:
document.getElementById("sidstemoned");
Nothing was found, and therefore in the second line, instead of accessing an element from the DOM, this is happening:
null.toDataURL("image/png");
null does not have a toDataURL property (or function), that is why you get that error. So just make sure that your variable canvas has an element associated to it, i.e. the id sidstemoned you are referencing exists in the document. You can verify that canvas has something by simply consulting its length property:
if(canvas.length !== 0) { /* remaining code goes here */ }
Also, non-directly related, you may want to delete the extra class attribute in the button (the one with a single costumor_statistic).

How do I create objects dynamically with Onclick property in javascript

I have the following code
var eventbar = document.createElement("Div");
eventbar.id = "eventa";
eventbar.className= "event";
eventbar.onclick = 'createpopupdata(this)';
eventbar.innerHTML = "Click here";
document.getElementById("body").appendChild(eventbar);
However when it creates the object inside the HTML my inspector shows no onClick property in the HTML Div that is created. Wondering were I'm going wrong as I have tried multiple ways posted here. (Obviously sans the quotes runs the function immediately).
Edit: I'm wonedering if I have to do something special like create a listener for the object or if there is an easy solution.
You can try something like this:
var eventbar = document.createElement("Div");
eventbar.id = "eventa";
eventbar.className = "event";
eventbar.onclick = createpopupdata.bind(null,eventbar);
eventbar.innerHTML = "Click here";
document.getElementById("body").appendChild(eventbar);
function createpopupdata(el){
alert(el.id)
}
div{
width:50px;
height:50px;
background:#eee;
}
<div id="body"></div>
Your onclick (not onClick it's case-sensitive!) should be the reference to the function (createpopupdata) , not the call to it ('createpopupdata(this)').
First add it to the DOM, then the onclick listener.
function createpopupdata(event) {
var el = event.target;
alert(el.id + " clicked, foo: " + el.dataset.foo + ", bar: " + el.dataset.bar);
}
var eventbar = document.createElement("Div");
eventbar.id = "eventa";
eventbar.dataset.foo = "FOO";
eventbar.dataset.bar = "BAR";
eventbar.className= "event";
eventbar.innerHTML = "Click here";
document.getElementsByTagName("body")[0].appendChild(eventbar);
eventbar.onclick = createpopupdata;
You also have to have <body id="body"> in order to make your version work. I modified it to work in the usual case.
This should work:
eventbar.addEventListener('click', function (){
createpopupdate(this);
}, false);

return image as HTML

trying to add an image to my innerHTML.
Looked at a few prvious Q's
Why does my image not show up when I use Javascript innerHTML to call it?
Javascripts innerHTML not working for images, but works with text?
I cant get it working, in google dev tools throws the error:
Uncaught TypeError: Cannot set property 'innerHTML' of null
with this line:
var newImage = document.getElementById('img').innerHTML = "<img src='images/bg-main.png></img>";
my code looks like:
function showImage() {
var img = document.createElement('image');
//var newImage = document.getElementById('img').innerHTML = "<a href='#'><img src='http://mintywhite.com/wp-content/uploads/2012/10/fond-ecran-wallpaper-image-arriere-plan-hd-29-HD.jpg' border=0/></a>";
var newImage = document.getElementById('img').innerHTML = "<img src='images/bg-main.png></img>";
var div5 = document.createElement('div');
div5.appendChild(newImage);
return div5.innerHTML;
}
I know there are many other methods to display an image, but for the purpose of this exercise I want to return the image as an innerHTML
Try this :
var img = document.createElement("img");
img.setAttribute('src', 'http://www.domain.com/imgSrc');
var div5 = document.createElement('div');
div5.appendChild(newImage);
document.createElement('image') creates a new html tag: <image> i suspect you're trying to add a div and apply the image as inner html. you can fix this code like the following:
function showImage() {
var img = document.createElement('div');
document.body.appendChild(img)
img.innerHTML = "<img src='images/bg-main.png></img>";
}

is it possible to display pictures in a popup.php window, using the src from the main page?

I have a page with pictures, which I want to displayed in a popup.php when clicking on them.
I want the popup window to display a picture(the one I'm clicking on), some text, and a print button.
I'm doing this on the page:
<img src="graphics/picture1.png" width="340" height="200" border="0"/>
In the JS file:
function popup()
{
window.open('popup.php', 'window', 'toolbar=no,location=no,status=no,menubar=no,scrollbars=no,resizable=no,width=520,height=400,left=350,top=100');
}
function showImg(img)
{
var imageSrc = "imageName/imagePath.png";
if(img.src != imageSrc){
img.src = imageSrc;
}
}
And in the popup.php:
<img src="graphics/picture03.png" onload="showImg(this)" />
There should be an obvious way, but I can't find it.
I would think adding the image name and text content to the URL would be the obvious way.
popup.php?image=myImage.gif&text=Say%20something%20witty%20here
Well, you'll want to have your popup contain a holder for the image (which it seems like you already have), but you'll also need to have a holder for your text. Your popup.php should have something like <div id="textHolder"></div> - then your javascript function needs to accept the appropriate text as well as populate it into the textHolder div.
I'm not sure how you're calling these JS functions, or from where - so some of the code might need to change - it should be something to the tune of....
function showImg(img, textHolderObj, text)
{
var imageSrc = "imageName/imagePath.png";
if(img.src != imageSrc){
img.src = imageSrc;
}
textHolderObj.innerHTML= text
}
If is that simple, you could create it:
var win = window.open('', 'win', 'toolbar=no,location=no,status=no,menubar=no,scrollbars=no,resizable=no,width=520,height=400,left=350,top=100');
var img = win.document.createElement('img');
img.src = 'image.png';
img.alt = 'Some text';
var label = win.document.createElement('p');
label.innerHTML = 'Some text';
var button = win.document.createElement('a');
button.href = 'javascript:window.close()';
button.innerHTML = 'Close';
win.document.body.appendChild(img);
win.document.body.appendChild(label);
win.document.body.appendChild(button);
I don't get the question too well. You want to access a function that was defined in the page that opened a popup? You should be able to use opener.showImg(this)
your popup has no idea what image you clicked on. you need to do this:
onClick="popup('imgSrc')"
and in your window reference:
window.open('popup.php?imgSrc='+imgSrc, ...
then... your popup window has to run off of url vars, but php now knows what its looking for:
<?php echo '<img src="' . $_GET["imgSrc"] . '" />'; // this is going to load the image, so you don't need the onLoad()
It is possible to create a new popup window using a variable
top.mydocument=window.open('','window','toolbar=no,location=no,
status=no,menubar=no,scrollbars=no,resizable=no,
width=520,height=400,left=350,top=100');
and then use document.write to write the content:
top.mydocument.document.write(
'<html><head></head>'
+'<body bgcolor=white onLoad="self.focus()">'
+'imageName/imagePath.png'
+'</body></html>'
)
Make sure you close it.
top.mydocument.document.close()

Categories

Resources