JavaScript in WordPress Part 2


The previous post, JavaScript in WordPress explained how to add JavaScript code to your WordPress site. It used a very simple example of JavaScript code because it focused on how to call a JavaScript function in your post or page. There are five steps you need to take in order to use JavaScript in your site.

  1. From your requirements, plan how you want to use JavaScript.
  2. Write your JavaScript code in a .js file, keeping in mind your HTML code.
  3. Copy that file up to the server in an appropriate location in your theme’s directory.
  4. In the head template of your theme, add a call to the above file to load your JavaScript code.
  5. Call your JavaScript functions as needed in your posts and pages.

Once you have set this up for one function, you can simply edit the .js file to add more functions and call them as needed. If you change your theme you will need to re-do steps three and four above. There is nothing stopping you from having multiple .js files in use with multiple functions inside of each file. Also be sure that your function names are unique (no duplicates).

In the previous post we only wrote one line of JavaScript code inside a function:

function helloMike () {
   document.writeln('Hello, Mike!');
}

Could we put HTML tags inside the text that writeln outputs? Can we put HTML tags around a call to a JavaScript function? We will add another function to our existing JavaScript file called helloMikeBold() to help answer this question. Here is the new code.

function helloMike () {
   document.writeln('Hello, Mike!');
}
function helloMikeBold () {
	document.writeln('<b>Hello, Mike!</b>');
}

So it worked!. You can include HTML tags within the writeln() function. For the Hello, Mike! just above I called our helloMikeBold() function. Now, the HTML below will put our call to the helloMikeBold() function inside of the em tag which shows the text in italics.



Cool. That worked also. So now we know that a JavaScript function could spit out all kinds of HTML tags and text all over the place! We could even ask the user to enter some text and HTML tags into a text box, ask them to click a button and then display the rests for them.

Leave a comment

Your email address will not be published. Required fields are marked *