Arda Zaman Arda Zaman - 4 months ago 9
jQuery Question

I can't remove hover effect when I resize the screen

I add a hover effect to a div when the screen is smaller. When the screen is resized to become bigger, the div turns into a search box, and the hover effect is supposed to go away. The problem is that the hover effect still continues.

See here - jsfiddle.

HTML:

<div id="search">
<i class="fa fa-search" aria-hidden="true"></i>
<input type="search" placeholder="Ara">
</div>


CSS:

div#search {
position: absolute;
top: 5px;
width: auto;
border: 2px solid #333;
padding: 5px;
right: 150px;
}

div#search i {
font-size: 25px;
border-right: 2px solid #333;
padding-right: 10px;
margin-left: 10px;
}

div#search input {
width: 200px;
height: 40px;
font-size: 22px;
border: none;
outline: none;
background: transparent;
margin-left: 5px;
}

@media screen and (max-width: 1280px) {
div#search {
right: 40px;
width: 32px;
padding: 13.5px;
}
div#search input {
display: none;
}
div#search i {
margin: 5px;
border: none;
}
}


jQuery:

$(document).ready(function() {

searchHover();

$(window).resize(function() {

searchHover();
});
});

function searchHover() {
var width = $(window).width() + 17;

if (width < 1280) {
$('div#search').on('mouseover', function() {
$(this).css({
'background-color': '#00aeef',
'transition': '0.5s',
'border-color': '#00aeef',
'color': 'white',
'border-radius': '5px'
});
});

$('div#search').on('mouseout', function() {
$(this).css({
'background-color': 'transparent',
'transition': '0.5s',
'border-color': '#333',
'color': '#333',
'border-radius': '0px'
});
});
}
}

Answer

If I understood your issue correctly, then I think I solved it. See the fiddle.

Your problem was that you forgot the else clause:

if (width < 1280) {
  $('div#search').on('mouseover', function() {
    $(this).css({
      'background-color': '#00aeef',
      'transition': '0.5s',
      'border-color': '#00aeef',
      'color': 'white',
      'border-radius': '5px'
    });
  });

  $('div#search').on('mouseout', function() {
    $(this).css({
      'background-color': 'transparent',
      'transition': '0.5s',
      'border-color': '#333',
      'color': '#333',
      'border-radius': '0px'
    });
  });
} else {
  $('div#search').off('mouseover mouseout');
}

Without the else clause, you set the event listeners when the width is less than 1280, but you never turn them off when the width is greater or equal.

You can see it more easily in full screen mode.

Comments