เพื่อใช้ Media Queries กับ JavaScript โค้ดมีดังนี้
ตัวอย่าง
<!DOCTYPE html> <html> <head> <meta name="viewport" content="width=device-width, initial-scale=1" /> <style> body { font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif; color: white; padding: 20px; } </style> </head> <body> <h1>Using media queries with JavaScript Example</h1> <h2>Resize the screen to see the color change from blue to red</h2> <script> var mediaQuery = window.matchMedia("(max-width: 700px)"); function setColor(mediaQuery) { if (mediaQuery.matches) { document.body.style.backgroundColor = "red"; } else { document.body.style.backgroundColor = "blue"; } } setColor(mediaQuery); mediaQuery.addListener(myFunction); </script> </body> </html>ผลลัพธ์
โค้ดข้างต้นจะสร้างผลลัพธ์ดังนี้บนขนาดหน้าต่างมากกว่า 700px -

เมื่อปรับขนาดหน้าต่างเบราว์เซอร์น้อยกว่า 700px -
