I have simple toggle div. I need on the big screens paragraph content
open when hover, and on the small screens when click. I try to do like this:
HTML:
<div class="container">
<div class="headline">Headline exaple</div>
<p class="content">
Lorem ipsum dolor sit amet, consectetur adipisicing elit. Vitae quia nulla, rem harum, minima sint assumenda perferendis cupiditate rerum corporis obcaecati, quam natus repudiandae veniam dolor. Maiores commodi sequi, esse.
</p>
</div>
CSS:
.container {
width: 400px;
border: 1px solid #ccc;
border-radius: 5px;
}
.headline {
background: #ccc;
padding: 5px;
cursor: pointer;
}
.headline:hover + .content {
display: block;
}
.content {
padding: 5px;
display: none;
}
jQuery:
var isSmallWindow;
$(window).on('resize', function() {
isSmallWindow = $(this).width() < 768;
});
$('.headline').on('click', function() {
if (isSmallWindow) {
$('.content').slideToggle(300);
}
});
But it does not work properly. When I change the window size content
is still open when hover. I clicked on the headline
and when I return window of its original position, then hover not working. How to solves this problem?
JSFiddle
You have the :hover
pseudo on your CSS. While this exists, the behaviour persists.
You can add a .small-window
class to your <html>
tag and control it with that.
https://jsfiddle.net/9a1n8xtw/4/
$(window).on('resize', function() {
isSmallWindow = $(this).width() < 768;
if(isSmallWindow) {
$('html').addClass('small-window');
}else {
$('html').removeClass('small-window');
}
});
And the css
html:not(.small-window) .headline:hover + .content {
display: block;
}
To avoid style overriding by slideToggle()
you can remove style property like this:
$(window).on('resize', function() {
isSmallWindow = $(this).width() < 768;
if(isSmallWindow) {
$('html').addClass('small-window');
}else {
$('html').removeClass('small-window');
}
$('.content').attr('style', false);
});
See the updated fiddle working fine:
https://jsfiddle.net/9a1n8xtw/7/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With