SitePoint Sponsor

User Tag List

Results 1 to 4 of 4
  1. #1
    SitePoint Member
    Join Date
    Oct 2013
    Location
    Canada
    Posts
    15
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    GetElementById from external JS file. Using the onclick event handler from input.

    This isn't working, tried bunch of different ways. It is from a Javascript beginners book.

    html

    HTML Code:
    <input type="button" value="click me" id="say_hi" />
    Code:
    function hi_and_by() {
          window.alert("Hi");
          window.alert("By");
    }
    
    document.getElementById("say_hi").onclick = hi_and_by;
    also tried this.


    Code:
    function hi_and_by() {
          window.alert("Hi");
          window.alert("By");
    }
    
    var hi_button = document.getElementById("say_hi");
    hi_button.onclick = hi_and_by;

    Neither of them do anything when I click the button.

  2. #2
    It's all Geek to me silver trophybronze trophy
    ralph.m's Avatar
    Join Date
    Mar 2009
    Location
    Melbourne, AU
    Posts
    23,592
    Mentioned
    411 Post(s)
    Tagged
    6 Thread(s)
    It will work if you link to the script just before the closing </body> tag. That's the recommended place for scripts nowadays.

  3. #3
    SitePoint Member
    Join Date
    Oct 2013
    Location
    Canada
    Posts
    15
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Thank you very much, solved the problem perfectly.

  4. #4
    SitePoint Guru Vincent Puglia's Avatar
    Join Date
    Feb 2000
    Location
    where the World once stood
    Posts
    700
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Hi,

    if that was exactly what the author of the book told you to do, get your money back. In all likelihood there is worse to come.

    If you're curious, the problem was that the document.getElementById statement was being executed before the page was loaded. You can write javascript within the 'head' tags, but if it is meant to interact with something on that page, that something has to exist. So, the rule of thumb is: if the code isn't a function, it doesn't belong in the head.
    Where the World Once Stood
    the blades of grass
    cut me still


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
  •