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>

A few things I noticed right away.

  • You’re using onload, but that is a DOM API and not a jQuery one. Its also not necessary since you’re code is already in a ready() which occurs when the DOM “loads” (DOM is available, though not all loaded assets, none of which, after loading, could have any affect on window size).
  • Your windowSize check has an else-if that performs the same check meaning it will never pass. Just use else since you’re only checking between two things. < 1000 or not.
  • The approach of using regular expressions to make this change seems excessive and complicated. You can easily use jQuery to access element text and attribute values and replace them with whatever you want without regex.
  • What happens when you replace text and links to the word “Link” and want to go back again? Since you replaced everything, how are you supposed to know how to get back to the original values?

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> '));
      });
    })
1 Like