Using JS in WP
-
I’ve written a piece of Javascript below. Very simply if a user clicks on the respective element on the page an overlay opens or closes thanks to the JS below.
I’m using this piece of Javascript to close the overlay…
this.searchCloseBtn.addEventListener("click", this.closeOverlay())
But it doesn’t work, it only works if I change it to this…
this.searchCloseBtn.addEventListener("click", ()=>this.closeOverlay())
And I can’t figure out why this is and I’ve no idea where else to ask this question.import axios from "axios" class Search { // 1. The constructor is where the object is created/initiated, hence the object properties below constructor() { this.searchOpenBtn = document.querySelectorAll(".js-search-trigger") this.searchCloseBtn = document.querySelector(".search-overlay__close") this.searchOverlay = document.querySelector(".search-overlay") this.doEvents() } // 2. Events (also called listeners) handles responses to user click event(s). doEvents() { this.searchOpenBtn.forEach(element => { element.addEventListener("click", e=>{ e.preventDefault() this.openOverlay() }) }); this.searchCloseBtn.addEventListener("click", ???? this.closeOverlay() ????) } // 3. Methods/Functions openOverlay() { console.log('In openOverlay') this.searchOverlay.classList.add("search-overlay--active") return false } closeOverlay() { console.log('In closeOverlay') this.searchOverlay.classList.remove("search-overlay--active") } } export default Search;
- The topic ‘Using JS in WP’ is closed to new replies.