Linkify (plain url to link) based on windowSize

Hi all,

this is what i would like to do

  1. when window size is < 1000, change any plain text url to a clickable one
  2. when window size is > 1000, change any plain text url to a clickable one, replaced by the word “Link”.

I had a go but it seems to be failing somewhere!

Anyone can shed some light?

Thanks

<html>
<head>
   <script src="https://code.jquery.com/jquery-3.1.0.js"></script>
   <script>$(document).ready(function() {
    function checkWidth() {
        var windowSize = $(window).width();
        if (windowSize < 1000) {
          $('div').each(function(){ $(this).html( $(this).html().replace(/((http|https|ftp):\/\/[\w?=&.\/-;#~%-]+(?![\w\s?&.\/;#~%"=-]*>))/g, '<a href="$1">$1</a> ') ); });
        } //make plain text url clickable
        else if (windowSize < 1000) {
          $('div').each(function(){ $(this).html( $(this).html().replace(/((http|https|ftp):\/\/[\w?=&.\/-;#~%-]+(?![\w\s?&.\/;#~%"=-]*>))/g, '<a href="Link">Link</a> ') ); });
        } //convert plain text to clickable word "Link"
        
    }
    checkWidth();
    $(window).resize(checkWidth);
    $(window).onload(checkWidth);
});
  </script>  
</head>  
<body>
  <div>https://www.google.com/</div>
  <div>https://www.yahoo.com/</div> 
  </body>
</html>
    if (windowSize < 1000) {

    else if (windowSize < 1000) {

… those two conditions are identical.
Also keep in mind that this is a one-way operation. Once you destroy the link data by replacing it with <a href="Link">Link</a>, there is no way to recover it if the window size gets smaller again.

1 Like

Nice solution from @jakecigar in the jquery forums

HTML:

<div>https://www.google.com/</div>
<div>https://www.yahoo.com/</div>

CSS:

@media only screen and (max-width: 1000px) {
  .abbr {
   font-size:0;
    text-decoration:none;
  }
  .abbr:after {
    display: inline;
    font-size:16px;
    content: "link";
    color:black;
  }
}

JS:

$(function() {
  $('div').each(function() {
    $(this).html($(this).html().replace(/((http|https|ftp):\/\/[\w?=&.\/-;#~%-]+(?![\w\s?&.\/;#~%"=-]*>))/g, '<a class=abbr href="$1">$1</a> '));
  });
})

just thinking off the top of my head but couldn’t you just do this with css. if you set up your links somethign like

<a href="http://www.example.com" class="link"><span>Some long link description text</span></a>

Then you can hide the span and insert your new text

<style>
@media only screen and (max-width: 999px) {

    .link:before {
       content: "Link";
    }
    .link span{
            display: none;
    }
}
</style>

i think that all works as you are asking and not a drop of js in sight. try resizing your browser and it should change responsively.

1 Like

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.