100% found this document useful (1 vote)
22 views

JavaScript in 10 Simple Steps or Less 1st Edition Arman Danesh - The ebook with all chapters is available with just one click

The document provides information about downloading the ebook 'JavaScript in 10 Simple Steps or Less' by Arman Danesh, along with links to other recommended ebooks. It includes details about the book's content, author, and publication information. The document also emphasizes the availability of additional resources on the website ebookultra.com.

Uploaded by

worldslongui4
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (1 vote)
22 views

JavaScript in 10 Simple Steps or Less 1st Edition Arman Danesh - The ebook with all chapters is available with just one click

The document provides information about downloading the ebook 'JavaScript in 10 Simple Steps or Less' by Arman Danesh, along with links to other recommended ebooks. It includes details about the book's content, author, and publication information. The document also emphasizes the availability of additional resources on the website ebookultra.com.

Uploaded by

worldslongui4
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 51

Visit https://ebookultra.

com to download the full version and


explore more ebooks or textbooks

JavaScript in 10 Simple Steps or Less 1st Edition


Arman Danesh

_____ Click the link below to download _____


https://ebookultra.com/download/javascript-in-10-simple-
steps-or-less-1st-edition-arman-danesh/

Explore and download more ebooks or textbooks at ebookultra.com


Here are some recommended products that we believe you will be
interested in. You can click the link to download.

HTML in 10 Simple Steps or Less 1st Edition Robert G.


Fuller

https://ebookultra.com/download/html-in-10-simple-steps-or-less-1st-
edition-robert-g-fuller/

Indian Cooking Unfolded A Master Class in Indian Cooking


with 100 Easy Recipes Using 10 Ingredients or Less Iyer

https://ebookultra.com/download/indian-cooking-unfolded-a-master-
class-in-indian-cooking-with-100-easy-recipes-using-10-ingredients-or-
less-iyer/

Digital Photography In Simple Steps 2nd Edition Marc


Campbell

https://ebookultra.com/download/digital-photography-in-simple-
steps-2nd-edition-marc-campbell/

Write a Romance in 5 Simple Steps 1st Edition Suzanne


Lieurance

https://ebookultra.com/download/write-a-romance-in-5-simple-steps-1st-
edition-suzanne-lieurance/
Diabetic meals in 30 minutes or less 2nd edition Edition
Webb

https://ebookultra.com/download/diabetic-meals-in-30-minutes-or-
less-2nd-edition-edition-webb/

The Irresistible Offer How to Sell Your Product or Service


in 3 Seconds or Less 1st Edition Mark Joyner

https://ebookultra.com/download/the-irresistible-offer-how-to-sell-
your-product-or-service-in-3-seconds-or-less-1st-edition-mark-joyner/

Simple Steps to Success Fruit and Vegetables in Pots 1st


American ed Edition Jo Whittingham

https://ebookultra.com/download/simple-steps-to-success-fruit-and-
vegetables-in-pots-1st-american-ed-edition-jo-whittingham/

Management Strategies in Antithrombotic Therapy 1st


Edition Arman Askari

https://ebookultra.com/download/management-strategies-in-
antithrombotic-therapy-1st-edition-arman-askari/

10 Simple Solutions for Building Self Esteem 1st Edition


Glenn R. Schiraldi

https://ebookultra.com/download/10-simple-solutions-for-building-self-
esteem-1st-edition-glenn-r-schiraldi/
JavaScript in 10 Simple Steps or Less 1st Edition Arman
Danesh Digital Instant Download
Author(s): Arman Danesh
ISBN(s): 9780764542411, 0764542419
Edition: 1
File Details: PDF, 14.11 MB
Year: 2003
Language: english
TM
JavaScript
in 10 Simple Steps or Less
TM
JavaScript
in 10 Simple Steps or Less

Arman Danesh
JavaScriptTM in 10 Simple Steps or Less
Published by
Wiley Publishing, Inc.
10475 Crosspoint Boulevard
Indianapolis, IN 46256
www.wiley.com

Copyright © 2004 by Wiley Publishing, Inc., Indianapolis, Indiana


Published simultaneously in Canada
Library of Congress Control Number: 2003114066
ISBN: 0-7645-4241-9
Manufactured in the United States of America
10 9 8 7 6 5 4 3 2 1
1Q/QZ/RS/QT/IN
No part of this publication may be reproduced, stored in a retrieval system or transmitted in any form or by any
means, electronic, mechanical, photocopying, recording, scanning or otherwise, except as permitted under Sec-
tions 107 or 108 of the 1976 United States Copyright Act, without either the prior written permission of the
Publisher, or authorization through payment of the appropriate per-copy fee to the Copyright Clearance Cen-
ter, 222 Rosewood Drive, Danvers, MA 01923, (978) 750-8400, fax (978) 646-8600. Requests to the Publisher
for permission should be addressed to the Legal Department, Wiley Publishing, Inc., 10475 Crosspoint Blvd.,
Indianapolis, IN 46256, (317) 572-3447, fax (317) 572-4447, E-mail: [email protected].
Limit of Liability/Disclaimer of Warranty: While the publisher and author have used their best efforts in
preparing this book, they make no representations or warranties with respect to the accuracy or completeness of
the contents of this book and specifically disclaim any implied warranties of merchantability or fitness for a par-
ticular purpose. No warranty may be created or extended by sales representatives or written sales materials. The
advice and strategies contained herein may not be suitable for your situation. You should consult with a profes-
sional where appropriate. Neither the publisher nor author shall be liable for any loss of profit or any other com-
mercial damages, including but not limited to special, incidental, consequential, or other damages.
For general information on our other products and services or to obtain technical support, please contact our
Customer Care Department within the U.S. at (800) 762-2974, outside the U.S. at (317) 572-3993 or fax (317)
572-4002.
Wiley also publishes its books in a variety of electronic formats. Some content that appears in print may not be
available in electronic books.
Trademarks: Wiley, the Wiley Publishing logo, and related trade dress are trademarks or registered trademarks
of John Wiley & Sons, Inc. and/or its affiliates in the United States and other countries, and may not be used
without written permission. JavaScript is a trademark of Sun Microsystems, Inc. All other trademarks are the
property of their respective owners. Wiley Publishing, Inc. is not associated with any product or vendor men-
tioned in this book.
To my beloved Tahirih for her support and encouragement.
Credits

Acquisitions Editor Project Coordinator


Jim Minatel Courtney MacIntyre

Development Editor Graphics and Production Specialists


Sharon Nash Elizabeth Brooks, Joyce Haughey, Jennifer Heleine,
LeAndra Hosier, Heather Pope, Mary Gillot Virgin
Production Editor
Felicia Robinson Quality Control Technician
John Tyler Connoley, John Greenough,
Technical Editor Charles Spencer
Will Kelly
Proofreading and Indexing
Copy Editor Sossity R. Smith, Johnna VanHoose
Joanne Slike

Editorial Manager
Kathryn Malm

Vice President & Executive Group Publisher


Richard Swadley

Vice President and Executive Publisher


Robert Ipsen

Vice President and Publisher


Joseph B. Wikert
About the Author

Arman Danesh is the Internet Coordinator for the Bahá’í International Community’s Office of Public
Information. In that capacity, he manages the development of numerous Web sites, including The Bahá’í
World (www.bahai.org), the official Web site of the Bahá’í Faith, and the Bahá’í World News Services
(www.bahaiworldnews.org), an online news service, both of which use JavaScript. Additionally, he is the
Technical Director for Juxta Publishing Limited (www.juxta.com). He has been working with JavaScript
since the mid-1990s and is the author of some of the earliest books on the subject, including Teach Yourself
JavaScript in a Week and JavaScript Developer’s Guide. Arman has authored more than 20 books on tech-
nology subjects, including ColdFusion MX Developer’s Handbook (Sybex), Mastering ColdFusion MX (Sybex),
SAIR Linux & Gnu Certified Administrator All-in-One Exam Guide (Osborne/McGraw-Hill), and Safe and
Secure: Secure Your Home Network and Protect Your Privacy Online (Sams). He is pursuing an advanced
degree in computer science at Simon Fraser University outside Vancouver, British Columbia.
Acknowledgments

