0

Explain to my why this works when I click the button.

<script type="text/javascript">
  function myFunction() {
    if (screen.width <= 800) {
      document.getElementById('cover-img').style.display = 'none';
    }
  }
</script>
<input type="submit" onclick="myFunction()">

While this does not:

<script type="text/javascript">
  if (screen.width <= 800) {
    document.getElementById('cover-img').style.display = 'none';
  }
</script>

It returns the error:

Uncaught TypeError: Cannot read property 'style' of null

3
  • 3
    The second one is running when the page loads, and so you probably have the script up in the <head>, which is before the element exists. Move your script to just before the </body>, and it should work. Commented Jun 10, 2016 at 14:09
  • Probably because cover-img doesn't exist at the time when you execute the script Commented Jun 10, 2016 at 14:09
  • 1
    Possible duplicate of Why does jQuery or a DOM method such as getElementById not find the element? Commented Jun 10, 2016 at 14:16

2 Answers 2

3

you can do that with pure css

@media(max-width:75em){
    #mydiv{
        display:none;
    }
}
Sign up to request clarification or add additional context in comments.

3 Comments

Doesn't answer the question, just a workaround. Doesn't have anything to do with JavaScript
@AndrewL: the solution css is more interesting then JavaScript in this case.
That's subjective @IlyasMimouni Good answer regardless though.
0

Here are 2 examples to better explain it:

In this example the JS is at the top so is ran before I make the div with the ID cover-img. Meaning when it is ran the getElementById returns 0 results, giving the error Cannot read property 'style' of null"

<script type="text/javascript">
  document.getElementById('cover-img').style.display = 'none';
</script>
<div id="cover-img">I'm still alive!</div>
<div>I'll be here not matter what...</div>

In this example however I've moved the script to after the cover-img div is created meaning getElementById has a result that can be passed to style.

And as you'll see the div is hidden.

<div id="cover-img">I'm still alive!</div>
<div>I'll be here not matter what...</div>
<script type="text/javascript">
  document.getElementById('cover-img').style.display = 'none';
</script>

I hope that makes sense, I took the size bit out just to make it clearer but the same holds true with that in place.

That being said using CSS to achieve this is a much better solution as @Foker points out in another answer on this page.

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.