Heidel
Heidel

Reputation: 3254

Bootstrap 4 - how to detect changes of width on resize

I use Bootstrap 4, so I added following HTML code on my page

HTML

<div id="device-size-detector">
    <div id="xs" class="d-block d-sm-none"></div>
    <div id="sm" class="d-none d-sm-block d-md-none"></div>
    <div id="md" class="d-none d-md-block d-lg-none"></div>
    <div id="lg" class="d-none d-lg-block d-xl-none"></div>
    <div id="xl" class="d-none d-xl-block"></div>
</div>

JS

$(document).ready(function() {

"use strict"

function getBootstrapDeviceSize() {
    return $('#device-size-detector').find('div:visible').first().attr('id');
}

function checkMenu(){
    var screen = getBootstrapDeviceSize();

    $(window).on('resize', function() {
        screen = getBootstrapDeviceSize();
    });

    if(screen == "lg" ||  screen == "xl") {
        console.log(1); 
    } else {
        console.log(0);
    }       
}

checkMenu();

});

But my script detects only the first value of screen size and doesn't detect any changes of width on resize. I guess I don't use $(window).on('resize', function() {...} properly, but I don't understand how to fix it and make it work?

Upvotes: 0

Views: 2895

Answers (1)

Suresh Ponnukalai
Suresh Ponnukalai

Reputation: 13978

Move your window.resize code outside of the checkMenu function and call the function like below.

$(window).on('resize', checkMenu);

$(document).ready(function() {

"use strict"

function getBootstrapDeviceSize() {
    return $('#device-size-detector').find('div:visible').first().attr('id');
}

function checkMenu(){
    var screen = getBootstrapDeviceSize();    

    if(screen == "lg" ||  screen == "xl") {
        console.log(1); 
    } else {
        console.log(0);
    }       
}
checkMenu();
$(window).on('resize', checkMenu);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="device-size-detector">
    <div id="xs" class="d-block d-sm-none"></div>
    <div id="sm" class="d-none d-sm-block d-md-none"></div>
    <div id="md" class="d-none d-md-block d-lg-none"></div>
    <div id="lg" class="d-none d-lg-block d-xl-none"></div>
    <div id="xl" class="d-none d-xl-block"></div>
</div>

Upvotes: 4

Related Questions