Javascript Miscellaneous Notes - Neils Resource WebJavascript Miscellaneous Notes - Neils Resource WebJavascript Notes - Web Dev. - Neils Resource Web

Contract Menu | Expand Menu

Summary of Content
Javascript LogoThis section is a collection of miscellaneous notes regarding Javascripting. I've needed to use these on more than one occasion, which is why they are here....Creating line breaks in long strings, Calling scripts externally, Running multiple scripts in a single page, Opening Windows with javascript, Standard pop up boxes, Formatting text in javascript.....

Creating Line Breaks In JavaScript Strings
JavaScript provides two ways to create line breaks within a string. The first is the newline character ( \n ). The newline character creates line breaks within the output of a string, whether it is text or JavaScript-generated HTML.

Here is a long string without line breaks:

 var noBreaks = Hello. My name is Neil. What is your name?
will produce...

Hello. My name is Neil. What is your name?

The same string with line breaks:

 var noBreaks = Hello.\nMy name is Neil.\nWhat is your name?
will produce...

Hello.

My name is Neil.

What is your name?


Opening A Window With JavaScript
The JavaScript command used to open a window is:

window.open


For this to work, though, it requires two extra things. Firstly you will need to have some extra information so that the JavaScript knows how to open the window:

window.open('link.html','mywindow');
This means that a window called 'mywindow' will open with the page link.html in it, exactly like with the HTML code above.

This code can either used as part of your JavaScript code (for example if you included it in the JavaScript code in the <head> section of your page it would open when the page loaded) or can be used when a link is clicked. To do this you must use another JavaScript command called onclick.

I will give you more information about how this command works in a later part but for now all you really need to know is the following: In your standard HTML code include a link as follows:

<a href="#" onClick="window.open('link.html','mywindow');">Click Here</a>

As you can see this is just the same window.open command inside an HTML tag.

Manipulating The Window

The main reason of using JavaScript to manipulate windows, though, is because you can set many things on the window which you could never do with HTML. JavaScript allows you to use commands to decide which parts of the browser window appear. This is done using a third part of the window.open command. This is where you decide the window features:

window.open('link.html','mywindow','window features');


There are many things you can include here. For example if you wanted a window that only has a location bar and a status bar (the part at the bottom of the browser) then you would use the following code:

window.open('link.html','mywindow','location, status');

The following can be included in the new window command:
 
Feature Function
menubar The File, Edit etc. menus at the top of the browser will be shown
scrollbar This will show scrollbars at the side of the window if they are needed
width You can set the width of the window in pixels (see the next section)
height You can set the height of the window in pixels (see the next section)
toolbar This will display the browser toolbar with the Back, Stop, Refresh buttons etc.
location The location bar (where you type in URLs) will be displayed in the browser
resizable This will allow the window to be resized by the user
directories This will show the directories in Netscape browsers like 'What's new' and 'What's cool'

Examples Of Manipulating Windows

You may be a little confused by all these options so I will show you a few examples of opening a window in JavaScript:

This window will open with a location bar, toolbar and will be resizable:

window.open('window1.htm','the_first_window','location, toolbar, resizable');


This will open another page in this window:

window.open('window2.htm','thefirstwindow');


This will open a window 200 pixels wide and 300 pixels high. It is not resizable and has a status bar and will scroll if necessary. This is a very commonly used combination:

window.open('window1.htm','thesecondwindow','height=300,width=200,status,scrollbars');

 

Extract from Freewebmasterhelp.com


External Javascripts

 

You can also include the javascript as an external js file. Take the script and paste it, all by itself, into a word processor. It should be the only thing on the page. Take out the beginning and end SCRIPT commands.


<SCRIPT LANGUAGE="JavaScript"> and </SCRIPT>
Get rid of them. Erase them. You'll pick them up again later.

Now do a SAVE AS command and save the file as TEXT only (the same way you would an HTML file), give it a name and add the extension .js. Let's say you want to name this file "Script". Do a Save As, making sure you are saving as text alone, and give the file the name "Script.js".

Calling For The JavaScript File

You have the JavaScript file saved. To call for it in from another document insert these commands:

<SCRIPT LANGUAGE="JavaScript" SRC="scriptname.js"> </SCRIPT>


Adding more than one JavaScript to a page

How to add multiple scripts to one page. Many people complain that, while a script works as it should alone on the page, when a second (or more) one is added, all of a sudden either one or both of the scripts no longer work.
The problem
First of all, there is no limit as to the number of scripts a page can contain (other than the "physical" limit), just like there isn't any cap on how much text a page can supposedly hold. Moving on...

The reason why two working scripts may mysteriously not work when put together is simple - script conflict. You see, any duplication in variable declaration, function name, or event-handler access in two scripts can cause at least one, if not both scripts to become inoperative. However, while the possibilities are great, the chances are not. The fact is, 95% of script conflicts are the result of one type of conflict- duplication in event-handler access; in particular, the body ONLOAD event handler.

Many scripts are set to run after an "event" has occurred, such as the moving of the mouse over a link or the completed loading of the document. The later is the most common, and takes the following two forms:

1) <body ONLOAD="runscript()">
2) window.onload=runscript //appears inside the <script> tag


Just for ease of reference, let's call the first form "delta", and the second, "beta" from hereon. If you see one of the above two lines in your page (where "runscript" varies depending on the script), you know the containing script is set to run after the document has loaded. If you have two or more scripts that EACH contain either delta or beta, you have a conflict on your hand.
The solution
The way to go about solving this conflict is simple, though not quite the same to explain. Essentially, what you want is to end up with only ONE delta for both scripts, with that delta calling the two scripts. Let's list some possible scenarios now, and their resolutions:

EXAMPLE #1:
SCRIPT 1: <body onload="dothis()">
SCRIPT 2: <body onload="dothat()">
RESOLUTION: <body onload="dothis();dothat()">


EXAMPLE #2:
SCRIPT 1: <body onload="dothis()">
SCRIPT 2: window.onload=dothat()
RESOLUTION: <body onload="dothis();dothat()">


EXAMPLE #3:
SCRIPT 1: window.onload=dothis
SCRIPT 2: window.onload=dothat
RESOLUTION: <body onload="dothis();dothat()">


As you can see, regardless of whether the two scripts contain "delta" or "beta", the resolution is the same- remove BOTH lines, and call the scripts directly within the <body> tag, each separated by a semicolon. If you wish to combine three scripts, the procedure is the exact same.

By using the above technique, both scripts are called and executed, as opposed to just one- or neither. In other words, conflict avoided! Check out http://www.javascriptkit.com/javatutors/eventaction4.shtml for some additional information on resolving script conflicts.


Standard Pop Up Windows
Here are the three different 'built in' popup windows. Alert, Confirm, and Prompt. Alert is used for letting the user know something. Confirm is used when you want to ask the user a yes or no question. The user will be able to click either 'OK' or 'Cancel', OK will return 'true', and Cancel will return 'false'. The last, Prompt, will let the user fill in a small text field and then click OK to send the value of the text field to the script
Alert
....</head>

<script language="javascript">
function myPopup(){
alert("Welcome!")
}
</script>

<body onload="myPopup()">
etc...
Confirmation
...</head>

<script language="javascript">
function myPopup(){
confirm("Are you sure?")
}
</script>

<body onload="myPopup()">
etc...
Prompt
...</head>

<script language="javascript">
function myPopup(){
prompt("Enter your name:")
}
</script>

<body onload="myPopup()">
etc...
 

Formatting text in JavaScript


http://www.scriptingmaster.com/index.asp

At the site above it states 'Learn Scripting Languages from the Master' This is no idle boast! It is an excellent resource answering amongst other things, most scripting questions. The extract below is perfect example and answered a problem I had completely. Use the above link and see for yourself. HTML, XHTML, ASP, Javascript etc..

