skip to Main Content

Is it somehow possible to add document.referrer js variable right into the a tag like this?

<a href="document.referrer;">Zpět</a>

For purposes of code shortening so all the machinery <script> document.ready .. doesn’t have to be deployed.

EDIT:

For further clarification;
I would prefer something like this to be avoided

<a href="#" id="return-back-one">Zpět</a>
    <script>
    $(function() {
        var back = $('#return-back-one')
        back.on("click", function(e){e.preventDefault();history.back(1)})
     });
    </script>

in favor of something shorter like

<a href="document.referrer;">Zpět</a>

or

<a href="history.back(1);">Zpět</a>

2

Answers


  1. you can’t include variables in tags because html is not a programming laguage, refer this.

    Login or Signup to reply.
  2. This capability is not built into HTML. You need to use JavaScript to do this.

    However you can design your JavaScript in a generic way so that you can have code shortening in future cases. You can do this with regular old JavaScript, or with any JavaScript library.

    One regular (ugly and not necessarily secure) JavaScript way might look like:

    <a data-href="return document.referer || 'https://google.com'" target="_blank">Test</a>
    
    const onDOMContentLoaded = () => {
      const anchorElements = document.querySelectorAll("a[data-href]");
      anchorElements.forEach((anchorElement) => {
        const dataHref = anchorElement.getAttribute('data-href');
        const hrefFn = new Function(dataHref);
        const href = hrefFn();
        if (href) {
          anchorElement.setAttribute('href', href);
        }
      })
      
    }
    document.addEventListener('DOMContentLoaded', onDOMContentLoaded, false);
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search