Uncaught ReferenceError: function is not defined [duplicate] - javascript

This question already has answers here:
Why isn't my JavaScript working in JSFiddle?
(7 answers)
Closed 9 years ago.
Im doing a simple jquery function using rangy script but im not being able to get it work, it says the error above.
<div onclick="cmon('cenas');"> cenas </div>
<textarea class="guides_chapters_textarea" id="textarea" name="gmessage" rows="7" cols="25"> Insert starting items here</textarea>
Javascript:
function cmon(text){
$("#textarea").insertText(text, 0, "collapseToEnd");
}
Jsfiddle: http://jsfiddle.net/VmhMM/

To get your example working, there is a few things you can do. Strictly speaking, there is actually nothing wrong with your code. The fault lies in how your code is being used/added to the page.
Here is one method of getting your code to work, by setting the function on the window object directly.
window.cmon = function cmon(text){
$("#textarea").insertText(text, 0, "collapseToEnd");
}
Another method mentioned by #elclanrs in the comment on the question (which is a better option in this case) points to the setting in the left panel of the JSFiddle to do with where your function is being run. By default, it adds it to the onLoad event which makes the function out of scope as it is being defined inside the event. Here is exactly what JSFiddle did to your code:
$(window).load(function(){
function cmon(text){
$("#textarea").insertText(text, 0, "collapseToEnd");
}
});
The concept that is going on is known as closures. So when you define a function, any variables or other functions defined inside of that are not accessible externally. If you set the variable on a global object or any other object outside the scope of your newly defined function (like I did in the example I linked), you can access what you defined outside of the closure.

You must use (no wrap in head) at the left side. This means you must load this script between tags. But If you still want to use it onload then:
<div id="cmon"> cenas </div>
<textarea class="guides_chapters_textarea" id="textarea" name="gmessage" rows="7" cols="25"> Insert starting items here</textarea>
<script>
$("#cmon").click(function(){
cmon($(this).text());
});
function cmon(text){
$("#textarea").insertText(text, 0, "collapseToEnd");
}
</script>
Here is the solution : http://jsfiddle.net/VmhMM/2/

Related

How do I set specific key for keydown event listener? [duplicate]

