SitePoint Sponsor

User Tag List

Results 1 to 4 of 4
  1. #1
    SitePoint Evangelist Pixelateur's Avatar
    Join Date
    Feb 2006
    Location
    Hamburg, Germany
    Posts
    593
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Question Start function depending on body id

    Hi,

    I have a function "showMap" in an external Javascript file and want this function to fire whenever the page with <body id="about_us"> is requested. The function looks like this:

    function showMap() {
    ...
    }

    How can can I get this function to run without using any inline handlers like "onload()" etc.? Sorry, I am new to Javascript...

  2. #2
    SitePoint Guru Ize's Avatar
    Join Date
    Nov 2005
    Location
    The Netherlands
    Posts
    808
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    If you don't already have a window.onload call somewhere, you can execute this function like this:

    Code javascript:
    window.onload = function (){
      if (document.getElementsByTagName('body')[0].id == 'about_us')
        showMap();
    }

  3. #3
    SitePoint Wizard silver trophy kyberfabrikken's Avatar
    Join Date
    Jun 2004
    Location
    Copenhagen, Denmark
    Posts
    6,157
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    You could refrain from including the external javascript on all but the page, where you want it to fire.

    Otherwise, you add the following javascript to your document:
    Code:
    window.onload = function() {
      if (document.body.id == "about_us") {
        showMap();
      }
    }

  4. #4
    SitePoint Evangelist Pixelateur's Avatar
    Join Date
    Feb 2006
    Location
    Hamburg, Germany
    Posts
    593
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Yes, works great. Thanks a lot, you just saved me an awful lot of time :-)


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •