0

When a button is clicked it will scroll to the bottom of the page automatically. I can't see the reason in the code why it is doing it. Is there something I am missing?

Code:

        echo "<br>Home Drive : <a class=clear href=$dir>$dir</a><br>";?>
         <p id="demo<?php echo $x; ?>"style="position:absolute;left:-1000px;top:-1000px;">
       <?php echo $dir ?>
        </p>
       <button onclick="copy('demo<?php echo $x; ?>')">Copy Home Drive</button> <br><br>
    


    <?php }
    echo "</div>"; 
}


?>
<script>
function copy(element_id) {
  var aux = document.createElement("div");
  aux.setAttribute("contentEditable", true);
  aux.innerHTML = document.getElementById(element_id).innerHTML;
  aux.setAttribute("onfocus", "document.execCommand('selectAll',false,null)");
  document.body.appendChild(aux);
  aux.focus();
  document.execCommand("copy");
  document.body.removeChild(aux);
}
</script>

Thanks

Here is the updated code. After testing Professor Abronsius method it seems to cause the page to not load. Am I missing anything? <?php

$LDAPFieldsToFind=array
        ("homedirectory", "displayname", "samaccountname");     //The data we want to find from the search

                
            
  
$numresults=$info["count"];
echo"<div style='position: fixed; float: right; padding-left: 450px;'><a class=clear href=javascript:history.go(-1)>Search again</a></div>";
echo "<div><p>There are <b>$numresults</b> results for your search '<i><b>$SearchFor</i></b>'";
if ($numresults>0){

    echo " these are:</p></div>";
    echo "<div>";
    


    <?php }
    echo "</div>"; 
}
else echo "</div><div><br><a class=clear href=javascript:history.go(-1)>Search again</a></div>";
ldap_close($cnx);

?>


<script>
document.querySelectorAll('div.usr button').forEach(bttn=>bttn.addEventListener('click',function(e){
    navigator.clipboard.writeText( this.parentNode.textContent )
    .then(()=>{
      alert( 'Copied' )
    })
    .catch( err=>alert( err ) )
}))
</script>
KCode
  • 27
  • 6

2 Answers2

0

Just use this instead:

navigator.clipboard.writeText(text)

And the scrolling most likely happens because you are selecting text on a new element that is appended to the bottom of the page.

GoldenretriverYT
  • 3,043
  • 1
  • 9
  • 22
0

Disclaimer: This snippet will display an error message but the code works OK when hosted on own server!

A much cleaner method, imo, to the copying of data can be done with the reasonably new Clipboard API - removes the need for adding elements off-screen, appending new elements and deleting them as you were. This also should prevent the scrolling mentioned as that was a byproduct of inadvertantly using focus on your recently added div element.

As your original code uses several br tags to separate displayed items it would be easier ( from a both styling and DOM manipulation/interrogation perspectives ) to use a common parent element for each set of results. You could possibly rewrite the loop logic as follows:

foreach( $info as $arr ){
    $obj=(object)$arr;
    printf(
        '<div class="usr">
            <div>Username: %1$s</div>
            <div>Name: %2$s</div>
            <div>Homedrive: <a href="%3$s">%3$s</a></div>
            <button>Copy Home Drive</button>
        </div>',
        $obj->samaccountname[0],
        $obj->displayname[0],
        $obj->homedirectory[0]
    );
}

And then the rendered content then might appear as follows, for example:

document.querySelectorAll('div.usr button').forEach(bttn=>bttn.addEventListener('click',function(e){
    navigator.clipboard.writeText( this.parentNode.textContent )
    .then(()=>{
      alert( 'Copied' )
    })
    .catch( err=>alert( err ) )
}))
<div class="usr">
  <div>Username: Big_G</div>
  <div>Name: Geronimo</div>
  <div>Homedrive: /nas-vol1/geonimo</div>
  <button>Copy Home Drive</button>
</div>

<div class="usr">
  <div>Username: Poca</div>
  <div>Name: Pocahontas</div>
  <div>Homedrive: /nas-vol2/pocahontas</div>
  <button>Copy Home Drive</button>
</div>

