Skip to content

Move node on media query

In case CSS display block and display none don’t cut it, here’s a way to move a child element to another parent

Tags that this post has been filed under. Links open in the same window.

class Appender{
constructor(bigScreenParent, smallScreenParent, child, media){
this._bigScreenParent = bigScreenParent
this._smallScreenParent = smallScreenParent
this._child = child
this._media = media
}
get bigScreenParent(){
return this._bigScreenParent
}
get smallScreenParent(){
return this._smallScreenParent
}
get child(){
return this._child
}
get media(){
return this._media
}
addChild(){
// if screen matches the media query, then move element to first child position of selected parent
if (this._media.matches){
this._smallScreenParent.insertAdjacentElement('afterbegin', this._child)
}else this.bigScreenParent.insertAdjacentElement('afterbegin', this._child)
}
}

//if screen is big enough, display #sidebarBlurb on sidebar - otherwise, show it on top of main
let bigScreenParent = document.getElementById('sidebar')
let smallScreenParent = document.getElementById('main')
let child = document.getElementById('sidebarBlurb')

//media query
let media = window.matchMedia("(max-width: 1280px)")

let prependThis = new Appender(bigScreenParent, smallScreenParent, child, media)

//run it on load to keep looks consistent
window.onload = prependThis.addChild()
//add an event listener in case screen size changes
window.matchMedia('(max-width: 1280px)').addEventListener('change', () => prependThis.addChild())