JavaScript provides number of predefined functions (methods) to format some text. The methods we are about to discuss are:

  1. bold () makes text bold using the HTML <b> tag.

  2. italics () italicizes text using the HTML <i> tag.

  3. fontcolor () changes the colour of the text to the specified colour as an argument. The fontcolor () method uses the HTML <font> tag with the color attribute.

  4. fontsize () changes the size of the text to the specified size as an argument. The fontcolor () method uses the HTML <font> tag with the size attribute.

  5. toLowerCase () changes text to all lowercase letters.

  6. toUpperCase () changes text to all upper case letters.

From other examples presented on this site about JavaScript, you should know how to call (use) a JavaScript method. We simply call the method with object it belongs to. The methods shown above are part of a string object. The following shows the JavaScript code how to use the above mentioned text formatting methods ():

<script language="javascript">
var str = "Learn JavaScript with easy examples!";
document.write ("Orginal text: " + str);
document.write ("<br>Changed to bold: " + str.bold());
document.write ("<br>Changed to italics: " + str.italics());
document.write ("<br>Changed color: " + str.fontcolor("DarkGreen")); // could also use the Hexadecimal value: #006400
document.write ("<br>Changed size: " + str.fontsize("2")); // possible values 1 through 7
document.write ("<br>In lowercase: " + str.toLowerCase());
document.write ("<br>In upper case: " + str.toUpperCase());
</script>

Let's discuss what the above JavaScript code does. We start with string variable. Line 3 displays the value of the variable. Line 4 prints our string as bold because of the bold () method being used with string object. Similarly, we call the other methods and pass arguments, when appropriate, inside the parentheses. The following shows the output of the above JavaScript code:

Orginal text: Learn JavaScript with easy examples!
Changed to bold: Learn JavaScript with easy examples!
Changed to italics: Learn JavaScript with easy examples!
Changed color: Learn JavaScript with easy examples!
Changed size: Learn JavaScript with easy examples!
In lowercase: learn javascript with easy examples!
In upper case: LEARN JAVASCRIPT WITH EASY EXAMPLES!

Just like in HTML we can use more than one tag to format a text, we can multiple methods on the same string object. For instance, in HTML if you wanted to display some text as bold, dark green and in bigger font size, you could use the <b> tag, <font> tag to adjust the colour and size; respectively. See the following HTML code:

<font size="6" color="#006400">
<b>Formatting some text.</b>
</font>

for

Formatting some text.

To produce the above shown output, notice our HTML code does not say:

<font size="6">
<font color="#006400">
<b>Formatting some text.</b>
</font>
</font>

This code uses two font tags instead of one yet the output of our code is unaffected. You may notice that this is long and is less efficient way of coding. By the same token, we want to avoid that in JavaScript. See the same example in JavaScript:

<script language="javascript">
var str = "Formatting some text.";
str = str.fontsize("6"); // sets size of the text to 6
str = str.fontcolor("#006400"); // sets color of the text to #006400
str = str.bold(); // makes text bold
document.write (str);
</script>

We create our string variable on line 2. Line 3 uses the fontsize () method to set the font size of this string to 6. Line 4 sets the color and line 5 makes the text bold. Finally, line 6 prints out result. Notice each time we make a change to the str variable, we assign the value to itself using the assignment operator.

The following JavaScript code is more concise and efficient to accomplish the same:

<script language="javascript">
var str = "Formatting some text.";
str = str.fontsize("6").fontcolor("#006400").bold();
document.write (str);
</script>

Notice on line 3 we are using three methods with the string object called str. We separate each method with a dot (specifically with dot operator). Notice the formatted string result is the same whether you use one method at a time or multiple methods in one step:

Formatting some text.

 

 
wwwThis Site
Hyperlink titles may have been abbreviated, (right click on the link and select properties for the full URL)
Top of the PageTop of the PageA double mouse click anywhere on the page will take you back to the top (except when over hyperlinks)

Last Update: 04/03/2008 - Javascript Miscellaneous Notes - Neils Resource Web

html 4.01 strict css 2.1 javascript 1.2