1

I am trying to adjust the size of a background image based on the width of the window. I have been testing this, and I can get the alerts to show up in chrome when I 'inspect element' and change the width size, and the alerts show up as they should. But I cannot get the class of the image to change.

Any ideas?

This is my basefunctions.js file

window.onload = function changeClass(){
    if( window.innerWidth < 770 ) {
      document.getElementById("bg_img").setAttribute("class", "imgMobile");
      alert("On Mobile");
    }else{
      alert("Not on Mobile");
    }
}

This is my HTML/CSS

<script language="JavaScript" type="text/javascript" src="js/basefunctions.js"></script>

<style>

#bg_img {
    width: 100%;
    z-index: 1;
    border: 1px #000 solid;
    height:80%;
}

.imgMobile {
    display: none;
    width: 100%;
    z-index: 1;
    margin-left: -100;
}

</style>

<img src="img/gavel.png" alt="" id="bg_img" class="">
Buddy
  • 10,874
  • 5
  • 41
  • 58
SJJ
  • 11
  • 1
  • 4

2 Answers2

1

You should use className rather than using setAttribute.

document.getElementById("bg_img").className = "imgMobile";

Here is another SO about changing an dom object's class.

I also put together a jsfiddle to demonstrate.

Community
  • 1
  • 1
Soturi
  • 1,486
  • 1
  • 14
  • 30
  • Yeah, I tried that too, not sure why it's not working. I have it set to display:none and the margin changing just to verify that it's working, but the image didn't change at all. – SJJ Aug 18 '15 at 18:01
0

You can set the class using

document.getElementById("bg_img").className = "imgMobile";

If you want to add the class without overriding other classes, then use

document.getElementById("bg_img").className += " imgMobile";
shadowfox
  • 505
  • 4
  • 7