Front-end Developer Front-end Developer - 4 months ago 13
jQuery Question

Fadetoggle not working optimally matchmedia max-width 767px

Little pain in the ass for me to solve this bug. When the width of the browser is max 767px, the fadeToggle function should be activated. It will collapse the unordered list. But when the browser has a width of more than 767px, everything should be shown including the unordered list. The thing is that when I minimize the the browser width to max 767 and collapse the unordered list. The unordered list is still collapsed when I make the browser screen wider (more than 767px) manually. Anyone who can solve this bug.

I only want a collapsible ul if screen is max 767px.



$(function(){
var hover = function(){
if(window.matchMedia("(max-width: 767px)").matches) {
$(".col-sm-3.col-xs-12").click(function(){
$(".head", this).fadeToggle(100);
});
} else {
}
};
$(window).resize(hover);
hover();
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>


<div class="col-sm-3 col-xs-12">
<div>
<h4 id="technology" class="header"><strong>Technology</strong></h4>
</div>
<div class="head">
<ul>
<p>VOOC</p>
<p>PURE IMAGE 2.0</p>
</ul>
</div>
</div>




Answer

When you attached the event handler inside, what happened is the every time the media query matched, an event handler was attached that told -> fade when the user clicks the div. Logically reverse it, when the click happens then you need to check if the window size condition is true.

See the working example below.

$(function() {
  $(".col-sm-3.col-xs-12").click(function() {
    if (window.matchMedia("(max-width: 767px)").matches) {
      $("#head").fadeOut(100);
    }
  });
  $(window).resize(function() {
    if (!window.matchMedia("(max-width: 767px)").matches) {
      $("#head").fadeIn(100);
    }
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>


<div class="col-sm-3 col-xs-12">
  <div>
    <h4 id="technology" class="header"><strong>Technology</strong></h4>
  </div>
  <div id="head">
    <ul>
      <p>VOOC</p>
      <p>PURE IMAGE 2.0</p>
    </ul>
  </div>
</div>

THIS IS TESTED at http://jsbin.com/kebiqus/edit?console,output