Superfast Goose
Superfast Goose

Reputation: 147

remove class when browser loads at width at less than 700px

I'm trying to remove a class on an <a> when some one accesses a website on a device smaller than 700px, the code below works when my browser is greater than 700px and I resize it below 700. but if the browser is already below 700px like a phone the class remains.

Thanks in advance.

$(function(){
        $(window).bind("resize",function(){
            console.log($(this).width())
            if($(this).width() <700){
            $('a').removeClass('element')
            }
            else{
            $('a').addClass('element')
            }
        })
        })

Upvotes: 0

Views: 1300

Answers (2)

Joe
Joe

Reputation: 8272

You can try:

$(document).ready(function(e) {
    dothis();
});

$(window).resize(function(e) {
    dothis();
});

function dothis(){

    console.log($(window).width());

    if($(window).width() < 700){
        $('a').removeClass('element');
    } else {
        $('a').addClass('element');
    }
}

Run the dothis() function on document ready too so that it would run on page load.

Upvotes: 1

Arun P Johny
Arun P Johny

Reputation: 388316

You need to trigger the event manually when the page is loaded

$(function () {
    $(window).resize(function () {
        console.log($(this).width())
        if ($(this).width() < 700) {
            $('a').removeClass('element')
        } else {
            $('a').addClass('element')
        }
    }).resize();//trigger the event manually when the page is loaded
})

Upvotes: 1

Related Questions