T he task of writing these long computer books is a daunting one, and it is a process that requires
significant contributions from many people who help these projects see their way to completion.
For this project, I need to thank the entire team, including Sharon Nash and Jim Minatel at Wiley, as
well as all the myriad others involved in preparing, designing, and producing the books there.

I also need to thank my family for their patience during the writing of the book. In particular, my wife,
Tahirih, and son, Ethan, deserve credit for tolerating the time I had to devote to the preparation of
this book.
Contents

Credits vi

About the Author vii

Acknowledgments ix

Introduction xix

Part 1: JavaScript Basics 1


Task 1: Creating a script Block 2
Task 2: Hiding Your JavaScript Code 4
Task 3: Providing Alternatives to Your JavaScript Code 6
Task 4: Including Outside Source Code 8
Task 5: Commenting Your Scripts 10
Task 6: Writing a JavaScript Command 12
Task 7: Temporarily Removing a Command from a Script 14
Task 8: Using Curly Brackets 16
Task 9: Writing Output to the Browser 18
Task 10: Creating a Variable 20
Task 11: Outputting a Variable 22
Task 12: Creating a String 24
Task 13: Creating a Numeric Variable 26
Task 14: Performing Math 28
Task 15: Concatenating Strings 30
Task 16: Searching for Text in Strings 32
Task 17: Replacing Text in Strings 34
Task 18: Formatting Strings 36
Task 19: Applying Multiple Formatting Functions to a String 38
Task 20: Creating Arrays 40
Task 21: Populating an Array 42
Task 22: Sorting an Array 44
Task 23: Splitting a String at a Delimiter 46
Task 24: Calling Functions 48
xii JavaScript in 10 Simple Steps or Less

Task 25: Alerting the User 50


Task 26: Confirming with the User 52
Task 27: Creating Your Own Functions 54
Task 28: Passing an Argument to Your Functions 56
Task 29: Returning Values from Your Functions 58
Task 30: Passing Multiple Parameters to Your Functions 60
Task 31: Calling Functions from Tags 62
Task 32: Calling Your JavaScript Code after the Page Has Loaded 64
Task 33: Using for Loops 66
Task 34: Testing Conditions with if 68
Task 35: Using Short-Form Condition Testing 70
Task 36: Looping on a Condition 72
Task 37: Looping through an Array 74
Task 38: Scheduling a Function for Future Execution 76
Task 39: Scheduling a Function for Recurring Execution 78
Task 40: Canceling a Scheduled Function 80
Task 41: Adding Multiple Scripts to a Page 82
Task 42: Calling Your JavaScript Code after the Page Has Loaded 84
Task 43: Check If Java Is Enabled with JavaScript 86

Part 2: Outputting to the Browser 89


Task 44: Accessing the document Object 90
Task 45: Outputting Dynamic HTML 92
Task 46: Including New Lines in Output 94
Task 47: Outputting the Date to the Browser 96
Task 48: Outputting the Date and Time in a Selected Time Zone 98
Task 49: Controlling the Format of Date Output 100
Task 50: Customizing Output by the Time of Day 102
Task 51: Generating a Monthly Calendar 104
Task 52: Customizing Output Using URL Variables 106
Task 53: Dynamically Generating a Menu 108
Task 54: Replacing the Browser Document with a New Document 110
Task 55: Redirecting the User to a New Page 112
Task 56: Creating a “Page Loading ...” Placeholder 114

Part 3: Images and Rollovers 117


Task 57: Accessing an HTML-Embedded Image in JavaScript 118
Task 58: Loading an Image Using JavaScript 120
Task 59: Detecting MouseOver Events on Images 122
Contents xiii

Task 60: Detecting Click Events on Images 124


Task 61: Switching an Image Programatically 126
Task 62: Using Multiple Rollovers in One Page 128
Task 63: Displaying a Random Image 130
Task 64: Displaying Multiple Random Images 132
Task 65: Using a Function to Create a Rollover 134
Task 66: Using a Function to Trigger a Rollover 136
Task 67: Using Functions to Create Multiple Rollovers in One Page 138
Task 68: Creating a Simple Rollover Menu System 140
Task 69: Creating a Slide Show in JavaScript 142
Task 70: Randomizing Your Slide Show 144
Task 71: Triggering Slide Show Transitions from Links 146
Task 72: Including Captions in a Slide Show 148
Task 73: Testing If an Image Is Loaded 150
Task 74: Triggering a Rollover in a Different Location with a Link 152
Task 75: Using Image Maps and Rollovers Together 154
Task 76: Generating Animated Banners in JavaScript 156
Task 77: Displaying a Random Banner Ad 158

Part 4: Working with Forms 161


Task 78: Preparing Your Forms for JavaScript 162
Task 79: Accessing Text Field Contents 164
Task 80: Dynamically Updating Text Fields 166
Task 81: Detecting Changes in Text Fields 168
Task 82: Accessing Selection Lists 170
Task 83: Programmatically Populating a Selection List 172
Task 84: Dynamically Changing Selection List Content 174
Task 85: Detecting Selections in Selection Lists 176
Task 86: Updating One Selection List Based on Selection in Another 178
Task 87: Using Radio Buttons instead of Selection Lists 180
Task 88: Detecting the Selected Radio Button 182
Task 89: Detecting Change of Radio Button Selection 184
Task 90: Updating or Changing Radio Button Selection 186
Task 91: Creating Check Boxes 188
Task 92: Detecting Check Box Selections 190
Task 93: Changing Check Box Selections 192
Task 94: Detecting Changes in Check Box Selections 194
Task 95: Verifying Form Fields in JavaScript 196
Task 96: Using the onSubmit Attribute of the Form Tag to Verify Form Fields 198
xiv JavaScript in 10 Simple Steps or Less

Task 97: Verifying Form Fields Using INPUT TYPE=”button”


Instead of TYPE=”submit” 200
Task 98: Validating E-mail Addresses 202
Task 99: Validating Zip Codes 204
Task 100: Validating Phone Numbers 206
Task 101: Validating Credit Card Numbers 208
Task 102: Validating Selection List Choices 210
Task 103: Validating Radio Button Selections 212
Task 104: Validating Check Box Selections 214
Task 105: Validating Passwords 216
Task 106: Validating Phone Numbers with Regular Expressions 218
Task 107: Creating Multiple Form Submission Buttons Using
INPUT TYPE=”button” Buttons 220
Task 108: Reacting to Mouse Clicks on Buttons 222
Task 109: Using Graphical Buttons in JavaScript 224
Task 110: Controlling the Form Submission URL 226
Task 111: Validating a Numeric Text Field with Regular Expressions 228
Task 112: Encrypting Data before Submitting It 230
Task 113: Using Forms for Automatic Navigation Jumping 232

Part 5: Manipulating Browser Windows 235


Task 114: Using the Window Object 236
Task 115: Popping Up an Alert Dialog Box 238
Task 116: Popping Up Confirmation Dialog Boxes 240
Task 117: Popping Up JavaScript Prompts 242
Task 118: Creating New Browser Windows 244
Task 119: Opening a New Browser Window from a Link 246
Task 120: Setting the Size of New Browser Windows 248
Task 121: Setting the Location of New Browser Windows 250
Task 122: Controlling Toolbar Visibility for New Browser Windows 252
Task 123: Determining the Availability of Scroll Bars for New Browser Windows 254
Task 124: Restricting Resizing of New Browser Windows 256
Task 125: Loading a New Document into a Browser Window 258
Task 126: Controlling Window Scrolling from JavaScript 260
Task 127: Opening a Full-Screen Window in Internet Explorer 262
Task 128: Handling the Parent-Child Relationship of Windows 264
Task 129: Updating One Window’s Contents from Another 266
Task 130: Accessing a Form in Another Browser Window 268
Task 131: Closing a Window in JavaScript 270
Task 132: Closing a Window from a Link 272
Contents xv

Task 133: Creating Dependent Windows in Netscape 274


Task 134: Sizing a Window to Its Contents in Netscape 276
Task 135: Loading Pages into Frames 278
Task 136: Updating One Frame from Another Frame 280
Task 137: Sharing JavaScript Code between Frames 282
Task 138: Using Frames to Store Pseudo-Persistent Data 284
Task 139: Using One Frame for Your Main JavaScript Code 286
Task 140: Using a Hidden Frame for Your JavaScript Code 288
Task 141: Working with Nested Frames 290
Task 142: Updating Multiple Frames from a Link 292
Task 143: Dynamically Creating Frames in JavaScript 294
Task 144: Dynamically Updating Frame Content 296
Task 145: Referring to Unnamed Frames Numerically 298