<div class="usr">
  <div>Username: Chief_SB</div>
  <div>Name: SittingBull</div>
  <div>Homedrive: /nas-vol1/SittingBull</div>
  <button>Copy Home Drive</button>
</div>

<div class="usr">
  <div>Username: Tonto</div>
  <div>Name: TomTom</div>
  <div>Homedrive: /nas-vol2/TomTom</div>
  <button>Copy Home Drive</button>
</div>

update: complete test page to illustrate the copy of text

<!DOCTYPE html>
<html lang='en'>
    <head>
        <meta charset='utf-8' />
        <title>Copy Active Directory Info</title>
    </head>
    <body>
    
        <div class="usr">
          <div>Username: Big_G</div>
          <div>Name: Geronimo</div>
          <div>Home drive: /nas-vol1/geonimo</div>
          <button>Copy Home Drive</button>
        </div>

        <div class="usr">
          <div>Username: Poca</div>
          <div>Name: Pocahontas</div>
          <div>Home drive: /nas-vol2/pocahontas</div>
          <button>Copy Home Drive</button>
        </div>

        <div class="usr">
          <div>Username: Chief_SB</div>
          <div>Name: SittingBull</div>
          <div>Home drive: /nas-vol1/SittingBull</div>
          <button>Copy Home Drive</button>
        </div>

        <div class="usr">
          <div>Username: Tonto</div>
          <div>Name: TomTom</div>
          <div>Home drive: /nas-vol2/TomTom</div>
          <button>Copy Home Drive</button>
        </div>
        
        
        <script>
            document.querySelectorAll('div.usr button').forEach( bttn=>bttn.addEventListener('click',function(e){
                navigator.clipboard.writeText( this.parentNode.textContent )
                    .then( ()=>{
                        console.info( '%s\n\n%cCopied!', this.parentNode.textContent.replace(/\ /gi,''),'color:red' );
                        alert( 'Copied' );
                    })
                    .catch( err=>alert( err ) )
            }))
        </script>
    </body>
</html>
Professor Abronsius
  • 33,063
  • 5
  • 32
  • 46
  • Hi, Thanks but I can't get that to work. I have updated the code in the main part of the thread. Is there something I am doing wrong? – KCode Nov 10 '21 at 14:47
  • Does it actually render the HTML OK or is that where the problem is? Check the error console for obvious clues... That said the PHP I posted was untested - the HTML & Javascript was tested and works OK (certainly in Chrome anyway and should also in FF & Opera ) – Professor Abronsius Nov 10 '21 at 15:24
  • I just want to make sure. I am not using the HTML you are using as my records are from active directory and not from a HTML document. That was how the original code worked. – KCode Nov 10 '21 at 16:02
  • I only offered this as an alternative to the `old-school` approach you had using `execCommand` which was initially an IE affectation. For this to work there should be a common parent for the content and the button... however you structure that or print the record is up to you. I appreciate that the data is from AD but that should have no bearing. The question, afterall, really was `"why does the page scroll to the bottom"` which has been resolved by removing `aux.focus()` – Professor Abronsius Nov 10 '21 at 16:16
  • Hi, Thanks. If I Remove aux.focus() the buttons no longer work which is strange. Thanks – KCode Nov 10 '21 at 16:26
  • With your original code that was an issue you highlighted earlier. I appreciate that the HTML I posted is dummy data and your would be dynamically generated but it should illustrate how you can use the clipboard api. I'll post a complete html page with that - create a new page and test it.....? – Professor Abronsius Nov 10 '21 at 16:37
  • Thanks that would be great – KCode Nov 10 '21 at 16:42
  • It seems like there is a issue with the updated code as it displays correctly but the copy function doesn’t work. – KCode Nov 11 '21 at 07:02
  • ah - my guess is that you are not using Google Chrome then. I tested the updated demo in Firefox and indeed - it broke so edited it which seems fine in both chrome & FF – Professor Abronsius Nov 11 '21 at 07:34
  • Hi, I am using chrome its strange. I have even tested a different example and the copy function doesn't work either but it works on online tester. – KCode Nov 11 '21 at 09:53
  • Thanks it is all working now – KCode Nov 12 '21 at 13:52
  • excellent - what was the issue? – Professor Abronsius Nov 12 '21 at 15:00