2

I have a copy script built in to the page I am working on, and when the copy JS is inline, it works great, but as soon as I moved it external, it produces the following error: copy.js:1 Uncaught TypeError: Cannot read property 'addEventListener' of null

I am unsure why because when inline there is no issues. Copy of the section code is:

    <?php
$connect = mysqli_connect("localhost", "brandina_templat", "REMOVED", "brandina_templates");  
$catresult = "SELECT * FROM categories";
$catquery = mysqli_query($connect,$catresult);
$catquery2 = mysqli_query($connect,$catresult);
?>
<html>  
      <head>  
           <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />  
           <title>Templates Sheet | Brandin Arsenault's</title>    
           <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
           <script src="js/bootstrap.js"></script>  
           <script src="js/tabcontent.js"></script> 
           <link href="css/bootstrap.css" rel="stylesheet" />  
      </head>   
      <body>  
       <div class="container">  
                <br />  
                <h1 align="center">Templates Sheet</h1>
                    <center><ul class="tabs">
<?php
    if(!$catquery)
    {
        die('Invalid query: ' . mysql_error());
    }
        while($row = mysqli_fetch_array($catquery))
        {
            $number=$row['number'];
            $tabname=$row['tabname'];
            $catname=$row['catname'];
            echo "<li class='tab-link' data-tab='$tabname'>$catname</li>";
        }
?>
        </ul>
<?php
    if(!$catquery2)
    {
        die('Invalid query: ' . mysql_error());
    }
        while($row = mysqli_fetch_array($catquery2))
        {
            $number=$row['number'];
            $tabname=$row['tabname'];
            $catname=$row['catname'];
            $result = "SELECT * FROM templates WHERE category=$number";
            $query = mysqli_query($connect,$result);
            echo "<div id='$tabname' class='tab-content'>
                                        <table><center>";
                    $c = 0;
                    $n = 3;
                if(!$query)
                    {
                        die('Invalid query: ' . mysql_error());
                    }
                        while($row = mysqli_fetch_array($query))
                            {
                                $id=$row['id'];
                                $longname=$row['longname'];
                                $shortname=$row['shortname'];
                                $text=$row['text'];
                                    if($c % $n == 0 && $c != 0)
                                        {
                                            echo '</tr><tr>';
                                        }
                                    $c++;
                                    echo "
                                        <td>
                        <center><b>$longname</b></center><textarea id='$id' cols='25' rows='3'>$text</textarea><br /><button id='$shortname'>Copy</button>
                                        </td>
                                        <script>
                                            var shortname = '$shortname';
                                        </script>";
                            }
            echo "</center></table></div>";
        }
?>
<script src='js/copy.js'></script>
</center>
</div>
</body>
</html>

copy.js is:

    document.getElementById(shortname).addEventListener('click', function() {
    copyToClipboardMsg(document.getElementById('$id'), 'msg');
});
function copyToClipboardMsg(elem, msgElem) {
      var succeed = copyToClipboard(elem);
    var msg;
    if (!succeed) {
        msg = 'Copy not supported or blocked.  Press Ctrl+c to copy.'
    } else {
        msg = 'Text copied to the clipboard.'
    }
    if (typeof msgElem === 'string') {
        msgElem = document.getElementById(msgElem);
    }
    msgElem.innerHTML = msg;
    setTimeout(function() {
        msgElem.innerHTML = '';
    }, 2000);
}

function copyToClipboard(elem) {
      // create hidden text element, if it doesn't already exist
    var targetId = '_hiddenCopyText_';
    var isInput = elem.tagName === 'INPUT' || elem.tagName === 'TEXTAREA';
    var origSelectionStart, origSelectionEnd;
    if (isInput) {
        // can just use the original source element for the selection and copy
        target = elem;
        origSelectionStart = elem.selectionStart;
        origSelectionEnd = elem.selectionEnd;
    } else {
        // must use a temporary form element for the selection and copy
        target = document.getElementById(targetId);
        if (!target) {
            var target = document.createElement('textarea');
            target.style.position = 'absolute';
            target.style.left = '-9999px';
            target.style.top = '0';
            target.id = targetId;
            document.body.appendChild(target);
        }
        target.textContent = elem.textContent;
    }
    // select the content
    var currentFocus = document.activeElement;
    target.focus();
    target.setSelectionRange(0, target.value.length);

    // copy the selection
    var succeed;
    try {
          succeed = document.execCommand('copy');
    } catch(e) {
        succeed = false;
    }
    // restore original focus
    if (currentFocus && typeof currentFocus.focus === 'function') {
        currentFocus.focus();
    }

    if (isInput) {
        // restore prior selection
        elem.setSelectionRange(origSelectionStart, origSelectionEnd);
    } else {
        // clear temporary content
        target.textContent = '';
    }
    return succeed;
}

Thanks in advance!

3
  • Is your PHP interpreter running on all files locally? Commented Sep 6, 2016 at 23:03
  • Maybe remove the dollar signs for the ID $shortname? Commented Sep 6, 2016 at 23:05
  • @BrandinArsenault, Updated my answer, you can check. Commented Sep 6, 2016 at 23:07

1 Answer 1

1

The variable $shortname exists when you use the inline code, but when you move your code to external it doesn't exists anymore.

You can use:

<script>
    var shortname = '$shortname';
</script>
<script src='js/copy.js'></script>

And in your copy.js file you should use:

document.getElementById(shortname).addEventListener('click', function() {

Otherwise - the javascript code is looking for element that it's id is $shortname, and you don't really have one with the value.

Sign up to request clarification or add additional context in comments.

10 Comments

thank you for replying. JS continues to produce the error as in my original post. I am unsure why. I used your steps, and totally understand what you're saying, but it sadly is not fixing the issue.
1. How do you print the variables? 2. What you html looks like?
1. You don't really want to set the <script src="js/copy.js"> inside the loop. 2. the shortname inside getElementById should be without the quotes (it's the name of the variable, not the string)
I appreciate you helping me with this. I have moved the script defining the var in in and outside of the loop. Inside the loop, no errors are produced, but no function happens when using the Copy button. Outside of the loop, it produces the original error. I have made the suggested changes to the getElementById function and this is occuring. I appreciate you helping me with this.
Without looking at your complete code, after the changes, it's hard to help. Note that instead of using id you might want to use some other selector (like class, which is not unique).
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.