Part 6: Manipulating Cookies 301


Task 146: Creating a Cookie in JavaScript 302
Task 147: Accessing a Cookie in JavaScript 304
Task 148: Displaying a Cookie 306
Task 149: Controlling the Expiry of a Cookie 308
Task 150: Using a Cookie to Track a User’s Session 310
Task 151: Using a Cookie to Count Page Access 312
Task 152: Deleting a Cookie 314
Task 153: Creating Multiple Cookies 316
Task 154: Accessing Multiple Cookies 318
Task 155: Using Cookies to Present a Different Home Page for New Visitors 320
Task 156: Creating a Cookie Function Library 322
Task 157: Allowing a Cookie to be Seen for all Pages in a Site 324

Part 7: DHTML and Style Sheets 327


Task 158: Controlling Line Spacing 328
Task 159: Determining an Object’s Location 330
Task 160: Placing an Object 332
Task 161: Moving an Object Horizontally 334
Task 162: Moving an Object Vertically 336
Task 163: Moving an Object Diagonally 338
Task 164: Controlling Object Movement with Buttons 340
Task 165: Creating the Appearance of Three-Dimensional Movement 342
Task 166: Centering an Object Vertically 344
Task 167: Centering an Object Horizontally 346
xvi JavaScript in 10 Simple Steps or Less

Task 168: Controlling Line Height in CSS 348


Task 169: Creating Drop Shadows with CSS 350
Task 170: Modifying a Drop Shadow 352
Task 171: Removing a Drop Shadow 354
Task 172: Placing a Shadow on a Nonstandard Corner 356
Task 173: Managing Z-Indexes in JavaScript 358
Task 174: Setting Fonts for Text with CSS 360
Task 175: Setting Font Style for Text with CSS 362
Task 176: Controlling Text Alignment with CSS 364
Task 177: Controlling Spacing with CSS 366
Task 178: Controlling Absolute Placement with CSS 368
Task 179: Controlling Relative Placement with CSS 370
Task 180: Adjusting Margins with CSS 372
Task 181: Applying Inline Styles 374
Task 182: Using Document Style Sheets 376
Task 183: Creating Global Style Sheet Files 378
Task 184: Overriding Global Style Sheets for Local Instances 380
Task 185: Creating a Drop Cap with Style Sheets 382
Task 186: Customizing the Appearance of the First Line of Text 384
Task 187: Applying a Special Style to the First Line of Every Element on the Page 386
Task 188: Applying a Special Style to All Links 388
Task 189: Accessing Style Sheet Settings 390
Task 190: Manipulating Style Sheet Settings 392
Task 191: Hiding an Object in JavaScript 394
Task 192: Displaying an Object in JavaScript 396
Task 193: Detecting the Window Size 398
Task 194: Forcing Capitalization with Style Sheet Settings 400
Task 195: Detecting the Number of Colors 402
Task 196: Adjusting Padding with CSS 404

Part 8: Dynamic User Interaction 407


Task 197: Creating a Simple Pull-Down Menu 408
Task 198: Creating Two Pull-Down Menus 410
Task 199: Detecting and Reacting to Selections in a Pull-Down Menu 412
Task 200: Generating a Drop-Down Menu with a Function 414
Task 201: Placing Menu Code in an External File 416
Task 202: Inserting a Prebuilt Drop-Down Menu 418
Task 203: Creating a Floating Window 420
Task 204: Closing a Floating Window 422
Contents xvii

Task 205: Resizing a Floating Window 424


Task 206: Moving a Floating Window 426
Task 207: Changing the Content of a Floating Window 428
Task 208: Detecting Drag and Drop 430
Task 209: Moving a Dragged Object in Drag and Drop 432
Task 210: Changing Cursor Styles 434
Task 211: Determining the Current Scroll Position 436
Task 212: Creating an Expanding/Collapsing Menu 438
Task 213: Creating a Highlighting Menu Using Just Text and CSS—No JavaScript 440
Task 214: Creating a Highlighting Menu Using Text, CSS, and JavaScript 442
Task 215: Placing Content Offscreen 444
Task 216: Sliding Content into View 446
Task 217: Creating a Sliding Menu 448
Task 218: Auto-Scrolling a Page 450

Part 9: Handling Events 453


Task 219: Responding to the onMouseOver Event 454
Task 220: Taking Action When the User Clicks on an Object 456
Task 221: Responding to Changes in a Form’s Text Field 458
Task 222: Responding to a Form Field Gaining Focus with onFocus 460
Task 223: Taking Action When a Form Field Loses Focus with onBlur 462
Task 224: Post-Processing Form Data with onSubmit 464
Task 225: Creating Code to Load When a Page Loads with onLoad 466
Task 226: Executing Code When a User Leaves a Page for Another 468
Task 227: Taking Action When a User Makes a Selection in a Selection List 470

Part 10: Bookmarklets 473


Task 228: Downloading and Installing Bookmarklets 474
Task 229: Checking Page Freshness with a Bookmarklet 476
Task 230: Checking for E-mail Links with a Bookmarklet 478
Task 231: E-mailing Selected Text with a Bookmarklet in Internet Explorer 480
Task 232: E-mailing Selected Text with a Bookmarklet in Netscape 482
Task 233: Displaying Images from a Page with a Bookmarklet 484
Task 234: Changing Background Color with a Bookmarklet 486
Task 235: Removing Background Images with a Bookmarklet 488
Task 236: Hiding Images with a Bookmarklet 490
Task 237: Hiding Banners with a Bookmarklet 492
Task 238: Opening All Links in a New Window with a Bookmarklet 494
Task 239: Changing Page Fonts with a Bookmarklet 496
xviii JavaScript in 10 Simple Steps or Less

Task 240: Highlighting Page Links with a Bookmarklet 498


Task 241: Checking the Current Date and Time with a Bookmarklet 500
Task 242: Checking Your IP Address with a Bookmarklet 502
Task 243: Searching Yahoo! with a Bookmarklet in Internet Explorer 504
Task 244: Searching Yahoo! with a Bookmarklet in Netscape 506

Part 11: Cross-Browser Compatibility and Issues 509


Task 245: Detecting the Browser Type 510
Task 246: Detecting the Browser Version 512
Task 247: Browser Detection Using Object Testing 514
Task 248: Creating Browser Detection Variables 516
Task 249: Dealing with Differences in Object Placement in Newer Browsers 518
Task 250: Creating Layers with the div Tag 520
Task 251: Controlling Layer Placement in HTML 522
Task 252: Controlling Layer Size in HTML 524
Task 253: Controlling Layer Visibility in HTML 526
Task 254: Controlling Layer Ordering in HTML 528
Task 255: Changing Layer Placement and Size in JavaScript 530
Task 256: Changing Layer Visibility in JavaScript 532
Task 257: Changing Layer Ordering in JavaScript 534
Task 258: Fading Objects 536
Task 259: Creating a Page Transition in Internet Explorer 538
Task 260: Installing the X Cross-Browser Compatibility Library 540
Task 261: Showing and Hiding Elements with X 542
Task 262: Controlling Stacking Order with X 544
Task 263: Changing Text Color with X 546
Task 264: Setting a Background Color with X 548
Task 265: Setting a Background Image with X 550
Task 266: Repositioning an Element with X 552
Task 267: Sliding an Element with X 554
Task 268: Changing Layer Sizes with X 556

Appendix A: JavaScript Quick Reference 559

Appendix B: CSS Quick Reference 593

Index 601
Introduction

S ince the mid-1990s when Netscape introduced version 2 of its flagship Netscape Navigator browser,
JavaScript has been part of the Web development landscape. Providing a mechanism to implement
dynamic interactivity in the browser, without connecting to the server, JavaScript is at the core of the
Dynamic HTML model, which allows today’s modern browsers to host sophisticated applications and
user interfaces.

