1

I want to put the script between the <head> tags using the anonymous function and I add the onclick event to change the contents of the tag p but after I click nothing happens. Is there anything wrong from my script please help me. thank you

<!DOCTYPE html> <html lang="en"> <head> <title>web</title> <script> window.onload=function(){ function rubah1(){ document.getElementById("text1").innerHTML="SUDAH BERUBAH TEXT 1"; } } </script> </head> <body> <p id="text1">Teks 1 Sebelum Di Rubah</p> <button type="button" onclick="rubah1();">Rubah Text 1</button> </body> </html> 
3
  • I assume if you remove the onload it works? Commented Dec 30, 2017 at 14:07
  • 2
    rubah() is not in global scope since you wrapped it in another function. Study some tutorials on "javascript scope" Commented Dec 30, 2017 at 14:11
  • @MattFletcher SOLVED thanks you when I read an article, if you want to put the javascript code should be with the add anonymus.is it true that but the proof does not work? Commented Dec 30, 2017 at 14:14

2 Answers 2

4

Please format your code better next time. You don't need to wait for the document to load to define a function. You can just define in in the head and then the button will work. Working code snippet:

 <!DOCTYPE html> <html lang="en"> <head> <title>web</title> <script> function rubah1() { document.getElementById("text1").innerHTML = "SUDAH BERUBAH TEXT 1"; } </script> </head> <body> <p id="text1">Teks 1 Sebelum Di Rubah</p> <button type="button" onclick="rubah1();">Rubah Text 1</button> </body> </html>

The problem with your approach is that you define the function in the inner scope of the onload function, and thus is not visible to the button.

Sign up to request clarification or add additional context in comments.

1 Comment

You thank someone by marking the answer as being correct (checking the checkmark next to the answer). This will give your rep a +2 boost.
1

The function rubah1 is defined within onload. Hence, its scope is not global. function rubah1's life is only within onload. Code that is out of scope of onload cannot call it because that code doesn't know that a function named rubah1 exists. You can remove onload as it doesn't seem to add any value to it.
You can help yourself by referring this which will clear your concepts: w3schools Javascript scope tutorial.

Updated Code:

<!DOCTYPE html> <html lang="en"> <head> <title>web</title> <script> window.onload=function(){ function rubah1(){ document.getElementById("text1").innerHTML="SUDAH BERUBAH TEXT 1"; } } </script> </head> <body> <p id="text1">Teks 1 Sebelum Di Rubah</p> <button type="button" onclick="rubah1();">Rubah Text 1</button> </body> 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.