using javascript

using javascript

by Andrew Golightly -
Number of replies: 3

Hi all,

I have a client that would like to use javascript within lessons to add a bit of functionality like mouse over effect. Or clicking on a button will update some text on that same page.

Anyway, editing a page, then going into HTML view, and putting in some javascript like:

<script type="text/javascript">// <![CDATA[
var i=0;
for (i=0;i<=5;i++)
{
document.write("The number is " + i);
document.write("<br />");
}
// ]]></script>

works fine. Calling functions doesn't seem to work though because I'll need to have the function defined in the <head> section. How do I do that? Edit the theme file?

What is the best way to go about integrating javascript into Moodle? I've read this http://docs.moodle.org/dev/JavaScript_guidelines but I'm not fully getting it all. I really only want to do some pretty basic things. So the key is to be able to define functions, and call them from within a block of HTML as in a lesson.

thanks!

Andrew

Average of ratings: -
In reply to Andrew Golightly

Re: using javascript

by Tim Hunt -
Picture of Core developers Picture of Documentation writers Picture of Particularly helpful Moodlers Picture of Peer reviewers Picture of Plugin developers

You don't need to define functions in <head>

<script type="text/javascript">// <![CDATA[
function square(x) {
return x*x;
}
for (i=0;i<=5;i++) {
document.write("The number is " + square(i));
}
// ]]></script>
will work.
Average of ratings:Useful (1)
In reply to Andrew Golightly

Re: using javascript

by Lynn Scarlet Clark -

Andrew,

Using JS in lesson screens works wonderfully - I have extensive interactivity within the lesson I have created using JS (as well as other things). As Tim said, you don't need to worry about placement; just write the JS in the editing window along with the HTML.

You need to turn off HTML editing though, everytime you put in new JS or edit existing, or Moodle will try to corrupt the script (and then your functionality won't work). Do this in your 'edit profile' page under the 'When editing text' drop down - you need to select 'USe standard web forms'. You can turn it back to pretty HTML at any time.

Have fun with it - lesson pages with javascript can work really well.

Average of ratings:Useful (1)
In reply to Lynn Scarlet Clark

Re: using javascript

by Andrew Golightly -

Hi Scarlet,

Thanks so much. I was looking for a way to stop Moodle changing my code.

Thank you!

Andrew