Matt Matt - 4 months ago 23
jQuery Question

bootstrap collapse shut on xs but open on lg. On window onresize keep open if clicked

On xs and sm, a div is collapsed and a button toggles the collapsing of this div. On lg screens, the div is always open and the button gets hidden.

The problem is that if the user is on xs or sm and clicks the button which opens the div, as soon as they move the browser window it becomes shut. (I have a window.resize function that does this because it is needed for a different user case which is if the user is on lg and moves the browser window smaller to become sm. The div correctly will shut).

So I would need to tweak this a bit to say only on sx or sm, if the button was clicked to open, ingore the window.resize function.

Maybe setting a var 'wasClicked' to true if there was a click on #Pnl1Btn, then compare that inside the window.resize event to stop the removeClass? I couldn't figure that out...

HTML:

<a href="#Pnl1" data-toggle="collapse" id="Pnl1Btn" class="btn btn-default hidden-md hidden-lg">Click This</a>

<div class="collapse" id="Pnl1">
Hello this is the panel opened
</div>


JS:

$(document).ready(function () {
var wWidth = $(window).width();

if (wWidth <= 991) { //for iPad & smaller devices
$('#Pnl1').removeClass('in')
} else {
$('#Pnl1').addClass('in');
}

$('#Pnl1Btn').on('click', function () {
if (Clicked == 0) {
Clicked = 1;
console.log(Clicked);
} else if (Clicked == 1) {
Clicked = 0;
console.log(Clicked);
}
});

});

window.onresize = function(event) {
var wWidth = $(window).width();
if (wWidth <= 991) { //for iPad & smaller devices
$('#Pnl1').removeClass('in');
} else {
$('#Pnl1').addClass('in');
}
if (Clicked == 1) {
$('#Pnl1').addClass('in');
}
};

});


CodePen link

Answer

This is the fix:

$(document).ready(function () {
var Clicked = 0,
    wWidth = $(window).width();

if (wWidth <= 991) { //for iPad & smaller devices
    $('#Pnl1').removeClass('in')
} else {
    $('#Pnl1').addClass('in');
}

$('#Pnl1Btn').on('click', function () {
    if (Clicked == 0) {
        Clicked = 1;
        console.log(Clicked);
    } else if (Clicked == 1) {
        Clicked = 0;
        console.log(Clicked);
    }
});

$(window).on('resize', function(event) {
    var wWidth = $(window).width();
    if (wWidth <= 991) { //for iPad & smaller devices
        $('#Pnl1').removeClass('in');
    } else {
        $('#Pnl1').addClass('in');
    }
    if (Clicked == 1) {
        $('#Pnl1').addClass('in');
    }
});

});