Programming The Browser - PowerPoint PPT Presentation

1 / 43
About This Presentation
Title:

Programming The Browser

Description:

To change the default message in the window's status bar, we need to use the ... clock you set the clock to make a ringing noise when a certain event happens. ... – PowerPoint PPT presentation

Number of Views:14
Avg rating:3.0/5.0
Slides: 44
Provided by: ahad6
Category:

less

Transcript and Presenter's Notes

Title: Programming The Browser


1
  • Programming The Browser

2
  • In this lecture, we want to find out how to write
    script for the web browser. Using this, we can
    start to create more impressive web pages.
  • Not only JavaScript is object-based, but the
    browser is also made up of objects. When
    JavaScript is running in the browser, we can
    access the browsers objects in exactly the same
    way we used JavaScripts native objects in the
    last chapter. But what kinds of objects does the
    browser provide for us to use?
  • The collection of objects that the browser makes
    available to us for use with JavaScript is
    generally called the Browser Object Model (BOM).
  • In this lecture we will concentrate on the core
    functionality of the BOM, which are the objects
    that are common to all browsers. We can achieve a
    lot in JavaScript by just sticking to such
    objects.

3
  • Introduction to the Browser Objects
  • When JavaScript is running in a web page, it has
    access to a large number of other objects made
    available by the web browser Rather like the Math
    object, these are created for us rather than us
    needing to create them explicitly. As mentioned,
    the objects, their methods, properties, and
    events are all mapped out in something called the
    Browser Object Model (BOM).
  • The BOM is very large and potentially
    overwhelming at first. However, we will looking
    at the more commonly used parts of the BOM

4
  • The BOM has a hierarchy. At the very top of this
    hierarchy is the window object. You can think of
    this as representing the frame of the browser and
    everything associated with it, such as the
    scrollbars, navigator bar icons, and so on.
  • Contained inside our window frame is the page.
    The page is represented in the BOM by the
    document object. You can see this represented in
    following figure.

5
  • The window ObjectOur Window onto the Page
  • The window object represents the browsers frame
    or window in which your web page is contained. To
    some extent, it also represents the browser
    itself and includes a number of properties that
    are there simply because they dont fit anywhere
    else. For example, via the properties of the
    window object, we can find out what browser is
    running, the pages the user has visited, the size
    of the browser window, the size of the users
    screen, and much more. We can also use the window
    object to access and change the text in the
    browsers status bar, change the page that is
    loaded, and even open new windows.
  • The window object is a global object, which means
    we dont need to use its name to access its
    properties and methods. In fact, the global
    functions and variables (the ones accessible to
    script anywhere in a page) are all created as
    properties of the global object.

6
  • For example, the alert () function we have been
    using since the beginning of the book is, in
    fact, the alert () method of the window object.
    Although we have been using this simply as
  • we could write
  • However, since the window object is the global
    object, it is perfectly correct to use the first
    version.

7
  • Some of the properties of the window object are
    themselves objects. Those common to both IE and
    NN include the document, navigator, history,
    screen, and location objects.
  • The document object represents our page, the
    history object contains the history of pages
    visited by the user.
  • The navigator object holds information about the
    browser.
  • The screen object contains information about the
    display capabilities of the client.
  • The location object contains details on the
    current pages location. Well look at these
    important objects individually later in the
    chapter.

8
  • Using the window Object
  • Lets start with a nice, simple example in which
    we change the default text shown in the browsers
    status bar The status bar (usually in the bottom
    left of the browser window) is usually used by
    the browser to show the status of any document
    loading into the browser. For example, on IE,
    once a document has loaded, youll normally see
    Done in the status bar, and in Navigator, it
    normally says Document
  • Done. Lets change that so it says Hello and
    Welcome.
  • To change the default message in the windows
    status bar, we need to use the window objects
    defaultstatus property. To do this we can write

9
  • or, because the window is the global object, we
    can just write
  • Either way works, however it is preferable to
    write window in front because it makes clear
    exactly where the defaultStatus property came
    from. Otherwise we might think that defaultstatus
    is a variable name. This is particularly true
    when using less common properties and methods,
    such as defaultstatus. For properties like
    document or methods like alert (), youll find
    that you become so familiar with them that you
    dont need to put window in front to remind you
    of their context.

10
  • Lets put our code in a page.
  • At this point, its worth highlighting the point
    that within a web page you shouldnt use names
    for your functions or variables that conflict
    with names of BOM objects or their properties and
    methods. if you do, you may not get an error, but
    instead get unexpected results. For example, in
    the following code we declare a variable named
    defaultStatus. We then try to set the
    defaultstatus property of the window object to
    Welcome to my website. However, this wont
    change the default message in the status bar
    instead the value in the defaultstatus variable
    will be changed.

