/    Sign up×
Community /Pin to ProfileBookmark

Hello Developers, Need Help In That Code

[B][I][FONT=Arial Narrow][SIZE=4][COLOR=”#B22222″]

[CENTER]

Hello Guys ,,
i made that JavaScript Code and it suppose to say a pop message when i click “Click me” Without type anything, and when i type it suppose to write what i typed in the text box, but still don’t work i dont know what is the reason,,,,
i already checked the code in Validator and it say there is no errors,,, hope any one give me a notes.
here is my code below

[/CENTER]

[COLOR=”#0000CD”]

[Code]
<!DOCTYPE html>
<html lang=”en”>
<head>
<meta charset=”UTF-8″/>
<title>JavaScript Test</title>
<script type=”text/javascript”>
function substitute() {
var myValue = document.getElementByID(‘MyTextBox’).value;
if (myValue.length == 0) {
alert(‘Please Enter A Real Value In The Text Box!’);
return;}
var myTitle = document.getElementByID(‘title’);
myTitle.innerHTML = myValue;}
</script>
</head>
<body>
<h1 id=”title”>JavaScript Test</h1>
<input type=”text” id=”MyTextBox” />
<input type=”submit” value=”Click Me” onclick=”substitute()” />
</body>
</html>
[/Code]

[/COLOR][/COLOR][/SIZE][/FONT][/I][/B]

Edited it so I can read it.

to post a comment
JavaScript

42 Comments(s)

Copy linkTweet thisAlerts:
@Kevin2Mar 22.2016 — document.getElementByI[B][COLOR="#FF0000"]d[/COLOR][/B]
Copy linkTweet thisAlerts:
@AhmadMWaddahauthorMar 22.2016 — Thank You Kevin It Really Worked,

after your note,

i am using Sublime Text 3 and i don't know why it type "ID' not "Id"

but i will take care of It from now.

Thank You Again.
Copy linkTweet thisAlerts:
@rootMar 22.2016 — </Code> needs to have [ ] not < > around them to make the code blocks appear...
Copy linkTweet thisAlerts:
@AhmadMWaddahauthorMar 23.2016 — [I][B][FONT=Arial Narrow][SIZE=4][COLOR=#800000][COLOR=#800000]Thank You Host For The Notes, I Am Sorry I Am New Here In The Forum I Know I Have To Read The Regulation For The Forum,[/COLOR][/COLOR][/SIZE][/FONT][/B][/I]
Copy linkTweet thisAlerts:
@Ay__351_eMar 25.2016 — I add this code:

document.getElementByI[COLOR="#0000FF"][B]D[/B][/COLOR] = function(ad){

return document.getElementByI[COLOR="orange"][B]d[/B][/COLOR](ad);



}



I try this code:

<br/>
&lt;!DOCTYPE html&gt;
&lt;html lang="en"&gt;
&lt;head&gt;
&lt;meta charset="UTF-8"/&gt;
&lt;title&gt;JavaScript Test&lt;/title&gt;
&lt;script type="text/javascript"&gt;

document.getElementByID = function(ad){

return document.getElementById(ad);

}

function substitute() {
var myValue = document.getElementByID('MyTextBox').value;
if (myValue.length == 0) {
alert('Please Enter A Real Value In The Text Box!');
return;}
var myTitle = document.getElementByID('title');
myTitle.innerHTML = myValue;}
&lt;/script&gt;
&lt;/head&gt;
&lt;body&gt;
&lt;h1 id="title"&gt;JavaScript Test&lt;/h1&gt;
&lt;input type="text" id="MyTextBox" /&gt;
&lt;input type="submit" value="Click Me" onclick="substitute()" /&gt;
&lt;/body&gt;
&lt;/html&gt;

This code is working.

I am using notapad++

http://www.w3schools.com/html/html_editors.asp
Copy linkTweet thisAlerts:
@meetjoshuapaulMar 25.2016 — did you try this code in browser developer mode ?
Copy linkTweet thisAlerts:
@rootMar 25.2016 — People [U]should learn[/U] to use form elements and DOM elements properly. You should only use the[B] .getElementById() [/B]when no method exists of accessing that property or DOM element.

[code=html]
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8"/>
<title>JavaScript Test</title>
<script type="text/javascript">
function substitute( fm ) {
var myValue = fm.MyTextBox.value;
if (myValue.length == 0) {
alert('Please Enter A Real Value In The Text Box!');
return false;
}else{
document.getElementsByTagName("h1")[0].innerHTML = myValue; // you use this method accessing tags in the DOM
}
return false;
}
</script>
</head>
<body>
<form name="" action="javascript:;" onsubmit="return substitute(this);">

<h1>JavaScript Test</h1>
<input name="MyTextBox" type="text" value="" />
<input name="Submit" type="submit" value="Click Me" />
</form>
</body>
</html>
[/code]
Copy linkTweet thisAlerts:
@Ay__351_eMar 25.2016 — did you try this code in browser developer mode ?[/QUOTE]
I tried this code in Microsoft Edge and Google Chrome Version 49.0.2623.87 m

I look this page:

JS HTML DOM

http://www.w3schools.com/js/js_htmldom_methods.asp

http://www.w3schools.com/js/js_htmldom.asp

http://www.w3schools.com/js/js_htmldom_document.asp

http://www.w3schools.com/js/js_htmldom_elements.asp

http://www.w3schools.com/js/js_htmldom_html.asp

http://www.w3schools.com/js/js_htmldom_css.asp

http://www.w3schools.com/js/js_htmldom_animate.asp

http://www.w3schools.com/js/js_htmldom_events.asp

http://www.w3schools.com/js/js_htmldom_eventlistener.asp

http://www.w3schools.com/js/js_htmldom_navigation.asp

http://www.w3schools.com/js/js_htmldom_nodes.asp

http://www.w3schools.com/js/js_htmldom_nodelist.asp



http://www.w3schools.com/js/js_objects.asp

JS OBJECTS

http://www.w3schools.com/js/js_object_definition.asp

http://www.w3schools.com/js/js_properties.asp

http://www.w3schools.com/js/js_object_methods.asp

http://www.w3schools.com/js/js_object_prototypes.asp


I open this page

http://www.w3schools.com/js/tryit.asp?filename=tryjs_dom_getelementbyid

I paste this code.

<br/>
&lt;!DOCTYPE html&gt;
&lt;html&gt;
&lt;body&gt;

&lt;p id="intro"&gt;Hello World!&lt;/p&gt;

&lt;p&gt;This example demonstrates the &lt;b&gt;getElementById&lt;/b&gt; method!&lt;/p&gt;

&lt;p id="demo"&gt;&lt;/p&gt;

&lt;script&gt;
document.getElementByID = function(ad){
return document.getElementById(ad);
}

var myElement = document.getElementByID("intro");
document.getElementByID("demo").innerHTML =
"The text from the intro paragraph is " + myElement.innerHTML;

&lt;/script&gt;

&lt;/body&gt;
&lt;/html&gt;

I click "see result". This code is working on Microsoft Edge and Google Chrome Version 49.0.2623.87 m
Copy linkTweet thisAlerts:
@rootMar 25.2016 — [code=html]<!DOCTYPE html>
<html>
<body>

<p>Hello World!</p>

<p>This example demonstrates the <b>getElementById</b> method!</p>

<p></p>

<script>
window.onload = function(){
myElement = document.getElementsByTagName("p");
myElement[2].innerHTML = "The text from the intro paragraph is " + myElement[1].innerHTML;
}
</script>

</body>
</html>[/code]
Copy linkTweet thisAlerts:
@PadonakMar 26.2016 — why noone still tried jQuery?
Copy linkTweet thisAlerts:
@rootMar 26.2016 — why noone still tried jQuery?[/QUOTE]

Why load up a library that is a few thousand lines ling and then run a JQuery script that is as many lines as doing it in native JavaScript???

Pointless exercise really, you are not learning anything other than being dependent on a library framework and JavaScript is much better...
Copy linkTweet thisAlerts:
@xelawhoMar 27.2016 — People [U]should learn[/U] to use form elements and DOM elements properly. You should only use the[B] .getElementById() [/B]when no method exists of accessing that property or DOM element.
[/QUOTE]

Why? If a form isn't going to be submitted there's no reason to even give the elements names and being that IDs are (unwisely, imo) hoisted to the global namespace, surely that's the most efficient way of accessing elements?

And what the heck is this -> action="javascript:;" ?
Copy linkTweet thisAlerts:
@rootMar 27.2016 — action="javascript:;" is to stop the form from submitting. It can be changed to whatever script handler is needed but for demo purposes its to stop the form being submitted when a button is clicked that invokes the onsubmit trigger.

the get element method should only be used on elements that typically are hard to access and because they use unique ID's it makes adding many id's a big job in HTML. If a form is used and a submit is used, then you can easily access the content of that form via the document.forms[0] or document.forms.formname.inputname.value

there is an advantage to using the right tool for the job... even in programming.
Copy linkTweet thisAlerts:
@Kevin2Mar 27.2016 — Since this train has already derailed, some highly opinionated thoughts:
[LIST=1]
  • [*] Unless one is submitting form data/input values to be processed on a server [B]<form>[/B] and [B]<input type="submit">[/B] are inappropriate. The form/inputs/script will work and validate either way. Validity and workability are not the point(s). If one is using HTML to state what something *is*, this is not a form, and nothing is being "submitted".

  • [*] Over the last year to year-and-a-half I've become a fan/proponent of [B]querySelector[/B] and [B]querySelectorAll[/B]. Part of the reason is that they use CSS selector syntax for the elements being targeted and I'm a lot better with CSS than JS ? . For a "real" form with name attributes on the form elements you could use [B]querySelector('input[name=myInputName]')[/B] for those elements with unique names, or for radio buttons [B]querySelectorAll('input[name=myRadioButtonName]')[/B] which is the rough equivalent of [B]getElementsByName('myRadioButtonName')[/B]. No IDs needed for the inputs, just name attributes. How is using the DOM different/better (other than my caveat below)?

    there is an advantage to using the right tool for the job... [/QUOTE]

  • [*] With the possible exception of debugging, [B]alert()[/B] should never be used.

  • [/LIST]


    With those thoughts in mind, here's a modified mashup of some previously posted code for demo purposes:

    [code=html]<!DOCTYPE html>
    <html lang="en">
    <head>
    <meta charset="UTF-8">
    <title>JavaScript Test</title>
    <style>
    .oops::after {
    font: bold 1em sans-serif;
    color: red;
    content: 'Please Enter A Real Value In The Text Box!';
    }
    </style>
    </head>
    <body>
    <h1>JavaScript Test</h1>

    <input type="text" placeholder="Change Hello World!">
    <button>Click Me</button>

    <p></p>

    <p>Hello World!</p>

    <script>
    document.querySelector('button').addEventListener('click', function() {
    var a = document.querySelector('input'),
    b = document.querySelectorAll('p');
    if (a.value.length == 0) {
    b[0].className = 'oops';
    }
    else {
    b[0].className = '';
    b[1].innerHTML = a.value;
    a.placeholder = "Change " + b[1].textContent;
    a.value = '';
    }
    });
    </script>
    </body>
    </html>[/code]


    Caveat: If you even care (I don't) IE8- does not recognize CSS3 selectors using querySelector/querySelectorAll. But then those versions also don't recognize getElementsByClassName. Choose your poison.
    Copy linkTweet thisAlerts:
    @xelawhoMar 27.2016 — @Kevin2: agreed on point 1. Thank you for saving me the effort of typing that out ?

    I'm a fan of the querySelectors, too, but only in special cases where the elements are otherwise hard to get at. All the perf tests (like [U]this one[/U]) show good ol' getElementById outperforming querySelectors (and of course jQuery, which just uses querySelectors in the background). The tests also prefer id's over names. See [U]this one[/U].

    But that's all milliseconds and in the OPs case wouldn't make any difference at all. I guess it mostly comes down to preference. Myself, I'm leaning towards getting rid of getElementById completely and just hitting the raw id which is sitting in the global namespace anyway. I'm yet to find a browser that chokes on the following - can anybody?

    [CODE]
    <!DOCTYPE html>
    <html>
    <body>
    <p id="exmp">Hi! I'm some <b>innerHTML!</b></p>
    <script>
    alert(exmp.innerHTML)
    </script>
    </body>
    </html>
    [/CODE]
    Copy linkTweet thisAlerts:
    @Kevin2Mar 28.2016 — @Kevin2: agreed on point 1. Thank you for saving me the effort of typing that out ?[/QUOTE]
    Haha! You are very welcome!

    I'm a fan of the querySelectors, too, but only in special cases where the elements are otherwise hard to get at.[ ... ][/QUOTE]
    Very interesting links! To be a "devil's advocate" some of the lag could be made up if/when the script is reused on another page (assuming it's cached within a separate file). After all, it's about the user and their perception of performance.

    I guess it mostly comes down to preference.[/QUOTE]
    Highly agree! Another reason I like querySelectors is that I only have to remember 2 methods. One for unique or first instances of a match, the other for multiple instances. None of this "do I have to use plural on Element?" junk. No "Dangit, I used 'byName' instead of 'byClassName'." And as I stated in my previous post, I'm much better with CSS so the selectors come naturally to me.

    the global namespace[/QUOTE]
    I barely understand global variables much less the global namespace. ? Told you I was much better at CSS than JavaScript!

    I'm yet to find a browser that chokes on the following - can anybody? [ ... ][/QUOTE]
    Other than the <b> tagset showing in the alert it works on everything I have on Windows 10 (Chrome, Firefox, IE11, Edge, webkit Opera).
    Copy linkTweet thisAlerts:
    @rootMar 28.2016 — Since this train has already derailed, some highly opinionated thoughts:
    [LIST=1]
  • [*] Unless one is submitting form data/input values to be processed on a server [B]<form>[/B] and [B]<input type="submit">[/B] are inappropriate. The form/inputs/script will work and validate either way. Validity and workability are not the point(s). If one is using HTML to state what something *is*, this is not a form, and nothing is being "submitted".

  • [*] Over the last year to year-and-a-half I've become a fan/proponent of [B]querySelector[/B] and [B]querySelectorAll[/B]. Part of the reason is that they use CSS selector syntax for the elements being targeted and I'm a lot better with CSS than JS ? . For a "real" form with name attributes on the form elements you could use [B]querySelector('input[name=myInputName]')[/B] for those elements with unique names, or for radio buttons [B]querySelectorAll('input[name=myRadioButtonName]')[/B] which is the rough equivalent of [B]getElementsByName('myRadioButtonName')[/B]. No IDs needed for the inputs, just name attributes. How is using the DOM different/better (other than my caveat below)?



  • [*] With the possible exception of debugging, [B]alert()[/B] should never be used.

  • [/LIST]


    With those thoughts in mind, here's a modified mashup of some previously posted code for demo purposes:

    [code=html]<!DOCTYPE html>
    <html lang="en">
    <head>
    <meta charset="UTF-8">
    <title>JavaScript Test</title>
    <style>
    .oops::after {
    font: bold 1em sans-serif;
    color: red;
    content: 'Please Enter A Real Value In The Text Box!';
    }
    </style>
    </head>
    <body>
    <h1>JavaScript Test</h1>

    <input type="text" placeholder="Change Hello World!">
    <button>Click Me</button>

    <p></p>

    <p>Hello World!</p>

    <script>
    document.querySelector('button').addEventListener('click', function() {
    var a = document.querySelector('input'),
    b = document.querySelectorAll('p');
    if (a.value.length == 0) {
    b[0].className = 'oops';
    }
    else {
    b[0].className = '';
    b[1].innerHTML = a.value;
    a.placeholder = "Change " + b[1].textContent;
    a.value = '';
    }
    });
    </script>
    </body>
    </html>[/code]


    Caveat: If you even care (I don't) IE8- does not recognize CSS3 selectors using querySelector/querySelectorAll. But then those versions also don't recognize getElementsByClassName. Choose your poison.[/QUOTE]


    what do you think that document.getElementsByClassName() is for CSS and document.getElementsByTagName() is for?

    while a set of form inputs will work without the form tag, it is however, proper HTML to use them and especially one where inputs will be used to submit a form. Most ¬my form isn't submitting¬ problems are solved by adding a <form> tag and adding the minimum tags of name, action, method and when needed enctype are solved by having them.
    Copy linkTweet thisAlerts:
    @xelawhoMar 28.2016 — Other than the <b> tagset showing in the alert it works on everything I have on Windows 10 (Chrome, Firefox, IE11, Edge, webkit Opera).[/QUOTE]

    Well, of course you will see the <b> - we are asking for the innerHTML - if we were asking for the innerText/textContent the <b>'s would not appear

    The caching argument applies across the board - the faster method will get cached faster and still be fastest.

    But it's not just about perception. We're entering a new age of hardware where mobile is starting to lead the pack considerably. We should be developing with the idea in mind that some users will only ever see our pages on their phone because their phone/tablet/phablet/whatever is going to be their only internet-enabled device. And more processing power requirement means more battery drain which for some parts of the world is a real problem.

    So, it's interesting - until the processors and batteries catch up, we're back in a position we were at 30+ years ago - having to think about every byte of code and trying to do things as efficiently as possible. There was a perfect storm there for a while with big desktop processors with fibre optic internet connections piped in, but the landscape has changed again and while those setups do exist and will only improve, we can't assume that every user is enjoying the same conditions as those we are developing under.
    Copy linkTweet thisAlerts:
    @Kevin2Mar 28.2016 — what do you think that document.getElementsByClassName() is for CSS and document.getElementsByTagName() is for?[/QUOTE]
    I know exactly what they're for (and document.getElementsByClassName() can be used for more than just CSS ?). I'm not against them and have a couple of scripts on one site that use them. They're great!! No issues with them at all. I only posed some alternatives. Honestly I don't understand your beef with my alternatives.

    Equivalents:
    querySelectorAll('.myClass') = getElementsByClassName('myClass')
    querySelectorAll('input') = getElementsByTagName('input')

    Your problem with those is ... what?

    OK, my apologies up front for this, but I'm gonna cherry-pick and comment on your post from here on out:
    while a set of form inputs will work without the form tag, it is however, proper HTML to use them[/QUOTE]
    Who says?? Certainly not W3C. As I stated, both ways validate and work. At least with the OP's code.

    and especially one where inputs will be used to submit a form.[/QUOTE]
    But that's restating in reverse exactly what I pointed out in my first point. IF you are NOT submitting data/values to a server, you do NOT have a form and should NOT be using <form> and <input type="submit">. If the reverse is true, by all means use those tags and use them correctly! On the other hand, if the only use of an <input> tag is to change some text in another element via JavaScript AND if the value will not actually be submitted to the server it is NOT A FORM!

    Most ¬my form isn't submitting¬ problems are solved by adding a <form> tag and adding the minimum tags of name, action, method and when needed enctype are solved by having them.[/QUOTE]
    Absolutely and completely true, no arguments. As I have at least tried to imply, WHEN data/values will be processed on the server, use the correct HTML tags and attributes to make that happen.

    Apologies for the capitalization which may appear as shouting. It's there for emphasis only. Consider those words surrounded by <strong> or <em> tags. ?
    Copy linkTweet thisAlerts:
    @rootMar 28.2016 — The same old condition of 30+ years ago, the need to wait for signalling for a completed DOM has never changed.

    The problem is that many people have been taught or told to do coding in a really bad way that is not good coding practice.

    <forms> are a constant problem, unless you actually make a form and access it properly, then people will always be complaining about their form is not working properly when they have not declared one in HTML. I have found this out myself, unless the DOM has a form, the AJAX delivery will not function as expected if you have coded server side to verify the delivery method.

    Coding issues are not just a case of do it this what because it works, its a case of do it this way because its the proper way and especially if you are using server-sides.

    I would like to know where this mindset arose about placement of scripts, they have and always will be an item that is in the <head> tags and if and only if needed in the body or before the end of the <body> tag, people don't seem to realize that it holds DOM up because putting your script in the body or at the end of the document is holding the DOM from completion even though items are available to access ONCE they have been parsed in the browser, it does not mean that they are available across the board UNTIL the DOM has fully loaded... I will let that float for a while.

    There's the proper way to do things and then there's the slapdash way, just because something works doesn't mean that its the right way, if you look at the modes of loading scripts, there was a site I read up about loading scripts and how the DOM loaded and it basically said what I keep on saying that everyone I see coding seems to fly in the face of fact. Unless you have a specific need, your scripts go in the <head> and you "Delay running processes" until the DOM has completed, that is the proper way.
    Copy linkTweet thisAlerts:
    @xelawhoMar 28.2016 — 
    I would like to know where this mindset arose about placement of scripts, they have and always will be an item that is in the <head> tags and if and only if needed in the body or before the end of the <body> tag, people don't seem to realize that it holds DOM up because putting your script in the body or at the end of the document is holding the DOM from completion even though items are available to access ONCE they have been parsed in the browser, it does not mean that they are available across the board UNTIL the DOM has fully loaded... I will let that float for a while.
    [/QUOTE]


    Either you explained that really badly or you have it completely the wrong way around. A "complete" DOM is once all the tags have been parsed, so in that way it makes no difference where the script is.

    The reason we have been putting scripts at the end of the body for the last 20 years is because the body will not parse until the head has been parsed, so if you have an enormous script in the head you must wait for the browser to parse that before it even gets to the body.

    So apart from the convenience of doing away with all that window.onload= silliness, placing the script at the end of the body tag means that the user is at least presented with something on the screen while waiting for the script to load, rather than staring at a big blank nothing and wondering if the page is malfunctioning
    Copy linkTweet thisAlerts:
    @rootMar 28.2016 — The <script> in the footer of a HTML is a DOM element, therfore it has to parse that tag to then pass that to the JavaScrip parser, it is not only the wrong way but the long way of doing things...
    Copy linkTweet thisAlerts:
    @xelawhoMar 28.2016 — yes, it has to parse regardless of if it is in the head or the body. It makes no difference. The only difference is that if you put it in the <head> the user doesn't see the [B]visible[/B] elements (text and graphics) while waiting for the [B]invisible[/B] elements (scripts) to parse.

    Why would you want that? And please don't say tradition. If you're clinging to tradition you're in the wrong industry... or will you be arguing in favor of eval and document.write next?
    Copy linkTweet thisAlerts:
    @rootMar 28.2016 — http://www.growingwiththeweb.com/2014/02/async-vs-defer-attributes.html this explains what happens if the script is in the body, for example. Contrary to popular belief that browses skirt over parsing the DOM, putting the script at the end does not make DOM load any faster.
    Copy linkTweet thisAlerts:
    @xelawhoMar 28.2016 — You have completely misunderstood what that page is saying.
    Copy linkTweet thisAlerts:
    @rootMar 28.2016 — Nope.

    DOM parsing ceases to parse if a script is within any other part of the body of the HTML document, if you defer the loading of the script until the DOM has loaded, meaning that if your script is placed in the body and is deferred, DOM is parsed then JavaScript is loaded and parsed.

    If you go the traditional method, the script is in the head, which is loaded and parsed first, because the script is there in the body, there's no fetching of it and it is ready to go.

    There was another articles about the way DOM is parsed in the parsers and it is basically this: The document is loaded, looked at, items initiated, the DOM is parsed and then rendered and scripts are parsed and rendered as well when encountered.

    Basically the script should reside in the head of the document as it has always traditionally been. You only put code inline or at the end if absolutely needed.
    Copy linkTweet thisAlerts:
    @Kevin2Mar 28.2016 — Well, of course you will see the <b> - we are asking for the innerHTML - if we were asking for the innerText/textContent the <b>'s would not appear[/QUOTE]
    I understand the reason why those tags appear, just didn't know if that was what you intended.

    But it's not just about perception. We're entering a new age of hardware where mobile is starting to lead the pack considerably. We should be developing with the idea in mind that some users will only ever see our pages on their phone because their phone/tablet/phablet/whatever is going to be their only internet-enabled device. And more processing power requirement means more battery drain which for some parts of the world is a real problem.[/QUOTE]
    A very valid point. One of my neighbors, who is about 31-32 years old, is also one of the most "connected" people I know. But until sometime last year his sole source of internet was his phone, on a cell connection. Then he got a good deal on a new phone which came with a cheap tablet. Finally got a home internet connection and a wireless router and at some point got a wifi-enabled printer. Still no "real" computer. That neighbor is the future. If we are not developing for him we're failing.

    Thoughts about perception: If you've been doing this stuff since dinosaurs roamed around (see below) you may remember saving JPEGs as "progressive" and GIFs as "interlaced" (http://blog.codinghorror.com/progressive-image-rendering/ -- see especially the first sentence). In those wild-west days of dialup connections and dot-com bubbles, saving those files thusly would make a web page show a low-res version of the image at first, then as the entire image file loaded the low-res gradually "filled in" with the higher-res image. It gave the perception that at least something -- anything -- was going on. The current argument on this thread is similarly based. As long as a user sees something on his/her screen they're happy to wait, for a short time anyway, for the page to become completely usable. If your page doesn't have "something, anything" appearing within about 2 seconds the feet start tapping, eyes start roaming elsewhere, and clicks away from your page (think Back button) start to happen. Putting a large script ( :::cough::: JQuery!), or reference to said script, in the <head> does exactly that. The same also applies to those of you with 300kb+ of CSS and other files and markup linked/contained within the <head>. The <body> will not load until everything in the <head> loads, therefore no content appears, therefore the perception that nothing is happening. Even Google's PageSpeed recommends not putting "content blocking code" into the <head>.

    This leads to a side comment on so-called "responsive design". With limited battery power, limited processing power, and probably most importantly, limited data allowances, "responsive" should be just as much, or more, about reducing page weight as it is about making content fit a smaller screen.

    until the processors and batteries catch up, we're back in a position we were at 30+ years ago - having to think about every byte of code and trying to do things as efficiently as possible.[/QUOTE]
    As one who started messing around with HTML about 1997 in the era of screaming fast 28.8k dialup modems and actual connection speeds even slower, that's something I still do. Frankly I'm appalled at what many current "designers" and/or "developers" consider an acceptable page weight. Actually I'm also appalled at what even I now consider acceptable!


    At this point, after succeeding wildly at stirring the pot, I'm backing out of here and letting people far smarter and more knowledgeable than me deal with what bubbles to the top of that pot. I've said my piece/peace. Anything else I'd post would only be repeating myself and I've already done that once.
    Copy linkTweet thisAlerts:
    @rootMar 28.2016 — One of my neighbors, who is about 31-32 years old, is also one of the most "connected" people I know. But until sometime last year his sole source of internet was his phone, on a cell connection. Then he got a good deal on a new phone which came with a cheap tablet. Finally got a home internet connection and a wireless router and at some point got a wifi-enabled printer. Still no "real" computer. That neighbor is the future. If we are not developing for him we're failing.[/QUOTE]

    Actually, smart phones don't need developing special sites for them because they can render web pages just fine and dandy. It hacks me off when I visit a site that picks up that my connection is a mobile connection and sends my browser a mobile site when my web browser can render regular HTML and run javascript just fine.

    So theres no were failing him at all, people need to get that out of their heads and if they wish to, ASK if the suer prefers to have a mobile site or regular HTML... THAT is the failing.

    It hacks me off no end when I get served or I am pushed to a mobile set up with no option to have regular HTML.

    Please remember that when you decide that a visitor is a mobile consumer, much nicer to offer a regular HTML page from a mobile site and "Remember" that setting.
    Copy linkTweet thisAlerts:
    @Kevin2Mar 28.2016 — Completely not the point. But probably my fault for being too wordy.
    Copy linkTweet thisAlerts:
    @Kevin2Mar 28.2016 — OK, let me amend my previous post.

    Yes, there are far too many "mobile" site versions which choose to remove content in the misguided thinking that doing so somehow helps those using smaller screen devices. Many news websites can be lumped into that category.

    However, if a developer puts the needs of those users up front, there is no reason a site can't have everything on it that the desktop version of the site does. None! On one site I rebuilt a couple years ago the only difference between desktop and "mobile" versions is that the navigation menu on the left side of the desktop version becomes a slide-in/slide-out menu when you click on a "hamburger menu" icon. That's it! All content is there. I did increase the size of some "tappable" things such as links to make them touchscreen friendly.
    Copy linkTweet thisAlerts:
    @xelawhoMar 29.2016 — Nope.

    DOM parsing ceases to parse if a script is within any other part of the body of the HTML document, if you defer the loading of the script until the DOM has loaded, meaning that if your script is placed in the body and is deferred, DOM is parsed then JavaScript is loaded and parsed.

    If you go the traditional method, the script is in the head, which is loaded and parsed first, because the script is there in the body, there's no fetching of it and it is ready to go.

    There was another articles about the way DOM is parsed in the parsers and it is basically this: The document is loaded, looked at, items initiated, the DOM is parsed and then rendered and scripts are parsed and rendered as well when encountered.

    Basically the script should reside in the head of the document as it has always traditionally been. You only put code inline or at the end if absolutely needed.[/QUOTE]


    No. Read the page again. [B]The HTML file will be parsed until the script file is hit[/B]. So if the script is in the head the parser will remain at the head level until all the script has been parsed, at which point it will move on to the body.

    defer and sync are two newish attributes for a script tag that solve certain problems, particularly those where external scripts depend on other external scripts. That's a whole other discussion, and of course if you add the defer attribute to an external script in the head then you will end up with more or less the same result as putting it at the end of the body with a speed gain because the script will be parsed while the body is being parsed and not execute until the DOM has been constructed. But please don't take this to mean that a script will be defer'd just because it is sitting in the head. In fact the opposite is true.

    It's all very simple and really not worth the extended discussion. You are very welcome to put your scripts wherever you like, but trying to pass off antiquated methods as optimal with the only reason being "that's the way it was always done" is not correct in my view.

    There's a very simple reason for making sites mobile-friendly out of the box and that is that Google now penalizes sites that aren't mobile friendly. Although I do agree with Kevin2 here - responsiveness should be done with CSS, and as little playing around with the HTML and JS as possible.
    Copy linkTweet thisAlerts:
    @rootMar 29.2016 — OK, let me amend my previous post.

    Yes, there are far too many "mobile" site versions which choose to remove content in the misguided thinking that doing so somehow helps those using smaller screen devices. Many news websites can be lumped into that category.

    However, if a developer puts the needs of those users up front, there is no reason a site can't have everything on it that the desktop version of the site does. None! On one site I rebuilt a couple years ago the only difference between desktop and "mobile" versions is that the navigation menu on the left side of the desktop version becomes a slide-in/slide-out menu when you click on a "hamburger menu" icon. That's it! All content is there. I did increase the size of some "tappable" things such as links to make them touchscreen friendly.[/QUOTE]


    Still, ASK the user, I can't use and loathe the mobile configuration as it is not at all helpful, especially when people fail to understand that phones and tablets since version 2 of the droid software can and does render standard HTML just fine.
    Copy linkTweet thisAlerts:
    @xelawhoMar 29.2016 — Geez, you have a hard time listening, don't you? I just said why serving up a non-mobile friendly site and ASKing the user if they want to see the mobile version will penalize you in google search results. You can read more here:

    https://support.google.com/adsense/answer/6196932?hl=en

    Or... er... google for "Mobilegeddon"
    Copy linkTweet thisAlerts:
    @rootMar 29.2016 — No. Read the page again. [B]The HTML file will be parsed until the script file is hit[/B]. So if the script is in the head the parser will remain at the head level until all the script has been parsed, at which point it will move on to the body.

    defer and sync are two newish attributes for a script tag that solve certain problems, particularly those where external scripts depend on other external scripts. That's a whole other discussion, and of course if you add the defer attribute to an external script in the head then you will end up with more or less the same result as putting it at the end of the body with a speed gain because the script will be parsed while the body is being parsed and not execute until the DOM has been constructed. But please don't take this to mean that a script will be defer'd just because it is sitting in the head. In fact the opposite is true.

    It's all very simple and really not worth the extended discussion. You are very welcome to put your scripts wherever you like, but trying to pass off antiquated methods as optimal with the only reason being "that's the way it was always done" is not correct in my view.

    There's a very simple reason for making sites mobile-friendly out of the box and that is that Google now penalizes sites that aren't mobile friendly. Although I do agree with Kevin2 here - responsiveness should be done with CSS, and as little playing around with the HTML and JS as possible.[/QUOTE]


    If you have a <script src="blah.js><script> that is true, however, we are talking about a document thats loaded and being parsed so the script between <script>var something = "Yay!";</script> will be parsed and not needing to be loaded.

    The link I posted was to demonstrate the loading options for newer scripts, the same people did an article about page loading... which is what I am referring to but can't find.

    What the article was saying was that putting scripts in the body doesn't help parsing as scripts have traditionally spent their lives in the <head> of the HTML and you should only put them in the body or at the end if you absolutely have to.
    Copy linkTweet thisAlerts:
    @xelawhoMar 29.2016 — It works the same. Html parsing will pause while the script tag contents are parsed. Because a script tag (and its contents) are just html at that point.

    Head or body, no difference. The only difference is if the user is left looking at a blank page while it happens.

    I reserve judgment on the article that supposedly claims otherwise until you produce it.

    For someone whose sig line encourages thinking outside of the box you seem awfully fond of the word "tradition"...
    Copy linkTweet thisAlerts:
    @rootMar 30.2016 — Theres doing it right and then theres doing it wrong, thinking out the box has nothing to do with tradition but doing things right can exist with thinking out the box ? and my point seems to be completely missed over script placement. You will find that everything I have said holds water too. I don't open my mouth unless I am 100% sure of things and its always the way when people take things I say out of context or haven't grasped what I am referring to, I gave that link as an example as it was the only one I could find in a hurry. There is an over use and over dependency for getElementsById when the same can be achieved using a form properly.

    If you put the script in the head, your code is ready before the document finishes loading and if you write one in the head, if the DOM fails to load properly, your script will be usable if you code it to signal that the page failed and attempt a page reload. if its in the body or at the end of the HTML page and theres a network error, then the page script fails. That is the most common issue I experience, failed sites because cod is elsewhere in the page that for whatever reason didn't complete.
    Copy linkTweet thisAlerts:
    @xelawhoMar 30.2016 — Sounds to me like you are making provisions for an edge case that is somewhat rare (if I understand it, when the head loads but the body fails to).

    Regardless, I'd like to see an example of a script that will be usable if you code it to signal that the page failed and attempt a page reload - could you post some code?
    Copy linkTweet thisAlerts:
    @rootMar 31.2016 — Its simple enough as google can provide you with this information ?
    Copy linkTweet thisAlerts:
    @xelawhoMar 31.2016 — This from the guy who just posted some other page 'cos he couldn't find the one he was talking about. :eek:

    Uh huh.
    Copy linkTweet thisAlerts:
    @jeff122Mar 31.2016 — Hi, i am having a crisis. I am stuck with my code, my task is to [COLOR=#333333]basically everytime the user gets a correct answer it should give them a +2 and everytime they get it wrong it will give them -1. i also need to change the background colour so if the user gets below 5 questions right then the background color changes red and if he gets above 5 it turns green. How do i do that? in which section of the code i write that? Please help me, someone i feel useless right now.[/COLOR]

    this is my code:

    <textarea>

    <!DOCTYPE html>

    <head>

    <title>Game Quiz</title>

    <style>

    div#test{ border-style: solid; padding:30px 50px 50px 50px; background-color: lightblue;}</style>

    </style>

    </head>

    <body>

    <div>

    <h2 id="test_status">Math Quiz</h2>

    <h3 id="timeleft">Time left</h3>

    </div>

    <div id="test"></div>


    <script>

    var myVar;

    function startTimer() {

    myVar = setInterval(function(){myTimer()},1000);

    timelimit = maxtimelimit;

    }


    function myTimer() {

    if (timelimit > 0) {

    curmin=Math.floor(timelimit/60);

    cursec=timelimit%60;

    if (curmin!=0) { curtime=curmin+" minutes and "+cursec+" seconds left"; }

    else { curtime=cursec+" seconds left"; }

    $_('timeleft').innerHTML = curtime;

    } else {

    $_
    ('timeleft').innerHTML = timelimit+' - Out of Time - no credit given for answer';

    // clearInterval(myVar);

    checkAnswer();

    }

    timelimit--;

    }


    var pos = 0, posn, choice, correct = 0, rscore = 0;

    var maxtimelimit = 150, timelimit = maxtimelimit; // 20 seconds per question


    var questions = [

    [ "What was the first console created by Sony?", "Psone", "Play Station", "Ps Vita", "B" ],

    [ "From the option below who is the fastest video game characters?", "Mario", "Master Chief", "Sonic", "C" ],

    [ "What company created FIFA?", "Electronic Arts(EA Sports)", "Microsoft", "Rockstars", "A" ],

    [ "What company invented the game GTA?", "Electronic Arts(EA Sports)", "Sony", "Rockstars", "C" ],

    [ "What is the current GTA game?", "GTA San Andreas", "Grand Theft Auto", "Grand Theft Auto V", "C" ],

    [ "What is the current Xbox Console?", "Xbox one", "Xbox 360", "Xbox 720", "A" ],

    [ "What was Nintendos first try at an arcade game?", "Donkey Kong", "Donkey Kong Jr.", "Final Fantasy", "A" ],

    [ "Which company created Tails?", "Rare", "Sega", "Microsoft", "B" ],

    [ "Dhaslim is a character in which game?", "Mortal Kombat", "Fight Night", "Street Fighter", "C" ],

    [ "What gaming console has the highest number of unit sold of all time?", "Wii", "Play Station 2", "xBox 360", "B" ]

    ];


    var questionOrder = [];

    var maxNumberOfQuestions = questions.length; // do NOT make BIGGER than number of 'questions' array

    // var maxNumberOfQuestions = 5; // do NOT make BIGGER than number of 'questions.length' array

    var maxNumberToDisplay = 10;


    function setQuestionOrder() {

    questionOrder.length = 0;

    for (var i=0; i<maxNumberOfQuestions; i++) { questionOrder.push(i); }

    questionOrder.sort(randOrd); // alert(questionOrder); // shuffle display order

    pos = 0; posn = questionOrder[pos];

    }


    function $_(IDS) { return document.getElementById(IDS); }

    function randOrd() { return (Math.round(Math.random())-0.5); }

    function renderResults(){

    var test = $_
    ("test");

    test.innerHTML = "<h2>You got "+correct+" of "+maxNumberToDisplay +" questions correct <br> <br>" +"Out of the total 100% percent " + " you got " + (correct/rscore*100).toFixed(0)+"% " + "You spent "+ "</h2>";

    $_("test_status").innerHTML = "Test Completed";

    $_
    ('timeleft').innerHTML = '';

    test.innerHTML += '<button onclick="location.reload()">Re-test</a> ';

    setQuestionOrder();

    correct = 0;

    clearInterval(myVar);

    return false;

    }

    function renderQuestion() {

    var test = $_("test");

    $_
    ("test_status").innerHTML = "Question "+(pos+1)+" of "+maxNumberToDisplay;

    if (rscore != 0) { $_("test_status").innerHTML += '<br>Currently: '+(correct/rscore*
    100).toFixed(0)+'% correct' }

    var question = questions[posn][0];

    var chA = questions[posn][1];

    var chB = questions[posn][2];

    var chC = questions[posn][3];

    test.innerHTML = "<h3>"+question+"</h3>";

    test.innerHTML += "<label><input type='radio' name='choices' value='A'> "+chA+"</label><br>";

    test.innerHTML += "<label><input type='radio' name='choices' value='B'> "+chB+"</label><br>";

    test.innerHTML += "<label><input type='radio' name='choices' value='C'> "+chC+"</label><br><br>";

    test.innerHTML += "<button onclick='checkAnswer()'>Submit Answer</button>";

    // setupTimer(); // for indivisible timer for each question

    }

    function setupTimer() {

    timelimit = maxtimelimit;

    clearInterval(myVar);

    startTimer();

    }


    function checkAnswer(){

    var choices = document.getElementsByName("choices");

    for (var i=0; i<choices.length; i++) {

    if (choices[i].checked) { choice = choices[i].value; }

    }

    rscore++;

    if (choice == questions[posn][4] && timelimit > 0) { correct++; }

    pos++; posn = questionOrder[pos];

    if (pos < questions.length) { renderQuestion();

    }

    else { renderResults(); }

    }









    window.onload = function() {

    setQuestionOrder();

    renderQuestion();

    setupTimer(); // for total time for entire quiz

    }

    </script>





    </body>

    </html>

    </textarea>
    Copy linkTweet thisAlerts:
    @jeff122Mar 31.2016 — Ignore the <textarea> i thought thats how you create the box where people inserts their code in
    Copy linkTweet thisAlerts:
    @rootApr 04.2016 — Please wrap code blocks in forum code tags, see my signature, also see my signature for correct place to post (JQuery and other frameworks like $_() )
    ×

    Success!

    Help @AhmadMWaddah spread the word by sharing this article on Twitter...

    Tweet This
    Sign in
    Forgot password?
    Sign in with TwitchSign in with GithubCreate Account
    about: ({
    version: 0.1.9 BETA 5.18,
    whats_new: community page,
    up_next: more Davinci•003 tasks,
    coming_soon: events calendar,
    social: @webDeveloperHQ
    });

    legal: ({
    terms: of use,
    privacy: policy
    });
    changelog: (
    version: 0.1.9,
    notes: added community page

    version: 0.1.8,
    notes: added Davinci•003

    version: 0.1.7,
    notes: upvote answers to bounties

    version: 0.1.6,
    notes: article editor refresh
    )...
    recent_tips: (
    tipper: @AriseFacilitySolutions09,
    tipped: article
    amount: 1000 SATS,

    tipper: @Yussuf4331,
    tipped: article
    amount: 1000 SATS,

    tipper: @darkwebsites540,
    tipped: article
    amount: 10 SATS,
    )...