Home > OS >  How can I convert an 'on click' button for history.back into pure JavaScript in template.j
How can I convert an 'on click' button for history.back into pure JavaScript in template.j

Time:01-31

I have this inline code on blog articles to take a user back to the previous page:

<button type="button" onclick="history.back();">Back</button>

How do I convert it to pure JavaScript to remove the inline 'onclick' and put the code into my template.js instead?

I presume the html would change to something like this:

<button type="button" >Back</button>

And the JavaScript would be something along the lines of the following, but I'm missing a crucial part:

if (document.querySelector(".back")) {
  // there will only ever be one instance of the class "back"
  let backButton = document.querySelector(".back");
  backButton.onclick = function handleClick() {
  // what goes here?
  }
}

Am I along the right lines, or is there more to it that that? TIA

CodePudding user response:

Using simple syntax:

const backButton = document.querySelector(".back"); 
if (backButton) backButton.addEventListener("click", () => history.back());

alternatively use optional chaining

document.querySelector(".back")?.addEventListener("click", () => history.back());

As noted in a comment: If the script you execute is present before the button exists in the page, you need to wrap in a load event listener:

window.addEventListener("DOMContentLoaded", () => {
  document.querySelector(".back")?.addEventListener("click", () => history.back());
});

CodePudding user response:

you can write event listener for it too.

like this :

document.querySelector(".back").addEventListener('click',()=>{
  history.back()
})
  • Related