11
  • In this situation we need to either use a
    different variable name or add window in front of
    the defaultstatus property we want to change.
  • This will have the effect that we want, that is,
    the message in the status bar will change.
    However, this way of writing things can obviously
    make code very confusing, so it is usually best
    not to use BOM object, property, or method names
    as variable names.
  • As with all the BOM objects, there are lots of
    properties and methods we could look at for the
    window object. However, in this chapter well
    concentrate on the history, location, navigator,
    screen, and document properties. All five of
    these properties contain objects (the history,
    location, navigator, screen, and document
    objects), each with its own properties and
    methods. in the next few pages, well look at
    each of these objects in turn and find out how
    they can help us make full use of the BOM.

12
  • The history Object
  • The history object keeps track of each page that
    the user visits. This list of pages is commonly
    called the history stack for the browser it
    enables the user to click the browsers Back and
    Forward buttons to revisit pages. We have access
    to this object via the window objects history
    property.
  • Like the native JavaScript Array object, the
    history object has a length property. This can be
    used to find out how many pages are in the
    history stack.
  • As you might expect, the history object has the
    back () and forward () methods. When they are
    called, the location of the page currently loaded
    in the browser is changed to the previous or next
    page that the user has visited.

13
  • The history object also has the go () method.
    This takes one parameter that specifies how far
    forward or backward in the history stack you want
    to go. For example, if you wanted to return the
    user to the page before the previous page, youd
    write
  • To go forward three pages, youd write
  • Note that go (-1) and back() are equivalent, as
    are go(.l) and forward()

14
  • The location Object
  • The location object contains lots of potentially
    useful information about the current pages
    location. Not only does it contain the URL
    (Uniform Resource Locator) for the page, but also
    the server hosting the page, the port number of
    the server connection, and the protocol used.
  • This information is made vailable through the
    location objects href, hostname, port, and
    protocol properties. However, many of these
    values are only really relevant when we are
    loading the page from a server and not, as we are
    doing in our examples at present, loading the
    page directly from a local hard drive.
  • In addition to retrieving the current pages
    location, we can also use the methods of the
    location object to change the location and
    refresh the current page.

15
  • Changing Locations
  • We can navigate to another page in two ways. We
    can either set the location objects href
    property to point to another page, or we can use
    the location objects replace () method. The
    effect of the two is the same the page changes
    location. However, they differ in that the
    replace () method removes the current page from
    the history stack and replaces it with the new
    page we are moving to, whereas using the href
    property simply adds the new page to the top of
    the history stack. This means that if the replace
    () method has been used and the user clicks the
    Back button in the browser, the user cant go
    back to the original page loaded, if the href
    property has been used, the user can use the Back
    button as normal.
  • For example, to replace the current page with a
    new page called myPage htm, wed use the replace
    () method and write

16
  • This will load myPage htm and replace any
    occurrence of the current page in the history
    stack with myPage htm.
  • To load the same page and to add it to the
    history of pages navigated to, we use the href
    property
  • and the page currently loaded is added to the
    history. Since as the window object is global
    throughout the page, we could have written the
    following
  • or

17
  • The navigator Object
  • The navigator object is another object that is a
    property of the window object and is available in
    both IE and NN browsers, despite the name. its
    name is more of a historical thing, rather than
    being very descriptive. Perhaps a better name
    would be the browser object, because the
    navigator object contains lots of information
    about the browser and the operating system in
    which its running.
  • Probably the most common use of the navigator
    object is for handling browser differences. Using
    its properties, we can find out which browser,
    version, and operating system the user has. We
    can then act on that information and make sure
    the user is directed to pages that will work with
    his browser The last section in this chapter is
    dedicated to this important subject, so we will
    not discuss it further here.

18
  • The screen Object
  • The screen object property of the window object
    contains a lot of information about the display
    capabilities of the client machine. Its
    properties include the height and width
    properties, which indicate the vertical and
    horizontal range of the screen in pixels.
  • Another property of the screen object, which we
    will be using in an example later, is the
    colorDepth property. This tells us the number of
    bits used for colors on the clients screen.

19
  • The document ObjectThe Page Itself
  • Along with the window object, the document object
    is probably one of the most important and
    commonly used objects in the BOM. Via this object
    you can gain access to the properties and methods
    of some of the objects defined by HTML tags
    inside your page.
  • The document object has a number of properties
    associated with it, which are also arrays. The
    main ones are the forms, images, and links
    arrays. IE 4 and IE 5 support a number of other
    array properties, such as the all array property,
    which is an array of all the tags represented by
    objects in the page. Netscape also has a few
    additional arrays that are not supported by IE,
    for example the tags array. However, well be
    concentrating on using objects that have
    cross-browser support, so that we are not
    limiting our web pages to just one browser
  • Well be looking at the images and links arrays
    shortly. A third array, the forms array, will be
    one of the topics of the next chapter when we
    look at forms in web browsers. First, though,
    well look at a nice, simple example of how to
    use the document objects methods and properties.

