1

I have some doubts about the "best" current method to distinguish Javascript functions in certain screen sizes, because all answers say something different and they don't convince much. As far as I understand, the methods to build "responsive Javascript functions" are:

matchMedia() function

if (window.matchMedia('(max-width: 500px)').matches) {

width() function applied to window

if ($(window).width() < 500) {

And another method that I haven't seen here is:

if ($(".sampleClass").css("float") == "none") {

that basically check for any CSS propriety that change in a CSS media query:

.sampleClass {float:left;}
@media only screen and (max-width: 800px){
    .sampleClass {float:none;}
}

What's the current "best" method in order to write jQuery functions in certain screen sizes?

1 Answer 1

1

I believe the options above are the main ways of accomplishing this. As far as which one to choose:

Using window.width is the most common way of having viewport conditional code, as far as I know. However, this has some drawbacks, as is it is not always consistent across browsers. It will typically get the job done, though.

Matchmedia is a more consistent option of you don't need to worry about supporting older browsers, so make sure to check the support for this feature: https://developer.mozilla.org/en-US/docs/Web/API/Window/matchMedia

The final method of comparing classes based on a css media query will also be more consistent and you don't need to worry about browser support. It's a bit lengthier however, so you'll need to take that into consideration.

On the whole though, these will all work. There are just some slight differences to take into account.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.