简体   繁体   中英

Stopping IE from jumping to top of page when HTML element is added via js

I have a page with an ASP:Grid with a small copy button in each line to copy the text inside the cell. To copy the text I wrote the following javascript function:

var copyText = function (p_text) {
  $(".copy").append("<textarea id='test'></textarea>");
  $("#test").val(p_text);
  var cutTextarea = document.querySelector("#test");
  cutTextarea.select();
  document.execCommand("copy");
  $("#test").remove();
}

It works perfectly fine in Firefox and Chrome. The copying also works for IE11 except that it always jumps to the top of the page which is really annoying. In Firefox and Chrome it stays at the scrolled position. I saw some similar problems and tried to save the current position before I append my textarea and to scroll there at the end of the function with these lines:

var selectTop = $("body").offset().top;
$("body").scrollTop(selectTop);

$("body").offset().top returns 0 so it does not work. I found some other possible solutions but was not able to implement them so that they would work for my case. Hope someone can give me a working solution :)

Thanks in advance!

I just stumbled on this question while looking for a similar answer (with a copy/paste function as well), so even though it is about 3 years old, here's how I finally managed to solve it:

I was lucky enough (I guess?) to have a position: fixed div accessible in my page. So the element I was creating, I made sure to set a zero size, and appended it to that fixed div, which meant no scrolling happened. End result being something like this:

function copyStringToClipboard(str) {
    var el = document.createElement('textarea');
    el.value = str;
    el.setAttribute('readonly', '');
    el.style = { position: 'fixed', height: 0, width: 0, padding: 0, margin: 0 };
    //create in position: fixed element to avoid re-scrolling the page in IE11
    var container = document.getElementById("fixed-position-div"); 
    container.appendChild(el);
    el.select();
    document.execCommand('copy');
    container.removeChild(el);
}

I hope that can help someone!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM