Instantly share code, notes, and snippets.

Embed
What would you like to do?
Responsive SVG background
// Grab SVG element
let bg = document.getElementById('bg-mbl')
// Media query event handler
if (matchMedia) {
let mqls = [ // Array of media queries
window.matchMedia("(min-width: 400px) and (max-width: 600px)"),
window.matchMedia("(min-width: 600px) and (max-width: 800px)"),
window.matchMedia("(min-width: 800px) and (max-width: 1000px)")
]
for (i=0; i < mqls.length; i++) { // Loop though media queries
mqls[i].addListener(widthChange) // Listen for queries
widthChange(mqls[i]) // Call handler func at runtime
}
}
// Media query change
function widthChange(mql) {
if (mqls[0].matches) {
bg.setAttribute("viewBox", "0 150 375 580")
}
else if (mqls[1].matches) {
bg.setAttribute("viewBox", "0 300 375 580")
}
else if (mqls[2].matches) {
bg.setAttribute("viewBox", "0 400 375 580")
}
else {
// Set default
bg.setAttribute("viewBox", "0 0 375 580")
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment