-1

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

Andrew Bone
  • 6,549
  • 2
  • 15
  • 31
Edvard Åkerberg
  • 1,901
  • 1
  • 20
  • 39
  • 2
    The second one is running when the page loads, and so you probably have the script up in the ``, which is before the element exists. Move your script to just before the ``, and it should work. –  Jun 10 '16 at 14:09
  • Probably because cover-img doesn't exist at the time when you execute the script – Andrew Li Jun 10 '16 at 14:09
  • 1
    Possible duplicate of [Why does jQuery or a DOM method such as getElementById not find the element?](http://stackoverflow.com/questions/14028959/why-does-jquery-or-a-dom-method-such-as-getelementbyid-not-find-the-element) – Sebastian Simon Jun 10 '16 at 14:16

2 Answers2

3

you can do that with pure css

@media(max-width:75em){
    #mydiv{
        display:none;
    }
}
Foker
  • 846
  • 2
  • 9
  • 21
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.

Andrew Bone
  • 6,549
  • 2
  • 15
  • 31