This book is a recipe book that provides you with quick, digestible examples of how to perform specific
tasks using JavaScript. These tasks range from simple tasks such as displaying dynamic output in the
browser window to complex tasks such as creating a dynamic, interactive menu system.

This book isn’t a tutorial in JavaScript. It is designed to be a useful reference when you are actively
engaged in building your Web applications and need quick answers to the question “How do I do this in
JavaScript?” For most tasks of low and medium complexity, you will likely find an example in this book.
Completing complex tasks can often be achieved by combining more than one sample tasks from the
book.

tip
If you don’t have any experi-
ence with JavaScript, you will
probably want to supplement
this book with a tutorial intro-
duction to programming in
JavaScript. For instance, you
might consider JavaScript for
Dummies by Emily A. Vander
Veer (John Wiley & Sons,
0-7645-0633-1).

About the Book


This book is divided into 11 parts:

Part 1: JavaScript Basics


This part provides tasks that illustrate some fundamental JavaScript techniques and skills. If you have
never used JavaScript before, this part is for you. It provides examples that illustrate the basics of creating
scripts and using JavaScript.

Part 2: Outputting to the Browser


This part covers some core techniques for using JavaScript to generate dynamic output to the browser
window, including outputting dynamic values such as dates.
Other documents randomly have
different content
river should have been crossed at that particular point; also why the
British forces should have been led over an open plain without any
attempt at reconnaissance? Such problems as these, however, might
be multiplied to little purpose throughout the earlier part of the
South African campaign. Perhaps the briefest answer to them would
be that it was just because of such incidents as these that the
country was eventually to plead with its oldest soldier to take over
the command. Now that we have tested the lessons that South
Africa taught us, the humiliation has passed into thankfulness that
they came in time.
Cronje simply waited until the British were within range of his fire,
and then very suddenly opened a tornado of bullet and shell fire at a
range of seven hundred and fifty yards. One moment, and in front of
them had lain an apparently peaceful landscape, a few houses and
farms sleeping under the morning sun; the next, and the whole
horizon was blazing with death. It was fatal to advance; the cavalry
could do nothing, while the infantry were dependent upon the guns
to gain the superiority. At this critical moment one of the most
dramatic incidents in the war occurred. Out of the unknown, with
staggering horses and guns caked with mud, lumbered up the 62nd
Field Battery, which had covered thirty-two miles in less than twenty-
four hours. It was a providential piece of good fortune.
Throughout the long day the infantry lay under the broiling sun, just
as the remnants of the Highland Brigade were to endure it not very
long after. The artillery engagement wore on, the heat passed, and
as night came the British were gaining the advantage. All day they
had been without food. At last, in the late afternoon, the North
Lancashires managed to get across the river and take up a position
on the extreme left, where they were joined by the Coldstreams and
the Argyll and Sutherlands. The action was turning against the
Boers. With this desperate little force on their flank, and the artillery
shattering their guns on the front, they took advantage of the night
to evacuate their trenches and retreat. It had indeed been a costly
action, and might have been a humiliating defeat. What perhaps it
was more than anything else was a proof of British bravery under
the most dismal conditions.
Lord Methuen remained upon the Modder River until he was joined
by the Highland Brigade, composed of the 2nd Seaforths, the
Highland Light Infantry, the 1st Gordons fresh from Dargai, and the
2nd Black Watch, with whom was Major-General Andrew Wauchope.
Wauchope had seen service in the Soudan, and was one of the best-
beloved officers in the history of the Highland regiments.
A spectator has written: “Watching the arrival of the Highland
Brigade, very magnificent they looked as they swung into camp,
pipers strutting before them, kilts swish-swishing, all in perfect order
and perfect step—the finest troops in the world.”
The Boers, having fallen back from the Modder River, halted at
Magersfontein, a circle of hills which Cronje endeavoured—with what
success we shall see—to render impregnable. It was the next step
towards Kimberley, and on Saturday, December 9, Lord Methuen
despatched one of the most critical and forlorn expeditions in our
history, and the most tragic in the story of the Highland regiments.
CHAPTER XXV
WITH THE HIGHLAND BRIGADE AT
MAGERSFONTEIN
(December 11, 1899)

I’ve heard them lilting at the ewe-milking,


Lasses a’ lilting before dawn o’ day;
But now they are moaning on ilka green loaning,
The flowers o’ the forest are a’ wede away.

Highland Funeral March.

Confronting the British troops lay a circle of hills which might or