20
  • Using the document Object
  • Weve already come across some of the document
    objects properties and methods, for example the
    write () method and the bgColor property.
    Appendix C has a full list of the available
    properties and methods, and well be using more
    of them later in the book.
  • In the next example we set the background color
    of the page to a color dependent on how many
    colors the users screen supports. This is termed
    screen color depth. If the user has a display
    that supports just two colors (black and white),
    theres no point in us setting the background
    color to bright red. We accommodate this by using
    JavaScript to set a color the user can actually
    see.

21
(No Transcript)
22
  • You can test that the code is working properly by
    changing the colors supported by your screen.
  • On Windows, you can do this by right-clicking on
    the desktop and choosing the Properties option.
    Under the Settings tab, there is a section called
    Colors in which you can change the number of
    colors supported. By refreshing the browser, you
    can see what difference this makes to the color
    of the page.
  • On Netscape 6, its necessary to shut down and
    restart the browser to observe any effect.

23
  • The images Array
  • As we know, we can insert an image into an HTML
    page using the following tag
  • The browser makes this image available for us to
    script in JavaScript by creating an img object
    for it with the name mylmage. In fact, each image
    on your page has an img object created for it.
  • Each of the img objects in a page is stored in
    the images array. This array is a property of
    the document object. The first image on the page
    is found in the element document images 0, the
    second in document, images 1, and so on.

24
  • If we want to, we can assign a variable to
    reference an img object in the images array.
    it can make code easier to read. For example, if
    we write
  • the mymage2 variable will contain a reference to
    the img object inside the images 1 array at
    index position 1. Now we can write mylmage2
    instead of document. images 1 in our code, with
    exactly the same effect.
  • We can also access img objects in the images
    array by name. For example, the img object
    created by the ltimggt tag, which has the name
    mylmage, can be accessed in the document objects
    images array property like this

25
  • Because the document. images property is an
    array, it has the properties of the native
    JavaScript Array object, such as the length
    property. For example, if we want to know how
    many images there are on the page, the code
    document, images length will tell us.
  • The img object itself has a number of useful
    properties we can utilize. The most important of
    these is its src property. By changing this we
    can change the image thats loaded. We
    demonstrate this in the next example.

26
  • When this page is loaded into the browser, a
    prompt box asks you to enter a number from 0 to
    3. A different image will be displayed depending
    on the number you enter.

27
  • The links Array
  • For each hyperlink tag ltAgt defined with an href
    attribute, the browser creates an A object. The
    most important property of the A object is the
    href property, corresponding to the href
    attribute of the tag. Using this, we can find out
    where the link points to and can change this,
    even after the page has loaded.
  • The collection of all A objects in a page is
    contained within the links array, in a similar
    way to the img objects in the images array
    that we saw earlier.

28
  • Connecting Code to Web Page Events
  • Events occur when something in particular
    happens. For example, the user clicking on the
    page, clicking on a hyperlink, or moving his
    mouse pointer over some text all cause events to
    occur Another example, which is used quite
    frequently, is the load event for the page.
  • Why are we interested in events?
  • Take as an example the situation where we want to
    make a menu pop up when the user clicks anywhere
    in our web page. Assuming that we can write a
    function that will make the popup menu appear,
    how do we know when to make it appear, or in
    other words, when to call the function? We
    somehow need to intercept the event of the user
    clicking in the document, and make sure our
    function is called when that event occurs.

29
  • To do this, we need to use something called an
    event handler. We associate this with the code
    that we want to execute when the event occurs.
    This provides us with a way of intercepting
    events and making our code execute when they have
    occurred. You will find that adding an event
    handler to our code is often known as connecting
    our code to the event. Its a bit like setting
    an alarm clockyou set the clock to make a
    ringing noise when a certain event happens. With
    alarm clocks, the event is when a certain time is
    reached.
  • Event handlers are made up of the word on and the
    event that they will handle. For example, the
    click event has the onclick event handler, and
    the load event has the onload event handler.
  • A number of ways exist to connect your code to an
    event using event handlers were going to look
    at two of the more useful ways.

30
  • Event Handlers as Attributes
  • The first and most common method is to add the
    event handlers name and the code we want to
    execute to the HTML tags attributes.
  • Lets create a simple HTML page with a single
    hyperlink, given by the element ltAgt. Associated
    to this element is the A object. One of the
    events the A object has is the click event. The
    click event fires, not surprisingly, when the
    user clicks on the hyperlink.

