- jQuery functions with CSS media queries for responsive website
- Use jQuery to test for a changed CSS property, rather than the browser width
- jQuery functions with CSS media queries
- Как использовать Media Query в JavaScript
- Как использовать Media Query в JavaScript
- Using jQuery with CSS Media Queries
- CSS
- jQuery
- How to Add Media Query in Jquery
- Steps to add Media Query in jQuery
- 1. Create an HTML Content
- What is lorem ipsum
- 3. Add Media Query Using jQuery
- My Suggestion
jQuery functions with CSS media queries for responsive website
DISCLOSURE: This article may contain affiliate links and any sales made through such links will reward us a small commission, at no extra cost for you. Read more about Affiliate Disclosure here.
Due to difference between CSS media queries based on max-width and jQuery’s ‘$(window).width()‘ measurement (caused by the inconsistent ways in which browser media queries handle scrollbars), there is always a mismatch between ‘jQuery $(window).width()‘ and CSS3 Media Queries. Which in turn causes some ugly or unexpected behaviour by your responsive website.
The Issue:
Initially I was using the code below:
When viewing the site in Firefox, I noticed a small difference in the width at which my media query and javascript were firing. The inconsistent treatment of vertical scrollbars in media query widths causes a small difference between browsers in the actual window width when a media query fires, which in turn causes media query and jQuery width measurements to not match in some popular browsers: Firefox, IE, and Opera. Any appearance of the responsive website was broken. So after some googling I made a solution which is better than detecting native window/device screen size.
Use jQuery to test for a changed CSS property, rather than the browser width
jQuery functions with CSS media queries
Rather than the measuring the screen width on resize of the window, I check for a css rule that is changed by the media query. This way, regardless of the how the browser treats the scrollbar, the media query will fire at the same time.
Suppose that body has a ‘padding-top: 140px‘ CSS rule for mobile devices and it’s ‘70px‘ for other large devices (ipad, tablet, desktop), I check for the change in rule.
Как использовать Media Query в JavaScript
Показываю рабочие примеры медиа запросов в JavaScript для получения реальных размеров экрана и дальнейшего использования этих значений.
Интернет проникает во все большее количество устройств с самыми мыслимыми и немыслимыми размерами экранов. Одна из важнейших задач веб-разработчика — обеспечить корректное отображение веб-страницы на любом разрешении любого экрана, сохранив при этом ее восприятие. При этом не вынуждая посетителя пользоваться горизонтальной прокруткой и масштабированием.
Для адаптации дизайна страницы под конкретные разрешения или устройства мы привыкли пользоваться медиа-запросами CSS (media query).
/* Smartphones (portrait) ----------- */ @media only screenand (max-width:320px) < >/* Desktops and laptops ----------- */ @media only screenand (min-width:1224px) < >/* Large screens ----------- */ @media only screenand (min-width:1824px)Приведенный выше CSS-код позволит вам стилизовать страницу под три различных устройства. Но как быть, если вам помимо изменения внешнего вида необходимо изменить функционал сайта в зависимости от размера экрана? К примеру, такая задача часто встает при адаптации под мобильные девайсы различных слайд-шоу.
Как использовать Media Query в JavaScript
Чтобы узнать размер экрана устройства, медиа запросы проверяют ширину окна. Поэтому, можно предположить, что мы можем использовать метод width() для объекта окна, как в примере ниже.
Однако, этот метод не вернет вам истинного значения размера окна, так как не учитываются размеры отступов и полос прокруток окна. Другой способ проверки заключается в использовании еще одного метода JavaScript для объекта окна .MatchMedia().
var window_size = window.matchMedia('(max-width: 768px)'));
Этот способ работает аналогично стандартному медиа-запросу CSS, и работает на всех современных браузерах выше IE9. Выглядит это примерно так:
if(window.matchMedia('(max-width: 768px)').matches)< // do functionality on screens smaller than 768px >
Давайте попробуем используя этот метод, добавить событие клика на подменю для экранов размером не более 768px. Код ниже является примером того, как можно добавив несколько строчек кода, заставить выполняться JavaScript только на экранах меньше, чем 768px.
if(window.matchMedia('(max-width: 768px)').matches) < $('.sub-menu-button').on('click',function(e)< var subMenu = $(this).next('.sub-navigation'); if(subMenu.is(':visible'))< subMenu.slideUp(); >else < subMenu.slideDown(); >return false; >); >
⚡️ Подписывайся на мой канал @DanilinBiz и ты узнаешь, почему одни фрилансеры пашут, как проклятые, зарабатывая копейки, а другие не напрягаясь поднимают приличные деньги.
Делаю сайты на Вордпресс с 2008 года, в том числе уникальные инструменты для решения сложных бизнес‑задач.
Ребята, давайте не будем мусорить символами ($) однабуквенными названиями в названиях. По сути это хуже машинного кода будет в конце выглядеть.
if(window.matchMedia(‘(max-width: 768px)’).matches)
$(‘.sub-menu-button’).on(‘click’,function(e)
var subMenu = $(this).next(‘.sub-navigation’);
if(subMenu.is(‘:visible’))
subMenu.slideUp();
> else subMenu.slideDown();
>return false;
>);
>
Код откуда-то с форума сперли, зачем тут «е»? Зачем тут «return false» ?IE9? Opera mini на мобилках?
Это быстрое и хорошее решение но не для всех девайсов.
http://caniuse.com/#feat=matchmedia — смотреть здесьЛучшим решением будет использование Modernizr и его media queries
if (Modernizr.mq(‘(max-width: 544px)’)) // необходимые действия
> else //другие действия
>
- Собственные проекты сложны тем, что ты заказчик и исполнитель в одном лице. На ходу корректируешь задачи, уходя в бесконечные правки. Что делаешь реальному заказчику, например, неделю, себе можешь пилить несколько месяцев. Открыть в Telegram
- Мне потребовались годы, чтобы понять смысл free в слове фриланс и осознать, что это все не про работу, а больше про образ жизни. Фриланс дает возможность самостоятельно выстроить и адаптировать под себя все рабочие процессы. Открыть в Telegram
- Не каждый работник и работодатель готовы к свободным трудовым отношениям. Вдруг кто-то меня услышит, задумается и осознает, что жизнь одна и просидеть ее в чужом офисе, зарабатывая левому дяде деньги, такая себе перспектива. Открыть в Telegram
- Я работал в офисе с 2003 по 2009 и первые два года в типичной совковой конторе с восьми до пяти, соответствующим контингентом, трудившимся там по тридцать, сорок и более лет. Депрессивная атмосфера не особо вдохновляла на подвиги. Открыть в Telegram
- У меня в приоритете сайты, которые на моей техподдержке. Если на них что-то случается, я бросаю все и занимаюсь проблемой. Дальше идут заказчики, с которыми я сотрудничаю много лет. Это самые важные в моей работе люди. Открыть в Telegram
- Для меня любая нерешенная задача это психологический груз. Их количество растет как снежный ком и в какой-то момент он может просто накрыть. Придется несколько дней безвылазно сидеть за компьютером и все это разгребать. Открыть в Telegram
- Поймав волну своей максимальной продуктивности и настроившись на нее, вполне реально начать жить нормальной жизнью, отвлекаясь на работу на несколько часов в день, а не наоборот. И это не какая-то инфоцыганская мечта, а реальность фриланса. Открыть в Telegram
- Если человек не ценит твое время, начинает общение с выплескивания тонны ненужной информации, выводит на долгие пустые разговоры, при этом совершенно тебя не слыша — хорошего не жди. Я понимаю, люди бывают разные, но иногда прям никак. Открыть в Telegram
- Поработав в штате, начинаешь понимать, что работодателю на тебя плевать. Цель эффективного менеджера выжать из сотрудника максимум, а заплатить минимум. Любой фрилансер, наоборот, стремится работать меньше, а зарабатывать больше. Открыть в Telegram
- Я пробовал разные форматы и понял, что мне комфортнее не отключаться совсем. Большие задачи разбиваются на более мелкие и последовательно в спокойном ритме решаются. Каждый день небольшими шагами идешь к цели. Открыть в Telegram
- Использовать разные рабовладельческие 5/2, 2/2 и прочие противоречит моему пониманию концепции фриланса. Мне кажется, у каждого свой баланс, который держит в форме. Надо просто найти его и научиться контролировать. Открыть в Telegram
- Знаю фрилансеров, которые чуть ли не круглые сутки проводят за компьютером. Мне кажется, их продуктивность такая себе и профит подозреваю тоже. Я, например, если сегодня весь день кодил, завтра вряд ли вообще подойду к компьютеру. Открыть в Telegram
Using jQuery with CSS Media Queries
As mobile web design is becoming widely used to provide an optimal viewing experience, we as developers are need to decide the best approach with regards to device detection and choice of client or server side logic.
When using adaptive design, we can process server side logic easier using mobile device detection plugins such as 51Degrees, however a responsive/fluid site is dependent on client side detection. Since client side detection is regularly used with responsive/fluid layouts, we may find ourselves requiring some JavaScript to detect viewport sizes and media queries outside of CSS.
On a recent project, I had to process a single function in jQuery based on the browser size. Initially I was going to check the device width was applicable to a mobile device (320px):
After testing various devices and browsers, I noticed the $(window).width() and CSS media query weren’t firing together. This was due to inconsistency amongst browser windows and scrollbars. This small discrepancy causes bigger issues when accuracy is number one priority for triggering certain functions.
Solution? After trawling through StackOverflow for some hints, I found a post where a developer checked a CSS rule using jQuery that was affected within a media query condition:
CSS
@media only screen and (max-width: 320px)
jQuery
Using this solution, regardless of how the browser treats the scrollbar, the jQuery and CSS media query will fire at exactly the same time.
Baring in mind there are various wrappers and solutions that you could use, for something so small this was more than enough.
keep up to date - With the latest web design, development & technology news
How to Add Media Query in Jquery
Media Query in JQuery: As you know that Media Query was created in CSS3. It is used to create responsive web pages. Means that it can display the web contents & layouts in different size of devices with proper format. So, It is widely used to create a user-friendly & mobile-friendly website.
In most cases, developers need to add CSS properties & media Query dynamically to the HTML element using jQuery. So, In this tutorial, you will learn it with a simple example.
Steps to add Media Query in jQuery
Suppose that we have a paragraph and title within a div (id=”content”). We have to change the CSS properties of these content in a device that screen size is less than or equal to 600px. This means that Whenever the content page opens in the browser the maximum width is 600px on the device.
You will display the content of the above example in different sizes of the device through the following steps.
1. Create an HTML Content
In this step, You have learned to add a media query to the title & description. After learning it, You can easily use a media query to any kind of HTML elements for displaying them on different screen sizes. So, let’s start it with the following steps –
- Create a parent div with create a title & paragraph with some text within the parent div
- Write some CSS to display the title & description in a proper format
.title < color:blue; font-style:italic; font-size:25px; >#content pWhat is lorem ipsum
Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industrys standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book.
3. Add Media Query Using jQuery
To add a media query to the HTML element, You have to write jquery code with the following steps –
- Create a function responsive(maxWidth) . where maxWidth is the parameter
- If maxWidth.matches is true then a class title to the h1 tag and some inline CSS code to the paragraph. otherwise, remove title from the h1 tag & add another inline CSS code.
- Pass a value (max-width: 600px) to the window.matchMedia() and assign it to maxWidth
- Also, Pass maxWidth to the responsive(maxWidth)
- Apply addListener with responsive to the maxWidth
function responsive(maxWidth) < if (maxWidth.matches) < $('#content h1').addClass('title'); $('#content p').css(); > else < $('#content h1').removeClass('title'); $('#content p').css(); > > var maxWidth = window.matchMedia("(max-width: 600px)"); responsive(maxWidth); maxWidth.addListener(responsive);
This code only gives you an idea How to add a media query. If you implement this code as it is another HTML element then It will not work. You will have to create a new code for any other kind of element using its concept.
But You should have a good understanding of CSS Media query. If you don’t have then go and learn it first. after that try to implement it in your project.
Don’t forget to include custom.js and jQuery CDN in the index.php. Otherwise, the media query will not work
My Suggestion
Dear Developers, I have that the above script is easy to understand. Now you can easily create a responsive website.
Share the above script with your friends and continue to visit my blog. You will regularly get more new web technology tutorials to develop your coding skills.