I am trying to use an HTML button to call a JavaScript function.
Here's the code:
<input type="button" value="Capacity Chart" onclick="CapacityChart();">
It doesn't seem to work correctly though. Is there a better way to do this?
Here is the link:http://projectpath.ideapeoplesite.com/bendel/toolscalculators.html click on the capacity tab in the bottom left section. The button should generate an alert if the values are not changed and should produce a chart if you enter values.
There are a few ways to handle events with HTML/DOM. There's no real right or wrong way but different ways are useful in different situations.
1: There's defining it in the HTML:
<input id="clickMe" type="button" value="clickme" onclick="doFunction();" />
2: There's adding it to the DOM property for the event in Javascript:
//- Using a function pointer:
document.getElementById("clickMe").onclick = doFunction;
//- Using an anonymous function:
document.getElementById("clickMe").onclick = function () { alert('hello!'); };
3: And there's attaching a function to the event handler using Javascript:
var el = document.getElementById("clickMe");
if (el.addEventListener)
el.addEventListener("click", doFunction, false);
else if (el.attachEvent)
el.attachEvent('onclick', doFunction);
Both the second and third methods allow for inline/anonymous functions and both must be declared after the element has been parsed from the document. The first method isn't valid XHTML because the onclick attribute isn't in the XHTML specification.
The 1st and 2nd methods are mutually exclusive, meaning using one (the 2nd) will override the other (the 1st). The 3rd method will allow you to attach as many functions as you like to the same event handler, even if the 1st or 2nd method has been used too.
Most likely, the problem lies somewhere in your CapacityChart() function. After visiting your link and running your script, the CapacityChart() function runs and the two popups are opened (one is closed as per the script). Where you have the following line:
CapacityWindow.document.write(s);
Try the following instead:
CapacityWindow.document.open("text/html");
CapacityWindow.document.write(s);
CapacityWindow.document.close();
EDIT
When I saw your code I thought you were writing it specifically for IE. As others have mentioned you will need to replace references to document.all with document.getElementById. However, you will still have the task of fixing the script after this so I would recommend getting it working in at least IE first as any mistakes you make changing the code to work cross browser could cause even more confusion. Once it's working in IE it will be easier to tell if it's working in other browsers whilst you're updating the code.
I would say it would be better to add the javascript in an un-obtrusive manner...
if using jQuery you could do something like:
<script>
$(document).ready(function(){
$('#MyButton').click(function(){
CapacityChart();
});
});
</script>
<input type="button" value="Capacity Chart" id="MyButton" >
Your HTML and the way you call the function from the button look correct.
The problem appears to be in the CapacityCount function. I'm getting this error in my console on Firefox 3.5: "document.all is undefined" on line 759 of bendelcorp.js.
Edit:
Looks like document.all is an IE-only thing and is a nonstandard way of accessing the DOM. If you use document.getElementById(), it should probably work. Example: document.getElementById("RUnits").value instead of document.all.Capacity.RUnits.value
This looks correct. I guess you defined your function either with a different name or in a context which isn't visible to the button. Please add some code
Just so you know, the semicolon(;) is not supposed to be there in the button when you call the function.
So it should just look like this: onclick="CapacityChart()"
then it all should work :)
One major problem you have is that you're using browser sniffing for no good reason:
if(navigator.appName == 'Netscape')
{
vesdiameter = document.forms['Volume'].elements['VesDiameter'].value;
// more stuff snipped
}
else
{
vesdiameter = eval(document.all.Volume.VesDiameter.value);
// more stuff snipped
}
I'm on Chrome, so navigator.appName won't be Netscape. Does Chrome support document.all? Maybe, but then again maybe not. And what about other browsers?
The version of the code on the Netscape branch should work on any browser right the way back to Netscape Navigator 2 from 1996, so you should probably just stick with that... except that it won't work (or isn't guaranteed to work) because you haven't specified a name attribute on the input elements, so they won't be added to the form's elements array as named elements:
<input type="text" id="VesDiameter" value="0" size="10" onKeyUp="CalcVolume();">
Either give them a name and use the elements array, or (better) use
var vesdiameter = document.getElementById("VesDiameter").value;
which will work on all modern browsers - no branching necessary. Just to be on the safe side, replace that sniffing for a browser version greater than or equal to 4 with a check for getElementById support:
if (document.getElementById) { // NB: no brackets; we're testing for existence of the method, not executing it
// do stuff...
}
You probably want to validate your input as well; something like
var vesdiameter = parseFloat(document.getElementById("VesDiameter").value);
if (isNaN(vesdiameter)) {
alert("Diameter should be numeric");
return;
}
would help.
Your code is failing on this line:
var RUnits = Math.abs(document.all.Capacity.RUnits.value);
i tried stepping though it with firebug and it fails there. that should help you figure out the problem.
you have jquery referenced. you might as well use it in all these functions. it'll clean up your code significantly.
I have an intelligent function-call-backing button code:
<br>
<p id="demo"></p><h2>Intelligent Button:</h2><i>Note: Try pressing a key after clicking.</i><br>
<button id="button" shiftKey="getElementById('button').innerHTML=('You're pressing shift, aren't you?')" onscroll="getElementById('button').innerHTML=('Don't Leave me!')" onkeydown="getElementById('button').innerHTML=('Why are you pressing keys?')" onmouseout="getElementById('button').innerHTML=('Whatever, it is gone.. maybe')" onmouseover="getElementById('button').innerHTML=('Something Is Hovering Over Me.. again')" onclick="getElementById('button').innerHTML=('I was clicked, I think')">Ahhhh</button>

Why is my JavaScript code showing different behavior on jsfiddle? [duplicate]

