-1

Here is the div to which I am trying to add class

<div id="sidebar" class="addthis_recommended_horizontal col-lg-4 col-md-4 col-sm-6 col-xs-12""></div>

and this is the script I am using

<script>window.onresize=function()
{var width=document.getElementById("#sidebar").clientWidth;
if(width<640) {document.getElementById("#sidebar").setAttribute("class",".sidebar");}
</script>

After adding this class, this CSS code changes the width

.sidebar.at4-recommended-item{width:45%!important}

But the class was not being added, I don't know why?

EDIT I am using media queries. In this case two classes have same name If I change one other will change too so I am adding a class dynamically, and it is a div not whole window width that I need to change.

WHY ARE PEOPLE SO KEEN ON DOWNVOTING EVERY QUESTION HERE?

Asain
  • 37
  • 10

2 Answers2

1

Since you are changing the element's width on window resize, ideally you should be using CSS3's @media queries instead!

In your case, the @media query will be:

<style>
    @media (max-width: 640px){
        #sidebar{
            width: 45%;
        }
    }
</style>

It is a bad idea to write Javascript just for this purpose.

Learn more: CSS @media queries | MDN

EDIT:

If you are adding the class dynamically, just mention that in the @media query:

<style>
    @media (max-width: 640px){
        .sidebar{
            width: 45%;
        }
    }
</style>

Keep it simple. :)

Rahul Desai
  • 15,242
  • 19
  • 83
  • 138
0

Don't use # when you select an element by document.getElementById. # is used in css/jQuery selectors, not in plain JavaScript. and also you are adding a class name on window resize to below 640, you should also consider removing that class when resized above 640.

Please try using following code:

<script>
    window.onresize=function() {
       var sidebar = document.getElementById("sidebar");
       var width = sidebar.clientWidth;
       if(width<640) {
           sidebar.className ="sidebar";
       }
       else{
           sidebar.className = ""; //assuming this element doesn't have any other classes.
       }
    }
</script>

If you want use jQuery then,

<script>
   window.onresize=function() {
       var sidebar = $("#sidebar");
       var width = sidebar.width();
       if(width<640) {
           sidebar.addClass("sidebar");
       }
       else{
           sidebar.removeClass("sidebar");
       }
   }
</script>
Mr_Green
  • 40,727
  • 45
  • 159
  • 271
BabyDuck
  • 1,249
  • 1
  • 9
  • 22
  • 3
    There is no `class` but a `className` property. One can also use `.classList.add("sidebar")`. – Kagami Sascha Rosylight Feb 09 '15 at 06:54
  • 2
    "*`#` is only used in jQuery selectors, not in plain JavaScript.*" - `#` is used in CSS selectors, rather than 'jQuery selectors,' and is used in plain JavaScript methods such as `document.querySelector()` and `document.querySelectorAll()` (among a couple of others). – David Thomas Feb 09 '15 at 07:03