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?


   <script src=""></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"

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




        @media only screen and (max-width: 1000px) {
          .abbr {
          .abbr:after {
            display: inline;
            content: "link";


    $(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