Edit: Sorry should have explained why your script fails.
This line
const addedPhoneNumberBox = document.querySelector("#phoneNumberBox");
You are searching the dom for #phoneNumberBox
before you add it in the next three lines
if (window.innerWidth >= 850) {
addPhoneNumberBox();
}
so addedPhoneNumberBox isn’t found and is presumably a null. This is then going to fail
addedPhoneNumberBox.parentElement.removeChild(addedPhoneNumberBox);
First off you want to be doing this in CSS. I presume this is only a learning exercise with Javascript.
In fact if you were to use JS and CSS you would be better off just toggling a class on the phoneNumberBox element to show or hide it (see below)
Anyway I am going to follow your approach — all part of learning.
const headerContact = `
<div id='phoneNumberBox' class='contactInfo'>
Call me: <a href='tel:+1 xxx-xxxxxx'>+1 012-3456780</a>
</div>
`
const resizeHandler = function(event) {
const header = document.querySelector('header')
const contactInfo = header.querySelector('#phoneNumberBox')
if (window.innerWidth > 850) {
if (contactInfo === null) {
header.insertAdjacentHTML('beforeend', headerContact)
}
return // exit out of the handler function
}
// if not already exited width is smaller than 850
if (contactInfo !== null) contactInfo.remove()
}
window.addEventListener('resize', resizeHandler)
resizeHandler()
I’ve moved the contact template string into it’s own variable assignment. It’s now not tightly linked to .header-module--logo--B7flj
which gives you a bit more flexibility and re-usage.
I have also created a separate handler function. This is instead of creating a function inside of the addEventListener. Just a bit clearer and easier to work with.
resizeHandler breakdown
finding and assigning elements
With querySelector we get the header element and assign to the header variable.
Then we search from that header element for #phoneNumberBox
element and assign it to contactInfo.
innerWidth > 850
We check if the innerWidth is larger than 850
Note: querySelector returns either an element or if not found null
.
Checking to see if contactInfo is null
we can see if it already exists — we don’t want to continuously be adding contact infos to the end of the header.
If contactInfo doesn’t exist then add it with insertAdjacentHTML
We then exit out of the function with a return
statement
innerWidth < 850
If we haven’t already exited in the last step we know the width is smaller than 850
This time we check to see if contactInfo isn’t null !== null
. Which means contactInfo exists and so remove it.
Again this really isn’t the way to do this
Toggling
Here’s a preferrable option toggling a class of ‘hide’ instead. No templates and quite a bit simpler.
const resizeHandler = function(event) {
const contactInfo = document.querySelector('#phoneNumberBox')
contactInfo.classList.toggle('hide', window.innerWidth < 850)
}