Functions in JavaScript are not working - javascript

I created a function that could be called once the user focus on the input field; when I tried to apply and test it myself though, no function had been called. I checked for my function, it was well-written; I found no syntax mistakes. I created some tricks to find out what kind of a problem I had had: The outcome is that the same code could be applied with the event "onfocus", whereas the browser totally ignored my function even when I created the inline code within the tag "input"...Taking into notice I am using Firefox, and the test was on Firefox 52.0.2 (32-bit) on Ubuntu Linux..
The testing function code:
(In script element):
function helpMe(){
alert("Help Me!");
};
(Within the input tag):
onfous="help me()" // NOT WORKING!
(Within the input tag):
onfocus="alert('Help Me!')" // WORKING WELL!

you have a typo
<script>
function helpMe(){ alert("Help Me!"); }
</script>
(Within the input tag):
// here helpMe instead of help me ..
<input onfous="helpMe()"/>

Related

Existing Functions aren't Functions?

So I'm working on a project. My functions are working fine, until all of a sudden I click a button that should run download(), but it doesn't. So I open the console, and see this:
TypeError: download is not a function
And I'm confused. I run download() from the console, and it works fine. So I think it might be an issue with onclick (my button has onclick="download()"), so I use JavaScript to add in the click event instead.
$("#download").onclick=download()
Note: $() is a custom jQuery-esque function without using the framework itself. It's worked on a lot of other uses at the same time as this problem.
But that doesn't work either. So I also try using
$("#download").addEventListener("click", download)
That yet again doesn't work. Both times it said that $() was null. So I go out on a limb, and try using
document.getElementById("download").onclick=download()
and the same with addEventListener(). But that gives me a very surprising error message:
TypeError: document.getElementById(...) is null
I've repeated all expressions in the console and found that they aren't null. I don't click the button until the page has been loaded very several seconds.
Here is the pertinent code:
function $(el){switch(el[0]){case"#":return document.getElementById(el.substring(1));break;case".":return document.getElementsByClassName(el.substring(1));break;default:return document.getElementsByTagName(el);break;}}
function download() {
alert("download() executed")
}
// Attempted Scripts:
//$("#download").onclick = download()
//$("#download").addEventListener("click", download)
//document.getElementById("download").onclick = download()
//document.getElementById("download").addEventListener("click", download)
<a class = "nav-link nohighlight" id = "download" onclick = "download()">Download</a>
It feels like my web browser is just trying to ensure I don't run the function. I've tested this on the latest Edge and Firefox. You can see my full page here.
Look at where your script tag is in your HTML: it's above the body. Scripts by default run immediately: when the HTML parser runs across them, it immediately executes the script before moving on to parse the rest of the HTML. So, at the time your script runs, none of your elements have been created yet - so, selecting any element will fail.
Either wrap your entire script in a DOMContentLoaded listener function:
document.addEventListener('DOMContentLoaded', () => {
// put your whole script here
});
Or give your script tag the defer attribute, which directs the parser to run it only once the document has been fully parsed:
<script src = "index.js" defer></script>

JavaScript code is not executed during the runtime of the code, but when I debug it and execute in console, it works

I have a following code:
var e = document.getElementById("overlay");
e.parentNode.removeChild(e);
This code is supposed to remove the DOM element, but it doesn't. So I removed the code and added a breakpoint in its stead and input the code in the console during the pause manually, and it worked (i.e. the element was successfully removed).
This behavior seems rather strange for me, so I wanted to ask, why does it happen and what can I do to inspect this peculiar issue?
Thanks in advance.
EDIT: Thanks for quick replies. Nonetheless, I want to make it perfectly clear that the element #overlay does exist at the time of the execution of the code. Moreover, when I put a debugging breakpoint at that place in the code and execute these two lines of code, it does have an effect on this particular existent element (which it doesn't without debugging).
EDIT 2: I was asked to clarify the code. I execute the following code before the body (part of the queryloader2 plugin, which ensures image preloading):
window.addEventListener('DOMContentLoaded', function() {
new QueryLoader2(document.querySelector("body"), {});
});
No errors present (except for a 404 error because of missing image, which has no impact on Javascript).
As Teemu mentioned #overlay more than likely doesn't exist when the code is run.
For a test.. Try wrapping your code in either of these...
Javscript
window.onload = function () { /*your code*/ };
Jquery (if included)
$(document).ready(function () { /* your code*/ });
You should execute your code after the DOM tree has finished loading. One option is to wrap your code in a function that executes after the DOMContentLoaded event has been fired.
document.addEventListener("DOMContentLoaded", function(event) {
// your code
});
Look at this answer for more information: $(document).ready equivalent without jQuery

`window.open` function dosen't open a popup windo but do vanish the existing html and other code

