linkifyjs icon indicating copy to clipboard operation
linkifyjs copied to clipboard

Is it possible to use different tags based on the content of the URL?

Open ghostofcain opened this issue 10 years ago • 3 comments

Hi,

I've been using linkifyjs to add links to json strings coming from an ajax call and it is working well with one caveat.

For links that end with a .gif, I need to be able to wrap them in a structure like this:

<x-gif src="abc.gif"></x-gif>

So that gifs automatically animate.

I had a look at the options and could see that I can specify the tagName in the options (http://soapbox.github.io/linkifyjs/docs/options.html):

tagName: 'a',

but I can't seem to figure out if this is possible to do conditionally. I would still like to use a for normal links but only if the links end with a .gif I would like to change the tagName.

Is it possible to do this?

Many thanks,

ghostofcain avatar Oct 15 '16 08:10 ghostofcain

Ok figured out a way to do it but I'd still be interested to know if it was possible to natively do this.

In case anyone is interested in how I did it:

// foreach element (specified by an id):
$('#' + id)
    .linkify({
        validate: {
            url: (val: any) => {
                return val.slice(-3) !== 'gif';
            },
            email: false
        }
    });

$('#' + id)
    .linkify({
        validate: {
            url: (val: any) => {
                return val.slice(-3) === 'gif';
            }
        },
        tagName: 'x-gif'
    });

// after everything has been "linkified":
$("x-gif").each((i, el) => {
    var src = el.getAttribute("href");
    el.setAttribute('src', src);
    el.removeAttribute('href');
    el.removeAttribute('target');
    el.removeAttribute('class');
    el.setAttribute('class', 'gif-image');
    el.innerHTML = '';
});

ghostofcain avatar Oct 15 '16 10:10 ghostofcain

Hey @ghostofcain, you can specify most options (including tagName and format) as a function. The function should take as arguments the link and the link type, and return the value for that option.

e.g.,

$('#'+id).linkify({

  // Use x-gif tag for GIFs
  tagName: (href, type) => {
    if (type === 'url' && href.slice(-4) === '.gif') {
      return 'x-gif';
    }
    return 'a';
  },

  // The contents of the x-gif tag should be empty.
  format: (val, type) => {
    if (type === 'url' && val.slice(-4) === '.gif') {
      return '';
    }
    return val; // regular value
  }
});

I hope that helps.

nfrasser avatar Oct 15 '16 17:10 nfrasser

Thank you very much @nfrasser. It works as you pointed out. I still have to do one more processing to change href to src but everything else is working well.

ghostofcain avatar Oct 16 '16 07:10 ghostofcain