Home > OS >  HTML anchor tag have href first then onclick()
HTML anchor tag have href first then onclick()

Time:03-14

In an anchor tag with both href and onClick, is it possible to have the href first go to the link then execute the onClick()?

For example, I want this anchor tag to first go to the link and then call the highlightButton function.

<a
   
  href="?page={{step.previous_page_number}}" 
  onClick="highlightButton();"
  aria-label="Previous"
>Previous</a>

CodePudding user response:

Nope. You can, however, check and validate the parameter page from the URL when the document is ready then execute the highlightButton() function.

Example:

HTML

<a  href="?page={{step.previous_page_number}}" aria label="Previous">Previous</a>

javaScript

document.addEventListener("DOMContentLoaded", function() {
    const params = new URLSearchParams(location.search);
    const page = params.get("page");

    // Example Validation
    if (page != "" || page != null) {
        highlightButton();
    }

    function highlightButton() {
        // Code goes here
    }
});

CodePudding user response:

No, You cannot do that, by opening a new link, the last page wont work at the background but if you want to use a specific function in the next page, just write the function and call it at the top of your script tag!

Like this :

<script>
    highlightButton()
    function highlightButton() {
        // your code 
    }
</script>
  • Related