Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery detect Bootstrap 3 state

In Bootstrap 3, there are 4 states; extra small devices, small devices, medium devices, and large devices. How can I know the website is currently at which state with jQuery? So that I can do some processing like when it is in extra small devices, then run this function.

Thanks.

like image 238
user1995781 Avatar asked Oct 19 '13 05:10

user1995781


3 Answers

I made some changes to this for bootstrap 3, try this"

function findBootstrapEnvironment() {
    var envs = ["ExtraSmall", "Small", "Medium", "Large"];
    var envValues = ["xs", "sm", "md", "lg"];

    var $el = $('<div>');
    $el.appendTo($('body'));

    for (var i = envValues.length - 1; i >= 0; i--) {
        var envVal = envValues[i];

        $el.addClass('hidden-'+envVal);
        if ($el.is(':hidden')) {
            $el.remove();
            return envs[i]
        }
    };
}
like image 110
Khurshid Avatar answered Nov 15 '22 21:11

Khurshid


Following @Khurshid's answer (which works perfectly well) I've written a native JavaScript implementation which is significantly faster:

function findBootstrapEnvironment() {
    var envs = ["xs", "sm", "md", "lg"],    
        doc = window.document,
        temp = doc.createElement("div");

    doc.body.appendChild(temp);

    for (var i = envs.length - 1; i >= 0; i--) {
        var env = envs[i];

        temp.className = "hidden-" + env;

        if (temp.offsetParent === null) {
            doc.body.removeChild(temp);
            return env;
        }
    }
    return "";
}
like image 33
awj Avatar answered Nov 15 '22 21:11

awj


I had to do something similiar for the medium size.

The media query for the extra small is up to 480px;

so you can say something like:

if($(document).width > 480)
{

  //Do Something
}
like image 43
w3bMak3r Avatar answered Nov 15 '22 22:11

w3bMak3r