Search code examples
javascriptjqueryhtmlmedia-queriesresponsive

jquery media queries changed css


I'm trying to find the mistake in my code for a while now but I can't figure out whats wrong. Any ideas?

$(document).ready(function(){
        checkSize();
        $(window).resize(checkSize);
    });
    
    
    function checkSize(){
      if($(".testClass").css("float") == "none"){
          window.alert("Test");
      }
    }
.testClass{
      float: left;
    }
    
    @media(max-width: 768px){
      .testClass{
        float: none;
      }
    }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>


Solution

  • Using $(window).width() you can get the viewport width and do any validation width it.

    $(document).ready(function() {
      console.log('Window width: '+ $(window).width());
      checkSize();
    });
    
    function checkSize() {
      if($(window).width() < 768) {
        console.log("Run code...");
      }
    }
    .testClass {
      float: left;
    }
    
    @media(max-width: 768px) {
      .testClass {
        float: none;
      }
    }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <div class="testClass"></div>