Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jquery trigger only on small window

Tags:

html

jquery

css

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

like image 688
Ihor Tkachuk Avatar asked Nov 11 '15 09:11

Ihor Tkachuk


1 Answers

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;
}

UPDATE

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/

like image 155
Marcos Pérez Gude Avatar answered Oct 23 '22 03:10

Marcos Pérez Gude