why document.readystate not working - javascript

<html>
<head>
<script>
if(document.readystate == "interactive"){
alert(document.forms[0].method);
}
</script>
</head>
<body>
<form name="form1" id="form1" method="post">
</form>
<input type="submit" id="submit" name="check" onclick="check()">
</body>
</html>
I also wrote alert() box within the function and triggered with the submit button, in that case the it executed but why isn't it executing in this stage.

First off, there are a several logic/design errors:
It is document.readyState (different capitalization).
While parsing the <head> section, your document will NEVER have document.readyState == "interactive" because the document doesn't switch to that state until it is done parsing the <body>, but by definition it is only parsing the <head> section at this moment.
If you thought your code would somehow fire when the readyState became == "interactive", then that's just not how a simple if statement works. It tests that condition at the moment the code runs and if it's falsey which it is here, then it will never execute.
If you want to run code when the document is loaded and the DOM is ready to modify and interact with, you can see a summary of your options in this answer.
Your options boil down to this:
Move your javascript to a script tag right before the </body> tag and remove the if test you have. At that point in the document parsing, it is safe to interact with any DOM element that was defined before the script.
In modern browsers, add an event listener for the DOMContentLoaded event and run your code when that event fires.
For more general support including older browsers, get a more complete implementation of a function that will notify you when the browser is safe to interact with. You can see such an implementation that works in pretty much all browsers in use today in this other answer.
Use some sort of javascript framework that already offers you a cross browser way to know when the DOM is ready. jQuery offers $(document).ready() as do pretty much all other similar frameworks.
This simplest solution to your code would be this:
<html>
<head>
</head>
<body>
<form name="form1" id="form1" method="post">
<input type="submit" id="submit" name="check" onclick="check()">
</form>
<script>
alert(document.getElementById("form1").method);
</script>
</body>
</html>
Working demo: http://jsfiddle.net/jfriend00/Ka4rL/
P.S. I presume you want your <input> tag inside the form. And, I'd recommend you change to using document.getElementById("form1") rather than forms[0] as this is a much more robust way to program because your code doesn't break if someone adds a new form to the page.

Related

Check Empty Input doesn't work

I'm trying to check if the input is empty with jQuery and the code doesn't work.
That's the code:
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script src="demo.js"></script>
</head>
<body>
<form>
<input type="text" id="name">
<input type="submit" id="btnConnect">
</form>
</body>
</html>
$('#btnConnect').click(function()
{
if($('#name').val() == '')
{
alert('Input is empty!');
}
});
Your problem has two easy solutions.
Basically, you call your script before the rest of the page loads. Your script tries to attach to #btnConnect, which doesn't exist yet.
1). Use document.ready or window.onload. The script will only execute after the whole page loads, so it should work as you meant it to.
2). Place the JS files at the bottom of the document, right before the closing body tag. Most programmers chose to put the scripts at the bottom of the page, because if you have large scripts, the user sees a blank page untill they load.
It works quite well, because most of the time JS is not required until the user begins interacting with the site. It also enables progressive rendering.
For more good JS practices, check out:
JSTheRightWay.org
Hope this helps!

reference to function before its defined

I have read that if you want to make it look like your site loads faster then you should put your javascript at the end of your html file like the following
<html>
<body>
</body>
<script>
//my awesome javascript functions go here because it lets things load faster
//than if it was at the top
</script>
</html>
The problem is when I create buttons or use onChange events that call these functions.
How am I meant to keep my JS at the bottom of the page and have the JS defined for when it reads that the js function will need to be called?
For example
<html>
<body>
<input type="text" onChange="myfunction()"/>
</body>
<script>
function myfunction(){}
</script>
</html>
I did the code in pseudo code-ishly so you wouldn't focus on any of my syntax errors, but more focus on how I am meant to go about this.
When creating the page, it creates the html properly, but gives me a console error saying "myfunction" is not defined.
If I move the script part above the body this works, but it is recommended to keep it last to increase speed in page load.
Just a note I am not using jquery.
I originally thought this was a duplicate (Javascript at the bottom, function call in the body?) but it doesn't seem to answer my problem.
------------------------update----------------------------
using event listeners
<html>
<body>
<input type="text" id="myawesometext"/>
</body>
<script>
function myfunction(){}
element = document.getElementById('myawesometext');
element.addEventListener("onChange", myfunction, false);
</script>
</html>

JavaScript: Error "Object doesn't support this action"

