I am new to Javascript. I ran into the problem of global variables. I cannot understand why global variables do not work, as the code looks fine. Help me solve this problem. I will briefly explain the code first. I have text on the page that changes when the text field is clicked. When I define the variables inside the function body, the code starts working fine. When these variables are defined globally, as in the following code, the console displays this error: the variable is not defined. Here is my code:
<!DOCTYPE HTML> <html> <head> <title>Span to Text Box - Demo - DOM</title> <script type="text/javascript" language="javascript"> var textNode = document.getElementById('text'); var textValue = textNode.firstChild.nodeValue; var textboxNode = document.getElementById('textbox'); var doneButton = document.getElementById('done'); function change() { textboxNode.setAttribute('value', textValue); textNode.style.display = 'none'; textboxNode.setAttribute('type','text'); doneButton.setAttribute('type','button'); } function changeBack() { textNode.firstChild.nodeValue = textboxNode.value; textNode.style.display = 'block'; textboxNode.setAttribute('type', 'hidden'); doneButton.setAttribute('type','hidden'); } </script> </head> <body> <p id="text" onClick="change()">Click me!</p> <form onSubmit="return false;"> <input type="hidden" id="textbox" /> <input type="hidden" id="done" onClick="changeBack()" value="Done" /> </form> </body> </html>
Please, help! Thanks at Advance.
source share