i have a very simple code which tries to open a popup window but it passes to ruin the whole html and other code.
the code is as follows:
<head>
<script type="text/javascript">
function write(){
/* var w = String(window.offsetWidth),
s = String(window.offsetHeight);*/
var s = window.open('', 'MsgWindow', '_blank');
};
</script>
</head>
<body>
<button onclick="write();" id="writeBtn">Write</button>
</body>
so simple but it dosent do anything!
i don't know what is the problem.
something to note...
when the button is clicked then the screen goes white and all the element disappear
when i saw this in google console then what i saw was shocking all the html code just disappear
i even try to werite in to the variable s like s.document.write('sanmveg') but that dosen't worked
what is the problem?
Rename your function. document.write() is being called instead of your function. Calling document.write() with no parameters causes unexpected behavior like this.
function mywrite() {
var s = window.open('', 'MsgWindow');
};
<button onclick="mywrite();" id="writeBtn">Write</button>
The problem is that your write function isn't being called; instead, document.write is being called. The reason for this is somewhat complex, but the short version is: If you call your function something else that isn't on document (or button elements), like openwindow, it'll work.
So why is document.write being called even though you're calling write(), expecting it to pick up your global write function?
Attribute-based onxyz event handlers are called in a complex scope which is effectively a series of nested with statements, each mixing in different stuff, and one of the things in that mix is the document object.
When you use an attribute-based onxyz event handler on a button as you have in your code, the browser generates a handler for you that looks very roughly like this:
with (document) {
with (theButton) {
handler = function() {
/* This is your attribute text */
write();
/* This is the end of your attribute text */
};
}
}
...and then calls the handler function. So when the browser calls your function, it tries to resolve any free symbols in your function, like write, against the button element first, then if the button doesn't have a write it tries document, and then if document doesn't have it, it tries the global scope.
But of course, document does have a write function, so it gets called instead of your event handler.
You can actually see this in Chrome, or Firefox with Firebug, by doing this:
Create a button with debugger; in the onclick, e.g.:
<button onclick="debugger;">Click Me</button>
Open the page in your browser
Open your dev tools / Firebug
Click the button
At this point, the debugger will pop up, paused on the debugger; statement. Here's what you see in Chrome:
(I don't know what the object is that Chrome inserts between the document and the button; it'll be a Chrome-specific implementation detail.)
And in Firefox+Firebug:
You can see how the function is nested within a couple of with blocks.
If your button were inside a form, the form would be there too, like this:
with (document) {
with (theForm) {
with (theButton) {
handler = function() {
/* This is your attribute text */
write();
/* This is the end of your attribute text */
};
}
}
}
...and so free symbols would attempt to resolve against the form element.
I guess you should fill the arguments in the proper order , which is :
window.open( "URL" , "window name" , "menubar,resizable,width,height,top,left") ;
note that the third argument should be a comma-separated string that specify some properties

Does this not work because I can't use a script in a div?

I am making a website with a program editor, for users to make HTML programs.
I usually test this out by inputting <script> alert("Hi!"); </script> into the body input area, but no alert comes. As you can see from the code, the result is the script ending up inside the div.
So do scripts work in divs? If they do, here's my code (the important part, at least):
This is my script to run when I press the "Run!" button:
<script>
function onclick(){
document.getElementsByTagName("head")["0"].innerHTML += eval(document.getElementById("editorHead").value);
document.getElementById("result").innerHTML = eval(document.getElementById("editorBody").value);
}
</script>
This is the code for the input areas & run button (omitting the text between them & class attributes):
<textarea id="editorHead" rows="20"></textarea>
<textarea id="editorBody" rows="20"></textarea>
<div id="result"></div>
<button onclick="onclick();">Run!</button>
I tried changing the onclick's name to run, and that made the clicking work (before that the button wouldn't turn blue when you clicked it), but that was it.
The asked question is do scripts work in div's. Yes <script></script> tag content executes inline where it appears in the document.
However, it always executes in the document context. Meaning this === document. So to bind to the div's onclick method (the way you handle ui events in javascript) you need to find the div :
document.findElementById("my-div-id").onclick = function(e) {
// do something
};
Note this clobbers the default behavior for the element if there is a default click behavior (like on an a tag)
Also to be more clear on the expected behavior. Do this
<script>
function doSomething() {
alert();
}
</script>
<button onclick="doSomething()">Button</button>

Can I put a script at the bottom of a web page, but call it from the top?

Could this cause potential problems:
<HTML>
<BODY>
...
<INPUT name="xyz" onchange="myFunction();">
...
<SCRIPT>
function myFunction()
{
...
}
</SCRIPT>
</BODY>
</HTML>
What happens if the page loads slowly and the form renders before the script portion at the bottom is loaded? Will a JavaScript error occur if the user enters some text into the INPUT box?
You need to load the script before you can call it. Why don't you change it to something like this:
<input name="xyz" id="myInput">
...
<script>
function myFunction
{
...
}
window.onload = function() {
var myInput = document.getElementById('myInput');
myInput.onchange = myFunction;
}
</script>
This approach allows you to separate your markup and scripting and have all of your js in one place.
JavaScript development has changed over the years.
Not only is your original question being debated, but to go back to the theme of your original question, so is your methodology itself.
I highly recommend reading this short bit on some JavaScript best practices:
http://www.catswhocode.com/blog/best-practices-for-modern-javascript-development.
It works, though it may be a problem if you loaded more HTML and it took longer for the browser to parse your JavaScript at the end. In that case, your function won't be defined and you will get...
myFunction() is not defined
Note you need to add open and closing parenthesis (( & )) after myFunction.
Whilst functions declarations are hoisted, they are only hoisted in their containing script block.
Also, you should really use lowercase tags, it isn't 1998 anymore :) And a doctype also helps, and finally, you should try and remove your event handlers from inline attributes.
The script needs to be defined in the DOM prior to it being executed. If script is at the bottom it needs to be loaded prior to use.

Categories