1

Here is all of my code... The inline JavaScript alert is firing off nicely, but the external alert is not. Whenever I reload the page I get a console error log saying "TypeError: tileBlock is null".. Any ideas? I've yet to come across this issue and I'd rather not be forced into writing all of my Javascript event handlers inline. Thanks!

#tileBlock {
    position: fixed;
        top: 0;
        right: 0;
        bottom: 0;
        left: 0;
        background-color: #0b0b0b;
        background-position: center;
        background-repeat: no-repeat;
        background-image: url(photo.jpg);
        border: 20px solid #fff;
        background-size: cover;  
    }

    @media (max-width: 400px) {
      #tileBlock {
        border-width: 8px;
      }
    }


<body>
  <div class="wrapper" id="tileBlock" onclick="alert('You clicked (inline)')"></div>
</body>




var tileBlock = document.getElementById('tileBlock');
tileBlock.onclick = function() {
    alert('you clicked(external script)');
}
3
  • 3
    Your script should be inside <script></script> tags Commented May 22, 2014 at 17:56
  • It's in an external Javascript file- and anyway I got the same result when I tried putting it in the same file in script tags Commented May 22, 2014 at 17:57
  • 1
    Then you are missing a window.onload to run the script after page load Commented May 22, 2014 at 17:58

3 Answers 3

1

Include jquery library and try this:

  $('#tileBlock').onclick(function(){
     alert('you clicked(external script)');
  });

Also I have tried your code and it works.(not my jquery) Try this: http://jsfiddle.net/XcsN/evK3v/

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks so much! I looked at your JsFiddle and it was calling the script on-load. I added the window.onload and that solved it... I did try your JQuery but that doesn't seem any simpler or more effective so I think I'll go with vanilla..
0

I just needed a window.onload... Thanks everyone for the help!

window.onload=function(){
var tileBlock = document.getElementById('tileBlock');
tileBlock.onclick = function() {
    alert('you clicked yes');
}
};

Comments

0

No need window before since it's reserved

onload=()=>{
    let elem // etc..
    elem.onclick=()=> // stuff ..
}

fiddle

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.