Search code examples
javascripthtmljsfiddle

JSFiddle example working on web but is not working on my pc


I was looking on google a script to copy a input field and this came across:

https://jsfiddle.net/9q3c1k20/

My example:

    document.getElementById("copy-text").onclick = function() {
      this.select();
      document.execCommand('copy');
      alert('This is a test...');
    }
    
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>Untitled Document</title>
    <script src="http://code.jquery.com/jquery-1.11.0.js"></script>
    </head>
    
    <body>
    <input id="copy-text" type="text" value="Select a part of this text!">
    </body>
    </html>


Solution

  • The script selecting #copy-text is running before the document body (and the input element) has been parsed. Move the script to the bottom of the body:

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>Untitled Document</title>
    <script src="http://code.jquery.com/jquery-1.11.0.js"></script>
    </head>
    
    <body>
    <input id="copy-text" type="text" value="Select a part of this text!">
    <script>
    document.getElementById("copy-text").onclick = function() {
      this.select();
      document.execCommand('copy');
      alert('This is a test...');
    }
    </script>
    </body>
    </html>
    

    But it's more elegant to put your script in a separate .js file and just give it the defer attribute:

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>Untitled Document</title>
    <script src="http://code.jquery.com/jquery-1.11.0.js"></script>
    <script src="myscript.js" defer></script>
    </head>
    <body>
    <input id="copy-text" type="text" value="Select a part of this text!">
    </body>
    </html>