might not be tenanted by the enemy. Lord Methuen followed the
established military course of shelling these hills from a long range,
preparatory to an advance. Unfortunately it served no purpose, for
the enemy retired temporarily, only to return when the
bombardment was over, knowing that after the artillery had
concluded their futile expenditure of shells, the British infantry
would, in the course of things, advance. It was on Sunday,
December 10, that the Highland Brigade set off early in the
afternoon under a deluge of rain. When they came within a few
miles of the Boers they halted, and darkness began to fall.
At this point Lord Methuen communicated to the Brigade
commanders his plan for carrying the enemy’s position. The attack
would be launched by the Highlanders at break of dawn.
At midnight, under a lowering sky, and in the black darkness of an
African night, the Highland Brigade set out upon its tragic march.
The men were drenched to the skin, carried no food, and were
formed in quarter column. On the right the Black Watch, then the
Seaforths, the Argyll and Sutherlands next, and in reserve the
Highland Light Infantry. The Gordons, who had only arrived before
the march began, remained in camp. It is important to follow out the
plan of attack as indicated by Lord Methuen in his despatch.
“The night march was ordered for 12.30 A.M., the bearings and
distance having been ascertained at great personal risk by Major
Benson, Royal Artillery, my Deputy-Assistant-Adjutant-General. The
distance is two and a half miles, and daybreak was due at 3.25 A.M. I
may remark that two rifles went off by accident before the march
commenced, and it is pretty clear flashes from a lantern gave the
enemy timely notice of the march. Before moving off, Major-General
Wauchope explained all he intended to do, and the particular part
each battalion of his brigade was to play in the scheme, namely, that
he intended to march direct on the south-west spur of the kopje,
and on arrival near the objective before daybreak the Black Watch
were to move to the east of the kopje, where he believed the enemy
to be posted under shelter, whilst the Seaforth Highlanders were to
march straight to the south-east point of the kopje, with the Argyll
and Sutherland Highlanders prolonging the line to the left, the
Highland Infantry to be in reserve until the action was developed.
The Brigade was to march in mass of quarter column, the four
battalions keeping touch, and if necessary ropes were to be used for
the left guides. These ropes were taken, but, I believe, used by only
two battalions. The three battalions were to extend just before
daybreak—two companies in firing line, two companies in support,
and four companies in reserve—all at five paces interval between
them.”
It is not our business to criticise the scheme of attack, but only to
deplore the fact that so many brave men should lose their lives in
such an abortive attempt. It would have been impossible to reach
the Boer lines in anything but disorder had the Highland Brigade not
advanced in close column: the blunder appears to have been that
they maintained close formation too long. Long before, in the year
1746, the Highlanders, who might be expected to have an intimate
knowledge of the country through which they were passing, set out
upon a similar night attack, only to find themselves hopelessly lost—
and that not so very far from Inverness. At Magersfontein the
distance was a short one, but the difficulty of ascertaining how far
the Boer trenches were from the foremost columns led to chaos. No
one has described the situation more graphically than Sir Arthur
Conan Doyle in The Great Boer War. “With many a trip and stumble,”
he writes, “the ill-fated detachment wandered on, uncertain where
they were going and uncertain what it was they were meant to do.
Not only among the rank and file, but among the principal officers
there was the same absolute ignorance. Brigadier Wauchope knew,
no doubt, but his voice was soon to be stilled in death. The others
were aware, of course, that they were advancing either to turn the
enemy’s trenches or to attack them, but they may well have argued
from their own formation that they could not be near the riflemen
yet. Why they should be still advancing in that dense clump we do
not now know, nor can we surmise what thoughts were passing
through the mind of the gallant and experienced chieftain who
walked beside them.... Out there, close beside him, stretched the
long trench, fringed with its line of fierce, staring, eager faces, and
its bristle of gun-barrels. They knew he was coming. They were
ready. They were waiting. But still, with the dull murmur of many
feet, the dense column, nearly four thousand strong, wandered
onwards through the rain and the darkness, death and mutilation
crouching upon their path.”
The end came quickly enough. Within a few hundred yards the Boer
rifles opened fire upon the massed columns of the Highlanders. They
fell in solid ranks and companies. The destruction inside a few
moments has been rightly enough compared to the fall of corn
before the reaper. Out of the darkness there was one single lurid
blaze of light, a prolonged roar of musketry, and the Highland
Brigade was decimated as it stood.
Just as the fire opened, the order had been given for the men to
deploy, but the extension never took place. Wauchope was one of
the first to fall. As his biographer has finely said: “General Wauchope
fought and fell as a man and as a soldier, carrying out his orders
loyally to the end. He died where he would have wished to die—at
the head of his gallant Highlanders, with his face to the foe.”
It was impossible for the Highland Brigade to advance in any order:
their officers were killed, their ranks were broken, they were
confronted by barbed wire and strong entrenchments, and yet it
came hardly on them that they should have to retreat. F. G. Tait, the
famous Scottish golfer, who was destined to fall at the Modder River,
remarked in a letter home: “General Wauchope and our Colonel, and
Captain Bruce and young Edmonds were all killed, with the lot of
men that I accompanied. General Wauchope is in no way responsible
for the fearful loss of life amongst the Highland Brigade: he got his
orders, and had to carry them out, and he was killed in front of his
brigade. I feel certain that if we had been led up in line we should
have rushed the position with probably a quarter of the loss that we
actually suffered. As it was, we arrived rather late, and in mass of
quarter column.... You might imagine the effect of a tremendously
hot rifle fire into that compact body.”[11]
According to F. G. Tait the first orders that emerged from the chaos
and noise and the groans of the wounded were those of, ‘Lie down,
fix bayonets, and prepare to charge.’ This, unhappily, led very little
farther. Tait writes as follows: “We got along a hundred yards or so
when we got into the dreadful flanking as well as frontal firing, and
lost very heavily. I could now see that the enemy were in trenches
about 200-250 yards off. We managed to get 50 yards nearer, losing
heavily all the time, and there we lay down (what was left of the lot
with me) and began firing. I was about 15 or 20 yards in front, and
had just got up to get back in line when I got a bullet through my
left thigh. I was able to turn over on my stomach and fire at the
Boers. A quarter of an hour later it was quite light, and then we
began to get it properly. The men on each side of me were hit
straight away, and in a few minutes very few were left unhit. It was
quite impossible for any ambulance or doctor to advance, so all our
wounded lay within 200 yards or so of the Boer trenches all day in a
broiling sun, being shot at whenever they moved until seven o’clock
at night, most of them without a drop of water.”
And yet out of this dismal event, despite their terrible position, the
Highland Brigade did not lose their prestige. Trapped, bewildered,
unable either to advance or retreat, they held their ground and died
without fear. Many, indeed, perceiving that no officers were left to
lead them, advanced on their own initiative through the hail of fire,
and were discovered in the morning suspended on the barbed wire
before the Boer trenches. A section of the Black Watch, it is
recorded, refused to retire, and entrenching themselves as far as
they could, carried on the combat throughout the long terrible day,
until when night fell there was not one single survivor left. All
through that desperate day the Highlanders lay exposed to the Boer
fire, refusing to surrender, without food or water, wounded and
unwounded together, awaiting the support from the artillery and the
reserves, which was so difficult to give. It has been recorded of the
Argyll and Sutherlands that their claim to the pledge, “We die, but
we do not surrender,” was most nobly earned that day. At
Magersfontein the regiment that had provided the ‘thin red line’ at
Balaclava remained steady under the terrific fire, and it was owing in
a large degree to the 93rd and to the Coldstream Guards that their
unfortunate comrades, who had led the advance and suffered more
terribly, were enabled to hold out during the day.
To return to the actual conflict. It is stated that within a few
moments of the opening of the Boer fire at least 600 men were out
of action. Less courageous or disciplined soldiers would have broken
and scattered wildly to the rear, and none could have called them
cowards; but the Highland Brigade, assembling as far as was
possible within their own units, had by the break of day made some
attempt at following up the belated attack. Unfortunately the Boers
were so securely entrenched that it was a very one-sided affair. The
rising sun brought the Horse Artillery up at the gallop, and under
cover of their fire the Highland Brigade were enabled to get some
respite from the deadly Boer marksmanship. As day advanced
reinforcements were hurried up, the Gordons coming with the 1st
and 2nd Battalions of the Coldstreams, and the gallant Yorkshire
Light Infantry to protect the flank. In the afternoon the Highland
Brigade—who had tasted neither food nor water for twenty-four
hours—made a pitiful effort to charge the Boer position. The fire that
was opened upon them was, at so short a range, almost
annihilating. It was inevitable that they must remain out of action
until they could fall back and reassemble. The Gordons, who came
fresh into action, did what was possible to distract the Boer fire from
their unhappy comrades, and when the evening came the merciful
darkness enabled the wreckage of the Highland Brigade to creep
back to the rear.
The bitterest day in the story of the Highland regiments was, at last,
at an end. The disaster at Magersfontein brought with it a loss of
nearly 1000 men; out of the Highland Brigade 57 officers had fallen,
and in the Black Watch alone 19 officers and over 300 men. Never in
the annals of that regiment had there been such a loss since the
action at Ticonderoga in 1757.
In his report of the action, Lord Methuen sums it up as follows: “The
attack failed. The inclement weather was against success. The men
in the Highland Brigade were ready enough to rally, but the paucity
of officers and non-commissioned officers rendered this no easy
matter. I attach no blame to this splendid brigade. Nothing could
exceed the conduct of the troops from the time of the failure of the
attack at daybreak. There was not the slightest confusion, though
the fight was carried on under as hard conditions as one can
imagine, for the men had been on the move from midnight, and
were suffering terribly from thirst.”
The next morning the Boers awaited a British attack, which never
came. It was evident from the disaster that had overtaken the
Highland Brigade that it would be almost impossible to storm the
Boer position by a frontal assault. Lord Methuen, feeling that he
could not carry out a flanking movement without reinforcements,
decided he would rest his troops, and postpone for the present the
advance on Kimberley.
CHAPTER XXVI
PAARDEBERG AND LADYSMITH

Pibroch of Donuil Dhu, Pibroch of Donuil,


Wake thy wild voice anew, summon Clan Conuil.
Come away, come away, hark to the summons!
Come in your war array, gentles and commons!

Regimental March.

In the meantime various engagements had taken place elsewhere,


