Furlong
Furlong

Reputation: 19

Add/Remove class from specific div based off screen size

I need to add the class .full-page when the screen size is >= 769px and remove the same class when screen size is <=768. The div I need the class to be applied to has an ID of #here I have tried quite a few things and this is where I left off...

<script>

    var windowSize = window.innerWidth;

    if (windowSize >= 769) {
        console.log('Greater than 768');
        document.getElementById('here').addClass = 'full-page';}

    else (windowSize <= 768) {
        console.log('Less than 768');
        document.getElementById('here').removeClass = 'full-page';}

</script>

Anyone have a tip? Thanks in advance!

Upvotes: 0

Views: 2263

Answers (3)

Ori Drori
Ori Drori

Reputation: 193248

You can use window#matchMedia to detect width changes, and see if it matches a certain criteria. Use classList to add and remove classes.

You can see an example here. Change the width of the bottom right rectangle by dragging the border.


Code:

var classList = document.getElementById('here').classList;

var minWidth769 = window.matchMedia("(min-width: 769px)");

function match() {
    minWidth769.matches ? classList.add('full-page') : classList.remove('full-page');
}

minWidth769.addListener(match);

match();

Upvotes: 1

Mario Wu
Mario Wu

Reputation: 11

I think you need to use jQuery if you want to use 'addClass', after link the jQuery file, Try

$("#here").addClass("full-page");

and

$("#here").removeClass ("full-page");

Upvotes: 0

Farooq Ahmed Khan
Farooq Ahmed Khan

Reputation: 4094

There is no method add|remove Class in JavaScript, if you want to change class for an element, you can use

document.getElementById('here').className = 'full-page'

OR

document.getElementById('here').setAttribute('class', 'full-page')

Upvotes: 0

Related Questions