I have been stuck on this for a good hour now and i know its something so simple but cant wrap my head around it 🤦🏽
Soooo both variables that i have set in the constructor are undefined outside of the constructor when calling them.
This is a js file eventually being used for a search component on a shopify site. Thanks in advance!
See the code below:
class PredictiveSearch extends HTMLElement {
constructor(){
super();
//Set elements
this.searchBtn = this.querySelector('#search-btn');
this.searchContainer = this.querySelector('#main-search_wrapper');
// Set event listeners
this.searchBtn.addEventListener("click", this.openSearch);
}
// Open search overlay
openSearch(){
console.log(this.searchContainer);
this.searchContainer.style.display = "block";
}
}
customElements.define('predictive-search', PredictiveSearch);
2
Answers
I believe that this is because
this
doesn’t refer to the class/instance of the class when it’s inside theconstructor()
function. I think it refers to the function itself.Your HTML probably hasn’t been loaded when
openSearch()
is called. Check if the elements have been loaded first before calling the function.If this doesn’t work, try bind
openSearch()
tothis
in the constructor to make surethis
is correct.