Frans B Frans B - 1 year ago 45
Javascript Question

adding class on screen size with javascript not working

var d = document.getElementById('promo5');

var viewportWidth = window.innerWidth;

function mobileViewUpdate() {

if (viewportWidth <= 700) {
d.className += (" .promo5-mobile");
}else (viewportWidth >= 700) {
d.className += ("");

window.onload = mobileViewUpdate();
window.onresize = mobileViewUpdate();

to add a class to this div

div id="promo5" class="promo5"

so it can to this on the mobile size of my website

.promo5-mobile {
display: none;

Just cant figure out why it wont add this class, or maybe its adding it but is still displaying, I want it to not display. It works when I run it on my browser console but not on my code. I have checked if my js file works and it does.I am a beginner so it maybe something really basic.

EDIT: changed wrongly worded if statement to else if, moved the viewportWidth variable inside the function, check with browser inspector and its still not adding the class. Will use media queries unless someone finds the problem.

Answer Source

Ok, so the errors are many there:

  1. move var viewportWidth = window.innerWidth; into the mobileViewUpdate function. Otherwise its value is set once at the page load.

  2. call function on resize as window.onresize = mobileViewUpdate, no brackets

  3. correct condition statement - no brackets after else

  4. className should not be adding promo5-mobile every time your resize window which is already small, and don't forget to remove that class if you resize it back to medium-large

This should work:

var d = document.getElementById('promo5');

function mobileViewUpdate() {
    var viewportWidth = window.innerWidth;
    if ( viewportWidth <= 700 ) {
        if ( d.className.indexOf(" promo5-mobile") === -1 ) {
            d.className += (" promo5-mobile");
    } else {
        if ( d.className.indexOf(" promo5-mobile") > -1 ) {
            d.className = d.className.replace(" promo5-mobile", "");

window.onload = mobileViewUpdate;
window.onresize = mobileViewUpdate;