Say OL
Say OL

Reputation: 280

Define a keyword to replace a long url

To create download button I normally use:

<button><a href="url-to-the-file"></a></button>

Is there any way to define myfile = url-to-the-file so that I can use just:

<button><a href="myfile"></a></button>

Upvotes: 0

Views: 242

Answers (1)

Greg Pettit
Greg Pettit

Reputation: 10830

Per my comment, I'm not sure why you would want to do this, but for example you could replace the short text with the real links fairly easily. Just as a very basic example (http://jsfiddle.net/7vbv9oxc/):

HTML:

<button>
  <a href="googs">Click</a>
</button>

JS:

var links = {
    googs: "http://google.com"
}

// jQuery but vanilla JS shouldn't be hard
$('a').each(function(){
    var $this = $(this);
    var shortLink = $this.attr('href');
    if(typeof(links[shortLink]) !== "undefined") {
        $this.attr('href', links[shortLink]);
    }
});

Alternatively, you could do the substitution at click time, saving iterating over all the anchor tags.

$('a').on('click', function(e) {
    var $this = $(this);
    var shortLink = $this.attr('href');
    if(typeof(links[shortLink]) !== "undefined") {
        $this.attr('href', links[shortLink]);
    }
});

We don't prevent default (or return false) because we WANT it to act like a normal anchor, but after the swap has been made. If you want to do something different before loading or redirecting the target URL, you would add an e.preventDefault() to that code block.

Note (for my own peace of mind!) that none of this code is meant to represent optimizations or best practices; it's just meant to illustrate the idea. For example, you would probably want to put the click listener on an ancestor!

Upvotes: 1

Related Questions