This question already has answers here:
Why isn't my JavaScript working in JSFiddle?
(7 answers)
Closed 5 years ago.
I am new to javaScript, that's why I am unable to find the real root cause for it.
This simple code is to append the value of a button into a paragraph every time i press it; however if the paragraph contains only a zero then it should replace the value, not append.
This is working fine on all of my browsers and also when running the snippet on stackoverflow .
Not working at all on https://jsfiddle.net/
Can you please tell me why I am facing this problem and what changes should I make to make it work on every platform?
function append(a){
if (document.getElementById('text1').innerHTML == '0')
document.getElementById('text1').innerHTML = document.getElementById(a).value;
else
document.getElementById('text1').innerHTML += document.getElementById(a).value;
};
<div>
<p id='text1' style="border-style: inset;
width:200px;
display:inline-block;">0</p><br>
<button value="1" id='a1' onclick="append(this.id)">1</button></div>
By default JSFiddle wraps your JavaScript in an onload function. This means that function append is only defined in that scope, and is not made global.
Global variables (and functions) are generally considered bad practice, as are inline event handlers.
Try:
document.getElementById('a1').onclick = append;
Then, inside function append, simply refer to this.value.

Why is using "javascript: <code>" bad? [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Do you ever need to specify javascript: in an onclick?
To execute JavaScript on a DOM event, you could use something like this:
<div onclick="alert('Alert');">Alert</div>​
Something like this seems to work as well:
<div onclick="javascript: alert('Alert');">Alert</div>​
However, I've heard that the second example is "bad" and that the first example should be used over the second.
Is this bad? If so, why is this bad? What is the difference between alert('Alert') and javascript: alert('Alert')?
What about using it in <a> tags (if it is any different)?
Alert
Edit: To clarify, I am asking about the javascript: part specifically, and not how I have inline JavaScript mixed in with my markup. Sorry about the confusion.
Oh the wonderful confusing world of JavaScript. The code you posted probably doesn't do what most programmers think it's doing.
There is a difference between each of the following lines:
<a onclick="alert('Hello World!')"...>example</a> //V1
<a href="javascript: alert('Hello World!')"...>example</a> //V2
<a onclick="javascript: alert('Hello World')"...>example</a> //V3
although they all will alert Hello World!.
The first (V1) has an inline click event bound via the [onclick] attribute. It may also contain an [href] attribute that navigates to another location after the [onclick] attribute has executed, or any number of other click events bound in the code, assuming the default behavior hasn't been prevented.
The second (V2) has an executable javascript: url set as the [href] attribute. It might also contain an [onclick] attribute or other click events bound in external scripts.
The first and second examples (V1 & V2) have identical code executed, which is:
alert('Hello World!')
The third example (V3) has an inline click event bound via the [onclick] attribute, just like V1, however the code being executed is different. The executed code is:
javascript: alert('Hello World')
Although it looks like a javascript: url, it's actually just using a label in javascript.
Labels in JavaScript are useful for skipping out of nested loops, as in the following example code:
label: for (i = 0; i < 5; i++) { //labeled line
for (j = 0; j < 5; j++) {
console.log(i, j);
if (i === 2 && j === 3) {
break label; //this jumps out of both for loops
}
}
}
In most inline JavaScript, it's misused because the author doesn't understand the difference between the three formats.
Why is using javascript: <code> bad?
That's a leading question. It assumes that using javascript: <code> is bad.
javascript: <code> isn't bad. It's a tool. Tools aren't inherently good or bad, only the people using the tools are. You wouldn't call a hammer "bad", even if someone used it as a weapon.
javascript: <code> has some nice uses. You shouldn't use it for most cases because it's the wrong tool for the job, however if you're writing a bookmarklet, you'd be required to use the javascript: <code> format.
Additionally, there are a few niche contexts where it could make sense to leave javascript inline. An example of this would be to add a simple print button to the page:
Print
Although even this example could be easily replaced by a class and externalizing the javascript:
Print
<script>
//jQuery used for brevity
$(document).on('click', '.print', function () {
window.print();
return false;
});
</script>
There's no real problem with using the javascript: labels. It's just considered bad style most of the time.
an onclick-handler already is JavaScript, so repeating that is just senseless, redundant information (in fact, it's chaging the code thats executed by adding a label named javascript - but in most cases this shouldn't have any effect).
JavaScript code in a href attribute would be placed more appropriately in an onclick handler, so you can use the href to provide a link for users that have JavaScript disabled. This is called Progressive Enhancement.
For more detailed information, you may want to take a look at this great blog-post about "The useless javascript: pseudo-protocol"

Protovis JavaScript doesn't work in dropdownlist onchange event

I noticed the following problem. When I remove either block of code, either one works well but when I put them together, only one of it worked.
I am trying to call a method from a dropdownlist using the onchange event but its fails when my code for Protovis/JavaScript is added.
<script type="text/javascript">
function getDate()
{
alert("dateValue");
}
</script>
<script type="text/javascript+protovis">
function Colour(color) {
new pv.Panel()
.width(12)
.height(20)
.anchor("center").add(pv.Dot)
.strokeStyle(null)
.fillStyle(color)
.radius(5)
.root.render();
}
</script>
<select name="mydropdown" onchange="getDate(this)">
<option value="None">Select Date</option>
</select>
I want to get both of them to work properly.
The above code works as expected here: http://jsfiddle.net/nrabinowitz/NAEku/
But, when I actually call the Colour() function elsewhere on the page, there's an error, and my guess is that's the root of your problem. The issue here is that when you use a script block with type="text/javascript+protovis", it gets eval'd by the Protovis library after the page is fully loaded - so any functions or variables you define in a javascript+protovis block won't be available in the global scope for normal script blocks further down the page.
So my guess is that you're trying to call Colour() before the Protovis block has been evaluated. The quick fix for this example, since you're not using any special Protovis syntax, is to just change the script block to type="text/javascript", which will cause it to be evaluated normally.
Updated, functional jsFiddle here: http://jsfiddle.net/nrabinowitz/NAEku/1/

JavaScript: get the current executing <script> node? [duplicate]

This question already has answers here:
How may I reference the script tag that loaded the currently-executing script?
(14 answers)
Closed 8 years ago.
I need to know if it is possible to obtain the current execution node?
Example:
..html
<script id="x">
console.log(document.currentNode.id); // << this must return "x"
</script>
..html
Thanks!
Modern browsers support a standard property on document object that points to the current script node:
https://developer.mozilla.org/en-US/docs/DOM/document.currentScript
<script id="x">
console.log(document.currentScript.id); // << this must return "x"
</script>
I don't know for 100% sure, but the collection of script tags returned by document.getElementsByTagName('script') should not include the script tags that are below the presently executing <script>. In other words, I think that this should work:
var arrScripts = document.getElementsByTagName('script');
var strScriptTagId = arrScripts[arrScripts.length - 1].id;
This will only work for scripts that are executing as the page loads. If this executes in a deferred script or as part of a page-load event, it will likely always report the last <script> in the completely rendered page. Note that the id tag is not a valid attribute for <script>, so your page won't likely validate. If you have any external scripts that write script tags (for example, third party ads), I think the code will be unpredictable. I played with this idea a couple years ago and the results were unsatisfactory.
Andrews Answer already has been a good idea but I experienced all the issues mentioned.
This is why I choosed a different approach which works well for IE,FF and Chrome.
Simply executing the script in an onload event of an image. Defining a transparent 1pixel gif inline and you will receive "this" when it fires.
This example is used to change DIV content dynamically while rendering. My target is to fill the div with a different innerHTML created by an browser based xsl rendering (not shown here).
For sure you even can load any image from the internet so it must not be inline. And the big benefit: the image and its event are replacing themself with the new content so even the image will disappear. The "div" even does not need any "id" assignment.
<div id="demo">
empty
<img onLoad="changeNodeOnTheFly(this,'hurra');void(0);" src="data:image/gif;base64,R0lGODlhAQABAIAAAP///wAAACH5BAEAAAAALAAAAAABAAEAAAICRAEAOw=="/>
</div>
The script:
<script>
function changeNodeOnTheFly(ele, text)
{
ele.parentNode.innerHTML=text;
}
</script>
BR
Heiko
Use document.write to find your position:
<script data-foo="bar">
var id = 'placeholder-' + Math.floor(Math.random() * 1e10)
document.write('<div id=' + id + '></div>')
var placeholder = document.getElementById(id)
var script = placeholder.previousSibling
placeholder.parentNode.removeChild(placeholder)
// "bar" is written to the document
document.write(script.getAttribute('data-foo'))
</script>
Why not use:
<script id="x">
console.log(document.getElementById("x").id);
</script>

Categories

Resources