lise wrote:
Would this be accurate? When it is a function,then I use the Insert Script, but when it is just the button, like in your first example, I just put it in the text editor within a paragraph.
No, you can define a function inline - like this say (not using script tags):
Code: Select all
<p>
<button type="button" onclick="(function sayHello(){
document.getElementById('demo').innerHTML = 'Hello JavaScript!';})()">
Click Me!
</button>
</p>
<p id="demo"> </p>
You might do this, for example, if you wanted to write a more complicated function than just a single line.
Couple of things to note about the example:
- Although I left the function name in the example, you wouldn't usually bother to name an inline function - after all, you aren't going to call it again. You can just say function() { //function code }
- Don't forget to put the extra pair brackets at the end (just before the end-quotes) - after a function they mean "run this now".
But the thing is that inline code is pretty limiting. For example, you wouldn't be able to call this function from anywhere else. Also, if anything went wrong with it, it would be harder to track down and test than a nice tidy script somewhere. So although you *could* do this, you usually shouldn't.
For example, imagine you had your nice function "sayHello" in a script tag like this:
Code: Select all
<script type="text/javascript">
function sayHello(message) {
document.getElementById("demo").innerHTML = message;
}
</script>
Then in your page you could have lots of buttons all calling the same function:
Code: Select all
<p><button type="button" onclick="sayHello('Hi there!')">Say Hi!</button></p>
<p><button type="button" onclick="sayHello('Howdy pal!')">Say Howdy!</button></p>
<p><button type="button" onclick="sayHello('こんにちは!')">Say Hello in Japanese!</button></p>
<p id="demo"></p>
lise wrote:Also, I was able to get your first example going fine, but I wasn't able to get the last code to work. I used the Script button, pasted it, and the built page always just displays my content with an extra
"/*]]>*/" at the end of the page (whether my "demo" class paragraph includes content or remains empty). Not sure what I'm doing wrong.
I suspect you created a script but then pasted my script *including* the script tags. The script button creates the tags for you, so you'll have ended up with an extra pair. Just paste the parts of the example code that is inside the script tags.