The code for a counter gives an error
Whereas a similar snippet does not
I can't figure out any valid reason...
The line under consideration is:
<input type=button name="but2" value="stop" onClick="window.clearTimeout(ID);">
The complete code is:
<html>
<head>
<script language="JavaScript">
var counter=0;
ID=window.setTimeout("start();",2000);
function start()
{
counter++;
document.forms[0].elements[0].value=counter;
ID=window.setTimeout("start();",2000);
}
</script>
</head>
<body>
<form name="frm1">
<input type="text" name="timer1">
<input type="button" name="but1" value="start" onClick="counter=0; start();">
<input type=button name="but2" value="stop" onClick="window.clearTimeout(ID);">
</form>
</body>
</html>
Use window.start instead of start for the onClick event. It may be that IE doesn't create a window context when you use code instead of a function for the handler.
Everything about that code there is wrong. Please try to avoid that source of tutorials in the future.
Here is a working script: http://jsfiddle.net/teresko/qTJPx/
List of problem with your script:
missing doctype
language="JavaScript" is deprecated
variables ID and counter ended up in global scope
using html to attach events
incorrect use of setTimeout
<script> tag used in <head> when DOM is not ready yet
.. and i don't even want to go over that "similar snippet", it looks like something that by all rights should be dead an buried.
When you add your JavaScript code, it should be right before the closing </body> tag, because at that stage the DOM is already ready, but page has not begun to render yet.
I would strongly suggest for you to get some newer materials for learning JavaScript.
Hi I think in this line your getting the error
ID=window.setTimeout("start();",2000);
Right ?
Put this code
var ID=window.setTimeout("start();",2000);
you'll not get this JavaScript: Error Object doesn't support this action error.

Appending text/elements to a DIV tag

How do I add text/elements to a target element (div) using getElementById (without jquery) when the page loads?
Here's my markup currently:
<html>
<head>
<title>test</title>
<script language="javascript">
/document.getElementById('content').innerHTML = 'Fred Flinstone';
</script>
</head>
<body>
<div id="content">
dssdfs
</div>
</body>
</html>
<script type="text/javascript">
function dothis()
{
document.getElementByID('content').innerHTML = 'Fred Flinstone';
}
</script>
<body onLoad="dothis()">
...
</body>
I think what is happening is that your script is executing before your document is ready. Try placing your javascript in a body load event.
The quickest (although not the best) way to do it is to put your script block towards the end of the HTML file (after the <div> you wish to modify).
The better way to do it is to register for DOM load notification
If you want it to execute after the page loads, then you need to observe the DOM loaded event. You can do that by subscribing to the DOM load event in the script block and then put the code that manipulates the DIV in the event handler.
The tricky part is that different browsers may need slightly different ways to register to be notified when the DOM is loaded (that's were jQuery or a different library becomes useful)
Here's some more information about different ways to register for a callback to be called when the DOM is loaded. The information may be a bit out of date as more modern versions of the popular browsers have become more standards compliant now: http://www.javascriptkit.com/dhtmltutors/domready.shtml

How can I find where a javascript event is initiated?

I have a JS script which created a new Node and inserts it to the HTML page. I am handling DOM mutation events and can capture DOMNodeInserted event. Inside that function I want to find out the source (i.e. in which part of the HTML has the script function been called) and the target (i.e. in which part the node is being added in the HTML page).
I am able to find the target using event.target, but I am not able to find the source of the event.
For example, consider the following pseudocode HTML page:
<html>
<head>
<script>
function test() {
//DOM access
<div_object>.setAttribute("attr", "value");
}
</script>
</head>
<body onload="test()">
<div id="123">
</div>
</body>
</html>
I want my source to be BODY (because that is were the script is initiated), target should be div(123) (because the attribute is added to div_123.
How can I do this?
Sorry, you can't find out what piece of code caused an event to be triggered, they're completely decoupled. You would have to have the triggering code co-operate by storing the values of its own this/event.target in a variable for the triggered code to pick up later.
But then if you have co-operation like that, you wouldn't need DOM Mutation Events.
If you have an event handling layer (as is part of many JS frameworks), you could put the this/target tracking in that layer, so the triggered code could ask “what was the last event that fired, before me?”.
But I'm not convinced this would be worth it. It's usually best to add your own co-operative hooks that communicate between components; you can't generally rely on DOM Mutation Events since they're not globally and completely supported (or indeed supported at all on IE<9).
What about
<html>
<head>
<script>
function test(element) {
//DOM access
element.setAttribute("attr", "value");
}
</script>
</head>
<body onload="test(this)">
<div id="123">
</div>
</body>
</html>
?
Interesting. I had a look here (answered to get formatting)
<html>
<head>
<script>
function test(e) {
if (e) var event=e;
//DOM access
var t="";
for (o in event) t+='<br/>'+o+':'+event[o]
document.getElementById('d123').innerHTML=t;
}
</script>
</head>
<body onload="test(event)">
<div id="d123">
</div>
</body>
</html>

Categories

Resources