Search code examples
javascripthtmlcssmedia-queries

How to put javascript inside media query condition


I would like to put javascript inside the media query condition. I want to change the behavior of the elements when the screen is resized into mobile view. This is my code.

    @media only screen and (max-width: 767px) {
    <script>
    jQuery(document).ready(function(){
    jQuery('.address0.fa-angle-double-down').on('click', function(event) {        
    jQuery("#address-1").toggleClass("expand");
    jQuery('.address0.fa-angle-double-down').toggleClass("less-text");
    });
    });
    </script>
    }  

this is the html

    <div class="place">
    <h3><a href="/#/"><i class="fa fa-map-marker"></i> Nevada</a><i 
    class="fa fa-angle-double-down address0" aria-hidden="true"></i></h3>
    <ul>
    <li><i class="fa fa-map-marker"></i> <a href="/#/">Las Vegas</a></li>
    </ul>
   </div>

Please help thanks a lot.


Solution

  • You need to check jQuery's width() function. You might need to listen to the resize event in conjunction with debounce function from lodash js library to handle cases in which the window resizes.

        
        function handleClick(e) {
              $("#address-1").toggleClass("expand");
              $('.address0.fa-angle-double-down').toggleClass("less-text");
        }
        
        function handleState() {
        console.log($(document).width());
          if($(document).width() < 767) {
            $('.address0.fa-angle-double-down').on('click', handleClick);
          }
         }
        
        $(document).ready(function(){
          handleState();
        });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <div class="place">
        <h3><a href="/#/"><i class="fa fa-map-marker"></i> Nevada</a><i 
        class="fa fa-angle-double-down address0" aria-hidden="true"> down</i></h3>
        <ul>
        <li><i class="fa fa-map-marker"></i> <a href="/#/">Las Vegas</a></li>
        </ul>
       </div>