+ 1

My code isnt working

It says the Console variable is null so it wont change. heres the js: var a; var b; var c; var d; var e; var Answer; var Console = document.getElementById("Console"); Console.innerHTML="Hi"; html: <!DOCTYPE html> <html> <head> <title>Mind Reading</title> </head> <body> <img src="http://www.mathsbusking.com/images/Mind-Reading-cards.jpg" id="Cards"/> <div id="Console"></div> <input placeholder="Answer Here" id="Input"></input> </body> </html>

6th Jul 2017, 4:24 PM
Joshua
Joshua - avatar
6 Réponses
+ 2
Where is your HTML? Sounds like it didn't locate the element with "Console" id. May be a typo, or maybe you forgot to create the element and set its ID to Console.
6th Jul 2017, 4:24 PM
AgentSmith
+ 2
Gotcha. Your JS is executing before your HTML stuff is ready, so the element doesn't technically exist when the code runes. If you're not using something like jQuery, then put your script at end of HTML. If you're using jQuery, then use the $(document).ready() function.
6th Jul 2017, 4:31 PM
AgentSmith
+ 2
SOLUTION FOR VANILLA JAVASCRIPT. USE $(DOCUMENT).READY() TO CONTAIN YOUR SCRIPT IF YOURE USING jQUERY. HTML: <!DOCTYPE html> <html> <head> <title>Mind Reading</title> </head> <body> <img src="" id="Cards"/> <div id="Console"></div> <input placeholder="Answer Here" id="Input"></input> <script> consoleFunc (); </script> </body> </html> JS: function consoleFunc (){ var a; var b; var c; var d; var e; var Answer; var Console = document.getElementById("Console"); Console.innerHTML="Hi"; }
6th Jul 2017, 4:33 PM
AgentSmith
+ 2
@Netkos Ent wrote: << If you're not using something like jQuery, then put your script at end of HTML. If you're using jQuery, then use the $(document).ready() function. >> Well, what JQuery can do, vanilla JS can also ^^ No need of JQuery just for the .ready() method provided :P No more need of putting script at end of Html (even if it's a working quick workaround fix)... The JQuery $(document).ready() is a shorthand for vanilla JS document.addEventListener('DOMContentLoaded',function() {}); wich could be lazy shorthanded by window.onload = function() {}; So, vanilla Js best solution is to embed the JS code in the function (named or anonymized) assigned to one of the event fired once that DOM is accessible for JS ;P
7th Jul 2017, 8:46 AM
visph
visph - avatar
+ 1
@Netkos Ent Heres the html
6th Jul 2017, 4:30 PM
Joshua
Joshua - avatar
0
<input type="text" placeholder="Answer Here" id="Input"></input>
10th Jul 2017, 12:36 PM
Mrunal Selokar
Mrunal Selokar - avatar