and a curious condition of stalemate was gradually setting in, during
which the British troops kept in touch with large bodies of Boers, but
were in most cases quite unable to advance and relieve the
beleaguered townships of Ladysmith, Mafeking, and Kimberley. The
whole situation gradually formed itself for the long-awaited advance
of Sir Redvers Buller, with all its unfortunate contingencies. But we
must first deal with the engagement at Stormberg. It has been
narrated, in a former chapter, how General Gatacre—or General
‘Backacher,’ as he was called in the Service—was the first to reach
the thorny entanglements of the Dervish camp at the Atbara. He was
a man of the greatest bravery, but by no means a skilful general,
relying solely upon the courage of the British soldier. In a country
like South Africa, where a pound of personal bravery was not always
as fruitful as an ounce of strategy, optimism of this kind was only
overloading a willing horse. It was magnificent, but it could not stop
a rifle bullet at a thousand yards. Unfortunately, too, the forces
under General Gatacre had been largely drawn upon for the
assistance of Lord Methuen and Buller. On the night of December 9
he discovered that the Boers were in position at Stormberg, and with
his little force of 3000 men set out for a night march, intending to
storm the Boer trenches at dawn. The whole scheme of attack, on a
lesser scale, was painfully similar to that at Magersfontein. It was so
splendidly obvious.
By the time the men had come within reach of the Boer position
they were so tired they could hardly drag their feet along. To
Gatacre fatigue was nothing. At the break of the dawn he alone was
full of zeal and courage, and spurred on by dread of a reverse to
storm the position. Unfortunately it was the Boers who opened fire
on the British, when a deadlock instantly ensued. It was difficult to
carry the hill under such conditions; for on such occasions, when
aeroplanes did not guide artillery fire, our own guns played as much
havoc among our own infantry as among the Boers.
In a similar plight at Dargai the Gordons carried the position and
enabled their comrades to move; but here it was impossible to
extricate the men, and this led to a miserable surrender of a good
many and the forlorn retreat of the rest.
Gatacre fell back after the action, and was shortly reinforced, but the
incident had in no way improved matters for the prestige of the
British arms. Within a week Methuen had suffered a crushing reverse
at Magersfontein while Gatacre had been again beaten.
Fortunately by this time great numbers of troops were arriving in
South Africa, and soon after Sir Redvers Buller prepared for the
crossing of the Tugela River. On Friday, December 15, he advanced
from Chieveley Camp to storm the Boer position. It was the first step
towards Ladysmith. As none of the Highland regiments took part in
this action, it is merely necessary to record that the battle of Colenso
took place, and despite the heroism of the British soldiers, and in
particular the Irish Brigade, the action was lost, and our troops, after
a loss of 600, fell back on Chieveley Camp.
The first advance to the relief of Ladysmith had been severely and
ignominiously checked.
The Christmas of 1899 was as black as any through which our nation
has passed. The repeated defeats of the British forces flung a gloom
over the country that for a moment almost paralysed it. More and
more troops had been despatched to South Africa, and numbers only
seemed to magnify our disasters. At such a moment Britain turned
to her sons in this country and throughout the Empire.
But it was necessary to do more than raise new armies: the whole
country required reassurance, and the name of one man instantly
rose before the public mind. When Lord Roberts was asked to take
supreme command in South Africa, with Kitchener as his Chief of
Staff, he accepted with the same readiness that Sir Colin Campbell
displayed at the time of the Indian Mutiny. “It is God’s will,” said
Roberts, now heartbroken at the death of his son, and two days
before Christmas he left London for the front.
His very name was half the battle, for, to recall the familiar lines:
There is something that’s audacious
In the very name of ‘Bobs,’
There’s a dare and dash about it
Makes you sort of want to shout it,
So that all the world can hear it
As you cheer.

On January 10, 1900, he landed at Cape Town, and appreciated at


once the extreme gravity of the situation. The successes of the
Boers were encouraging signs of revolt amongst the Cape Colonists,
and to crush these symptoms at once Roberts set out towards the
Orange Free State, anxious at the same time to distract the pressure
upon Kimberley and Ladysmith. But there were many other things to
do. In such a country as South Africa great numbers of mounted
troops were a necessity. No attempt had been made so far to work
upon the material that was already to hand. Regiments were formed
of South African colonists, and mounted forces such as the
Yeomanry and the Australian and Canadian Horse were to prove one
of the most potent influences in the later stages of the campaign.
In the meantime there was continued bad news from the seat of
war. Again Buller had attempted to cross the Tugela River, and had
met with utter defeat. The forlorn capture of Spion Kop, with a loss
of men amounting to forty per cent, had only proved a futile
engagement and a barren victory.
Buller, who was courageous as a lion, admitted that his heart failed
him after Spion Kop, and that he feared the relief of Ladysmith had
become an impossibility. But Roberts telegraphed to him that
whatever the cost might be, Ladysmith must be relieved. In the
meantime Roberts set out upon the road to Bloemfontein with the
hope of relieving Kimberley by the end of February. On February 8
he reached Methuen’s camp on the Modder River, and knowing so
well how sore the Highland Brigade must feel over the disaster at
Magersfontein, he made them a little speech stating that he had
never campaigned without Highlanders, and hoped he would never
do so, and it was the Highlanders in India and Afghanistan who had
brought him his success. He then wired to Kimberley the three
words that were to mean so much, “We are coming.”
It was all like a rushing of clean wind in a parched land. Now for the
first time the Boers found themselves baffled as to the intentions
and plans of a British leader. They had hitherto taken it for granted—
and rightly so—that they would be forewarned of every move that
was to take place, and had acted accordingly. Lord Roberts gave
them the impression that Bloemfontein was his objective. Instead,
on February 12 he instructed General French to make a dash on
Kimberley, while he would follow with the infantry. French, the only
general to make his reputation in South Africa, and almost the only
one who did not lose it, set out with his cavalry, made his way round
the Boer position, and pierced the Boer lines. Then, hastening on, he
broke through the enemy, and that same evening entered Kimberley.
The genius of French was even more apparent at Koodoostrand
Drift, where he cut off Cronje’s retreat toward Bloemfontein. It was a
piece of military daring as great as the sudden appearance of
Montrose at Inverlochy, or Jackson at Manasses Junction. Speedily
Cronje entrenched his men, but the arrival of the infantry rendered
his ultimate surrender inevitable.
Inside the laager Cronje, despite the bitter recriminations of the
Boers, did his best to put up a stout resistance, while outside our
troops crept nearer night by night, until on February 27—the
anniversary of Majuba—the Gordon Highlanders, to whom such a
task was naturally very acceptable, advanced upon the Boer
trenches under a heavy fire, and won a position controlling the
inside of the laager. Cronje, realising that further resistance was
impracticable, sent in a notice of his surrender to Lord Roberts. The
meeting of the Boer commander and the hero of Kandahar must
have been one of the most graphic incidents in the war. An eye-
witness has narrated: “Presently the body of horsemen came past
the hospital tents into the camp. A heavy bundle of a man was
lumped atop of a wretched bony little Boer pony. Was this the
terrible Cronje? Was it possible that this was the man who had held
back the British army at Magersfontein?... Lord Roberts stepped
forward, saluted, shook hands, and handed his fallen enemy a chair:
‘You have made a gallant defence, sir; I am glad to meet so brave a
foe,’ was his greeting.”
Thus within a brief fortnight Roberts had entirely altered the whole
aspect of the war. He had inflicted a heavy defeat upon the Boers,
relieved Kimberley, and captured Cronje, together with 4000 men.
From now onwards his swift advance, his unerring judgment, and
the services of his mounted troops not merely gave fresh heart to
the Empire, but broke the confidence of the enemy.

We must now return to Ladysmith. It was on October 30, 1899, after