31
  • As it stands this page does nothing a normal
    hyperlink doesnt do. You click it, and it
    navigates this window to another page, called
    somepage.htm, which would need to be created.
    Theres been no event handler added to the link
    yet!
  • As we mentioned, one very common and easy way of
    connecting the event to our code is to add it
    directly to the tag of the object whose event we
    are capturing. In this case, its the click event
    of the A object, as defined by the ltAgt tag. On
    clicking the link, we want to capture the event
    and connect it to our code. We need to add the
    event handler, in this case onclick, as an
    attribute to our ltAgt tag. We set the value of the
    attribute to the code we want executing when the
    event occurs.
  • Lets rewrite our ltAgt tag to do this as follows

32
  • You can see that we have added onclickalert(
    You Clicked?)!! To the definition of the ltAgt
    tag. Now, when the link is clicked, we see an
    alert box. After this, the hyperlink does its
    usual stuff and takes us to the page defined in
    the href attribute.
  • This is fine if you just have one line of code to
    connect to the event handler, but what if you
    want a number of lines to execute when the link
    is clicked?
  • Well, all you need to do is define the function
    you want to execute and call it in the onclick
    code. Lets do that now.

33
  • T
  • I

34
  • Within the script block we have created a
    function, just a standard function, and given it
    a descriptive name to help us when reading the
    code.
  • In the preceding example, the function is called
    linksomePage_ onclick() since we are referring to
    the onclick event handler for the A object with
    name linksomePage. Note that this naming
    convention is not compulsory, and you can use
    whatever convention you prefer as long as you are
    consistent.
  • Our onclick attribute is now connected to some
    code that calls the function linksomePage_onclick
    (). Therefore, when the user clicks the
    hyperlink, this function will be executed.
  • Youll also see that the function returns a
    value, true in this case. Also, where we define
    our onclick attribute, we return the return value
    of the function by using the return statement
    before the function name. Why do we do this?

35
  • The value returned by onclick return
    linkSomePage_onclick () is used by JavaScript to
    decide whether the normal action of the link,
    that is, going to a new page, should occur if we
    return true, the action continues, and we go to
    somepage htm.
  • If we return false, the normal chain of events
    (that is, going to somepage htm) does not happen.
    We say that the action associated with the event
    is canceled. Try changing the function to this

36
  • Now youll find that you just get a message, and
    no attempt is made to go to somepage htm.
  • Not all objects and their events make use of the
    return value, so sometimes its redundant. Also,
    its not always the case that returning false
    cancels the action. For reasons of browser
    history rather than logic, its sometimes true
    that cancels the action. Generally speaking, its
    best to return true and deal with the exceptions
    to this as you find them.
  • Some events are not directly linked with the
    users actions as such. For example, the window
    object has the load event, which fires when a
    page is loaded, and the unload event, which fires
    when the page is unloaded (that is, either the
    user closes the browser or moves to another
    page).

37
  • Event handlers for the window object actually go
    inside the ltbodygt tag. For example, to add an
    event handler for the load and unload events,
    wed write the following
  • Notice that we have specified the language
    attribute of the ltbodygt tag as JavaScript. This
    is because the ltbodygt tag is not contained within
    a JavaScript script block defined with the
    ltscriptgt tag. As usual, since JavaScript is the
    default scripting language, this can be left off.

38
  • Event Handlers as Properties
  • The second way of connecting to events is to use
    event handler property of the objects.
  • In this way of connecting to events, we first
    need to define the function that will be executed
    when the event occurs. Then we need to set that
    objects event handler property to the function
    we defined.
  • This is illustrated in the following example.

39
(No Transcript)
40
  • We define the function linksomePage_onclick ( ) ,
    much as we did before. As before we can return a
    value indicating whether we want the normal
    action of that object to happen.
  • Next we have the ltAgt tag, whose objects event we
    are connecting to. Youll notice there is no
    mention of the event handler or the function
    within the attributes of the tag.
  • The connection is made between the objects event
    and our function on the final lines of script, as
    shown in the following

41
  • As we saw before, document. links 0 returns the
    A object corresponding to the first link in our
    web page, which is our linksomePage hyperlink. We
    set this objects onclick property to reference
    our function name. This makes the connection
    between the objects event handler and our
    function. Note that no parentheses are added
    after the function name. Now whenever we click
    the link, our function gets executed.
  • The first method of connecting code to events is
    easier, so why would we ever want to use the
    second?
  • Perhaps the most common situation in which you
    would want to do this is where you want to
    capture an event for which there is no HTML tag
    to write your event handler as an attribute. It
    is also useful in situations where you want the
    code attached to an event handler to be changed
    dynamically. ( See Example)
  • Lets look at another example in which we connect
    to a hyperlinks click event to randomly change
    the image loaded in a page.

42
(No Transcript)
43
  • Load the page into your browser You should see a
    page like that shown in Figure 5-3.
  • if you click on an image, youll see it change to
    a different image, and that image is selected
    randomly.
Write a Comment
User Comments (0)
About PowerShow.com