Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript

Nathan Marshall
Nathan Marshall
6,031 Points

Why wont this work on my phone but works on my window resizing?

Hi Guys,

I am currently working on a project, I had the task of changing an overlay on a slider based on the actual slide that appears. I have managed to get the code to work but I have faced the problem of it not working on mobile phones?. In theroy I think that this should work , i am using window.matchMedia to set the conditions. It works perfectly when I resize my window but when on my phone it really plays up. I need to turn my phone horizontally for it to activate.

Here is my code (Includes alot of non DRY programming):

function changeSlideColor(windowSize){


let overlay = document.getElementsByClassName('zphoto-overlay');
console.log(overlay);

let slideImage1 = document.getElementById('slide--1480352639511-0');

let slideImage2 = document.getElementById('slide--1533648783968');

let slideImage3 = document.getElementById('slide--1480352639511-1');


  if(windowSize.matches){


if(slideImage1.style.zIndex = '2'){
 overlay[0].style.background='rgba(254, 255, 250, 0.55)';
}

if(slideImage2.style.zIndex = '2'){
 overlay[1].style.background='rgba(0, 0, 0, 0.55)';
}

if(slideImage3.style.zIndex = '2'){
 overlay[2].style.background='rgba(0, 0, 0, 0.55)';
}

    console.log('matches!');

} 

else {


if(slideImage1.style.zIndex = '2'){
 overlay[0].style.background='0';
}

if(slideImage2.style.zIndex = '2'){
 overlay[1].style.background='0';
}

if(slideImage3.style.zIndex = '2'){
 overlay[2].style.background='0';
}

}

  console.log('Doesnt match!');
}

let windowSize = window.matchMedia("(max-width:700px)");
windowSize.addListener(changeSlideColor);

If you have any ideas, please let me know!

Thanks,

Nathan

1 Answer

Brian Jensen
seal-mask
STAFF
.a{fill-rule:evenodd;}techdegree seal-36
Brian Jensen
Treehouse Staff

You can try adding this to the <head> of your HTML file:

<meta name="viewport" content="width=device-width, initial-scale=1">