the humiliating disaster at Nicholson’s Nek—a disaster that can be
compared to the surrender of the Duke of York’s troops in Flanders
in the eighteenth century, that Sir George White made what
preparations he could to defend the town of Ladysmith. On
November 2 the last train had left, and the long siege commenced.
White had some 10,000 men under his command, and although the
Boer commandos numbered a very large force, the defenders
managed to give throughout the siege of four months an
exceedingly good account of themselves. Ladysmith was a place of
considerable military importance, and it would have been a signal
disaster if it had fallen into the Boer hands with so large a number of
men. At the same time it was a very difficult position to hold, being
commanded from every side by kopjes, and lying, as it were, in a
saucer. The Gordon Highlanders, who were the only representatives
of the Highland Brigade to serve in the siege, were old comrades-in-
arms to White. He had led them in the advance upon Kabul and
Kandahar. With him was Sir Ian Hamilton, who had been with the
92nd at Majuba.
From November 3 onwards the progress of the siege was marked by
daily fighting and increasingly short rations. Each regiment was
given a certain section of the circumference to defend. Time dragged
on, until by the beginning of December, news came that Buller had
reached Frere Camp, while, in the far distance, could be heard the
booming of his guns. Later, it was borne in upon the garrison that
the British force must have suffered a reverse, and that relief was
probably farther away than ever.
Enteric and typhoid were thinning out the ranks, food was running
short, and things began to look very hopeless when, in the first
gleam of light on January 6, 1900, the enemy launched a formidable
attack. The defeat of Buller had enabled the Boers to send
reinforcements from Colenso. They were full of confidence, and at
the initial assault carried everything before them. It very soon
became a case of hand-to-hand fighting, in which the Gordons were
called up with Ian Hamilton in command. The Boers were
determined to capture Ladysmith, knowing the great moral effect
that would be produced following upon their victory at Colenso. The
Manchesters, nearly overcome at Caesar’s Camp, put up a
magnificent resistance, until the Gordons came up. It was in this
advance that Colonel Dick-Cunyngham was killed.
The British were determined that their positions should never be
taken by the enemy while they survived, and in one place defended
by sixteen of the Manchesters, at the end of the day fourteen lay
killed, the remaining two out of action. Throughout that day this
fierce fighting continued, until at last the Devons, with the Gordons
and the Rifles, cleared the ridge of the enemy. It had been touch
and go, but at the last extremity the Boers could not face the
gleaming steel of the bayonet, and a few minutes later were falling
back from their trenches. A fight lasting for twenty-six hours was
over at last. “But the end,” says Sir Arthur Conan Doyle, “was not
yet. The Boer had taken a risk over this venture, and now he had to
pay the stakes. Down the hill he passed, crouching, darting, but the
spruits behind him were turned into swirling streams, and as he
hesitated for an instant upon the brink, the relentless sleet of bullets
came from behind. Many were swept away down the gorges and
into the Klip River, never again to be accounted for in the lists of
their field cornet. The majority splashed through, found their horses
in their shelter, and galloped off across the great Bulwana Plain, as
fairly beaten in as fair a fight as ever brave men were yet.”
This was the final attempt to take Ladysmith by storm, and it cost
the British 13 officers and 135 men killed, with 28 officers and 244
men wounded.
Meanwhile it had been rumoured that Ladysmith was on the point of
surrender, but the famous heliograph had bravely answered, “We
have not come to that yet,” and, indeed, rather than hand over their
arms the garrison would have fought their way towards the Tugela.
Each day found things more desperate, and relief came only in time.
Buller drove his way to within a few miles of the town, and in the
heart of the battle sent his message, “Doing well.” It was in the
night of February 28 that the Boers could be heard saddling up and
leaving Pieter’s Hill, and just before dawn Lord Dundonald,
accompanied by some cavalry, reached the British lines.
“Halt! Who goes there?” rang out the familiar challenge, at which
the dramatic and long-prayed-for answer was returned, “The
Ladysmith Relief Column.” Quickly the news spread through the
town, the good tidings that after all they had passed through, their
defence had not been in vain.
The sentiment that was uppermost both in the minds of the garrison
and throughout the Empire was best expressed by Sir George White
himself. “I thank God we have kept the flag flying,” he said in his
address to the soldiers; and it is recorded that an old Kaffir woman
remarked as she watched the troops entering Ladysmith, “These
English can conquer all things but death.”
After the siege 2000 of the garrison, refusing to take a well-deserved
and altogether necessary rest, set out upon the tracks of the
retreating Boers, surely one of the most pitiful spectacles in history.
“It is God’s mercy,” wrote Sir Arthur Conan Doyle, “that they failed to
overtake them.”
Mafeking and Bloemfontein were the only towns still to be relieved,
and the former suffered from no shortage of food.

To return to the Highland Brigade, we have not dealt with the part
that they took in the advance upon Kimberley. With the hope that he
would distract the Boers, Roberts despatched the Black Watch, the
Argyll and Sutherlands, the Seaforths, and the Highland Light
Infantry, with Hector Macdonald, popularly known as ‘Fighting Mac,’
at their head. Macdonald crossed the Modder River, seized
Koodoosberg, and sustained an attack from the Boers the next day.
For a long time it fell to the Black Watch to resist the furious
onslaught of the enemy, who were by no means satisfied to leave
the situation undisputed. It was here that Lieutenant Tait—one of
the most popular men in Scotland—was mortally wounded. There is
an interesting letter that not only records his death, but also shows
how the Highland soldiers had fallen into the manner of Boer
fighting. A private writes: “I got down beside our officer, Lieutenant
Tait, on his right hand. He said, ‘Now, men, we will fight them at
their own game.’ That meant that each man was to get behind a
rock and just pop up to fire and then down again. And we found it a
good way, for we were just as good as they were at it, and we did
not forget to let them know it either, for whenever one showed
himself, down he went with half a dozen bullets through him. After
firing for about half an hour the Boers stopped, and the order was
given not to waste our shot. Lieutenant Tait’s servant came up with
his dinner, and he asked me if I would like a bit, and I said I would,
and thanked him very much. He gave me and another man half of
his dinner between us.... Just as we finished he said, ‘I think we will
advance another fifty yards, and perhaps we will see them better
and be able to give it them hot.’ We all got ready again, and
Lieutenant Tait shouted, ‘Now, boys! We were after him like hares.
The Boers had seen us, and they gave us a hot time of it. But on we
went. Just as our officer shouted to get down he was shot.”
Lieutenant Tait was one of the most beloved men in Scotland.
Thousands had seen him upon the green, and few in Scotland could
read of his death without a sense of personal bereavement. In the
middle of June 1915 another eminent golfer of equal fame and no
less popularity, Captain John Graham, of the Liverpool Scottish, was
fated to give his life for his country. No two finer men and finer
sportsmen ever brought fairer honour to the name of Scotland in
peace and war.
The action continued all day, and eventually, on the approach of the
9th Lancers, the Boers fell back and the Highland Brigade returned
to the Modder River, having lost some fifty men. There followed
afterwards the relief of Kimberley, and from thence onwards to the
end of the war the part taken by the Highlanders was peculiarly
arduous and without many distinguished features. Month after
month they were employed in hard marching, holding positions that
the mounted troops had carried, uncomplaining as always, and
winning back here and there some of the losses that they had
suffered at the hands of the enemy at Magersfontein. We have seen
how the Gordons were instrumental in the capture of Cronje, despite
the heavy fire with which they were met from the Boer trenches,
and it is a notable fact that the Highland Brigade, for all their
handling at Magersfontein, appear to have suffered in no way in
prestige, and were only too anxious to make good. “On the 18th,”
says General Colville, speaking of the end of Cronje, “the courage
and determination shown by the Highland Brigade in their advance
over some fifteen hundred yards of perfectly open plain, and their
passage of the river, both under heavy fire, are beyond all praise.”
CHAPTER XXVII
WITH SIR IAN HAMILTON TO PRETORIA
(1900)

To you who know the face of war,


You, that for England wander far,
You that have seen the Ghazis fly
From English lads not sworn to die,
You that have lain, where, deadly chill,
The mist crept o’er the Shameful Hill,
You that have conquered, mile by mile,
The currents of unfriendly Nile,
And cheered the march, and eased the strain
When Politics made valour vain,
Ian, to you from banks of Ken,
We send our lays of Englishmen!

Andrew Lang.

It was during the halt at Bloemfontein that the Highland Brigade


received reinforcements from home, and no praise could be too high
for the volunteers who formed additional companies to the
regiments of the regular forces. To-day, when thousands and
hundreds of thousands are trained soldiers who a year ago had
never held a rifle in their hands, it would be futile to belaud the
qualities of the amateur soldier. But until the Boer War no one had
taken unprofessional soldiers very seriously. Just as the Territorials
won the esteem of the Regulars in Flanders, so the companies of
Volunteers earned the admiration and gratitude of the country in the
Boer War.
The great need at this time was still for mounted troops and more
mounted troops, and it is interesting to note that the Gordons were
to a large extent mounted to prove more effective. Our soldiers have
always been able to fit themselves for whatever was required of
them. The infantry were mounted in the South African War, and the
cavalry in the German War were placed in the trenches.
It was on May 3 that the British Army left Bloemfontein and set out
upon the road to Pretoria. De Wet, who was now to take the
ascendance in Boer generalship, and to lead the British troops in
wearisome pursuit for many months, was in command of a mobile
force moving swiftly across country, gathering food where it could.
With the utmost patience our Highlanders covered over twenty miles
a day, “winning their way,” as some one has said, “at the expense of
their boots and not of their lives.”
Lord Roberts was in command of the main division and General Ian
Hamilton was over the right column. With him were the Highland
Brigade, including the Camerons, new come from Egypt. The
Brigade, as a body, never reached Pretoria, though the Gordons and
the Seaforths entered the Boer capital. It is the march on Pretoria
with General Hamilton that we must first follow.
The Commander of the Highland Brigade was an old Gordon officer,
by training and heredity a soldier. Born in 1853, he first saw service
in the Afghan War. He was wounded at Majuba, losing the use of
one hand. He received the D.S.O. for gallantry in the Soudan, fought
in the Chitral and Tirah campaigns; and in this chapter we will
accompany him on the march to Pretoria, in which he covered four
hundred miles, fought ten engagements, and took five towns. After
the Boer War he accompanied the Japanese army to Manchuria, and
upon his return was made General Officer Commanding-in-Chief
Mediterranean and Inspector-General Overseas Forces in 1910.
No finer, more experienced, more brilliant soldier could have been
placed in command of our forces in the Dardanelles.
It was at Thabanchu Mountain that the Gordons brought additional
distinction to their name, linked with that of Captain Towse. The
British troops were having it all their own way when the Boers were
reinforced by a party of the foreign legion commanded by a Russian,
the majority of them being Germans. The situation was a very
curious one. The German troops advanced in their customary close
formation, and with their usual deliberateness, and for some time it
was not realised that they were part of the enemy’s forces. At the
same time Captain Towse, with a party of the Gordon Highlanders,
was moving in their direction, but concealed from view behind the
shoulder of the hill. The Gordons could not see the enemy any more
than the enemy could see the Gordons, and it was seen that the two
forces would confront each other at the brow of the hill. “At last,”
says Winston Churchill, “with suddenness, both parties came face to
face at fifty yards’ distance. The Germans, who had already made six
prisoners, called loudly on Captain Towse and his little band to
surrender. What verbal answer was returned is not recorded, but a
furious splutter of musketry broke out at once, and in less than a
minute the long lines of the enemy recoiled in confusion, and the top
of the hill was secured to the British.”
Unhappily, however, a chance shot deprived the gallant Captain
Towse of the sight of both his eyes. For this action he received the
Victoria Cross he so richly deserved.
The advance now proceeded on the road to Pretoria. The town was
stated to be heavily defended, and regarded as practically
impregnable. President Kruger had established himself there, and it
was thought that a very long siege would await the British. On May
29 the Gordons encountered the Boers at Crow’s Nest Hill, very close
to the place where the Jameson raiders had surrendered to Cronje,
and here the Gordon Volunteers had their chance. The Highlanders,
“in perfect discipline and with disdainful silence,” drove the Boers out
of their position, and it is worth while recording, in the words of an
eye-witness, the manner of the attack. “It was not without a thrill
that I watched this famous regiment move against the enemy. Their
extension and advance was conducted with machine regularity. The
officers explained what was required to the men. They were to
advance rapidly until under rifle fire, and then to push or not as they
might be instructed. With impassive unconcern the veterans of
Chitral, Dargai, the Bara Valley, Magersfontein, Paardeberg, and
Houtnek walked leisurely forward.”
At eight hundred yards they came in for a heavy fire from the Boer
rifles. “But the advance neither checked nor quickened. With
remorseless stride, undisturbed by peril or enthusiasm, the Gordons
swept steadily onward.”
The Boers were never able to tolerate that kind of advance, and
finding that rifles would not stop the Highlanders, they hastily
retreated, and soon afterwards General Ian Hamilton rode over to
congratulate the battalion on their exploit. Lord Roberts was not long
in sending his praise. “Tell the Gordons,” he wrote, “that I am proud
to think that I have a Highlander as one of the supporters of my
coat-of-arms.”
During this action the fourth Victoria Cross was given to the
Gordons, being awarded to Corporal Mackay, who “repeatedly
rushed forward under a withering fire at short range to attend to
wounded comrades, dressing the wounds, while he himself was
without shelter, and in one instance carrying a wounded man from
the open under a heavy fire to the shelter of a boulder.”
On May 31 the Union Jack flew over Johannesburg. At this point
General French arrived, and as senior officer took command. General
Sir Ian Hamilton then thanked the Gordons, “the, regiment my
father commanded and I was born in,” for their support. On June 3
the army set out for Pretoria, when suddenly the whole
contemplated resistance of the Boers faded away like smoke.
President Kruger, not forgetting two millions of money, but leaving
his wife instead, hurried to Delagoa Bay, and with his departure
came the unconditional surrender of Pretoria. It had been a long and
arduous march, covering forty-five days and some four hundred
miles of country. The Highlanders engaged in nine actions, and
occupied five towns. It must have been a dramatic and inspiring
spectacle to see the Gordons and the Camerons, gaunt and lean
with all the fatigue through which they had passed, in tattered
clothes and soleless boots, marching into the Boer capital. It might
have been thought that the fall of Pretoria would have brought with
it the conclusion of the Boer War. But the fall of Pretoria held no
special significance to the Boers. Many of them had probably never
seen the town, and took no interest in it. They resorted to a manner
of warfare peculiarly suited to their habits of life, and which,
developing over an extensive country, threatened a hopeless
stalemate. They hoped by a guerilla warfare to weary the British
forces into a favourable peace. From this point to the end of the war
that agile leader De Wet was to make his name familiar as a kind of
military will-o’-the-wisp.
Every week brought with it news of some minor engagement in
some isolated part of the country. Here a position had been attacked
or there a convoy had been seized. Often it was a raid on the long
line of railway running from Capetown to Pretoria, but always De
Wet, despite the efforts of the British, would manage to elude
capture and fling his burghers upon another part of our lines.
On July 11, 1900, the Gordons won their fifth Victoria Cross, and
established a record in the history of the Army. An officer who was
present has recorded the incident. “The enemy’s position,” he says,
“consisted of two long hills, with a ‘nek’ between them about five
hundred yards long. In front of, and about six hundred yards away
from the nek were two small kopjes. The guns galloped up between
these kopjes, which were one hundred and fifty yards apart, and
opened fire on the big hill on the right. The Gordons were advancing
behind the guns in open order. The guns fired a few shots, and then
suddenly the enemy opened fire from the hill on the left, which was
only eight hundred and fifty yards away. Very soon fifteen out of the
seventeen British gunners were wounded, so that the guns could no
longer be worked. The Gordons by this time had reached the kopjes,
and were about one hundred yards from the guns, the intervening
space being in the enemy’s line of fire. At this moment orders were
signalled by the General in the rear, from Lord Roberts at Pretoria,
telling General Smith-Dorrien to retire. The Colonel of the Gordons,
reluctant to leave the guns to fall into the enemy’s hands, sent up
the teams of horses to fetch them, but the Boer bullets were raining
around, and two of the horses were shot. Colonel Macbean then
shouted for volunteers to fetch in the guns. Captains Younger,
Gordon the Adjutant, and Allan called on the few men around. They
ran out under heavy fire, and with the greatest difficulty they
dragged back the gun along seventy yards of the way, but it would
not even then have been saved if three more men had not run out
and helped for the remaining thirty yards to the kopje. As it was,
one of the men was hit only ten yards from the kopje, but he was
got in all right. Captain Allan was now ordered away with his
company to the left flank, where they were kept for the rest of the
day, but Captain Younger, with several men, ran out to try and save
the second gun. It was got in, but not before Captain Younger was
shot dead.”[12]
This incident is interesting, not only as a record of a gallant feat of
arms, but also because this Captain Gordon who won the Victoria
Cross was later on to command the Gordons in the present war, and
unhappily to fall a prisoner with many of his men.
At the end of August Lord Roberts met Buller and French at Belfast.
Botha, a very able general, and the future conqueror of German
South-West Africa, was beaten at Middelburg, and this defeat added
the Transvaal to the British Empire. The news that Kruger had fled to
the Portuguese was another disappointment to the enemy, but their
determination to resist the British was so strong that they refused to
surrender, for a long time carrying on the unequal contest.
To return to the history of the Gordons in South Africa, the Volunteer
companies assisted Buller against the Boers in Natal, and came into
action against Botha. Throughout their engagements they acted up
to the highest traditions of the Highland regiments. Early in
September there was a dramatic and picturesque scene, when the
two battalions of the Gordons came face to face. “The old 75th, with
their Dargai laurels scarcely faded, were meeting the 92nd on a
Welcome to our website – the ideal destination for book lovers and
knowledge seekers. With a mission to inspire endlessly, we offer a
vast collection of books, ranging from classic literary works to
specialized publications, self-development books, and children's
literature. Each book is a new journey of discovery, expanding
knowledge and enriching the soul of the reade

Our website is not just a platform for buying books, but a bridge
connecting readers to the timeless values of culture and wisdom. With
an elegant, user-friendly interface and an intelligent search system,
we are committed to providing a quick and convenient shopping
experience. Additionally, our special promotions and home delivery
services ensure that you save time and fully enjoy the joy of reading.

Let us accompany you on the journey of exploring knowledge and


personal growth!

ebookultra.com

You might also like