I'm trying for hours now to add a wrapper around two divs (aside and .related) at a certain screensize (>60em and <90em). I'm doing this with matchMedia and an eventListener. The wrapper seems to be added at the right spot, but the problem is that it's still there even when the condition of the size is not met.
Here is a jsfiddle: http://jsfiddle.net/Vanilla__/4q26ngmg/1/
Simplified HTML:
<body>
<header>Header</header>
<main>Main</main>
<aside>Aside</aside>
<div class="related">Related</div>
<footer>Footer</footer>
</body>
Javascript:
if(window.matchMedia("screen and (min-width: 60em) and (max-width: 90em)").matches) {
window.addEventListener("resize", function addWrapper(q) {
//Create div with id wrapper
var div = document.createElement('div');
div.id = "wrapper";
// Select aside
var selectDiv = document.querySelector("aside");
//clone
div.appendChild(selectDiv.cloneNode(true));
//Place the new wrapper at the right place in the HTML
selectDiv.parentNode.replaceChild(div, selectDiv);
//Add related to the wrapper so they're both in the wrapper
document.querySelector('#wrapper').appendChild(
document.querySelector('.related') );
});
}
I wanted to add an 'else' to remove the child (with removeChild) or delete the eventListener (with removeEventListener) when there's another screen size, but all I get is errors about that the function is not definied or other errors whatever I try.
else {
window.removeEventListener("resize", addWrapper(q));
}
Does anyone know how the wrapper can be removed when the screensize is not >60em and <90em? I'm a Javascript rookie (as might be clear ;) ). Any help is appreciated.