0

I have a script that randomly generates a room id when joined. I want to copy that ID with a click of a button. It would be easy job with a input element, however, I don't know how to even target that random ID to edit and manipulate it. How could I do that?

function createRoom(){

    var option = document.createElement("option");
    option.text = makeid(10);
    roomSelection.add(option);
    window.sessionStorage.setItem("arhostas", 1);
}

function makeid(length) {
    var result           = '';
    var characters       = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
    var charactersLength = characters.length;
    for ( var i = 0; i < length; i++ ) {
       result += characters.charAt(Math.floor(Math.random() * charactersLength));
    }
    return result;
 }
 
 var roomUrl = document.createElement("div");
roomUrl.innerText = `Room id: ${room}`
roomID.append(roomUrl)
<div id='roomId'></div>

enter image description here

Room ID is already generated when joined to the room. I just need to copy it to the clipboard somehow. Adding a "createRoom" code.

0

2 Answers 2

1

room_id_div is not a valid html-element. You can create an element and assign some properties to it in one go using Object.assign. If you want to use the id within the innerText of the created element, you'll have to create the (random) id separately.

Alternatively you can set the content of a div using a pseudo-selector in css (:before). In that case you don't need to create a random id separately. The downside is that the text within the div can not be selected (hence, not copied to the clipboard).

Both demonstrated in this snippet:

document.addEventListener("click", handle);
document.addEventListener("change", handle);

function handle(evt) {
  const origin = evt.target;
  if (/Room$/.test(origin.id)) {
    return origin.id === "fromIdRoom" ? 
      createRoom1() : createRoom2();
  } else if (origin.id === "roomSelector") {
    if (origin.value !== "-1") {
      document.querySelectorAll("#roomId1 div")
        .forEach(elem => elem.style.backgroundColor = "");
      document.querySelector(`#${origin.value}`).style.backgroundColor = "#FFFFC0";
    }
  }
}

// room id from css pseudo :before
// use [makeId] directly
function createRoom1() {
  const roomParent = document.querySelector("#roomId1");
  roomParent.append(
    Object.assign(
      document.createElement("div"), {
        id: `X${makeId(15)}`, // NOTE: id can not start with a number
      })
  );
  const idNow = roomParent.querySelector("div:last-child").id;
  roomParent.querySelector("select").append(
    Object.assign(
      document.createElement("option"), {
        value: idNow,
        textContent: idNow
      })
  );
}

// room id within innerText
// you'll need to pre-assign [room]
function createRoom2() {
  const room = `X${makeId(15)}`; // NOTE: id can not start with a number
  document.querySelector("#roomId2").append(
    Object.assign(
      document.createElement("div"), {
        id: room,
        innerText: `Room id: ${room}`,
      })
  );
}

function makeId(length) {
  var result = '';
  var characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
  var charactersLength = characters.length;
  for (var i = 0; i < length; i++) {
    result += characters.charAt(Math.floor(Math.random() * charactersLength));
  }
  return result;
}
#roomId1 div:before {
  content: 'Room id from css: 'attr(id);
}
<p>
  <button id="fromIdRoom">create create a room within #roomId1</button>
  <button id="createRoom">create a room within #roomId2</button>

</p>
<div id='roomId1'>
  <select id="roomSelector">
    <option value="-1">Select room</option>
  </select>
</div>

<div id='roomId2'></div>

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

5 Comments

Doesn't work for me. I might be doing something wrong. I added my "createRoom" code. Could you please take a look? My room is generated beforehand.
There's not enough context in your code to say much about it. It seems that you want to add a rooms id to a <select> element?
Well, that script creates a room with a random generated number (on different html file). Now I want to copy that number with a click of a button as you showed. But your code generates that random code and then copies it. I will accept your answer regardless.
Ok, not completely clear to me, but I hope it helped you further along. Added demo functionality for a 'roomselector' just to be sure, but it may well be that's not what you intended.
NB: for creating random strings/-html-id's you may be interested in randomStringExtension within this helper library
0

The navigator.clipboard API is the modern method for copying to the clipboard navigator.clipboard. The tab must be active for you to copy to the clipboard for security reasons. So you can't copy the id in this snippet

You created an element room_id_div that isn't a valid HTML element. So I changed it to a normal div tag.

I created a button to listen for click and then copy the text.

const length = 7;
const button = document.getElementById('copyId');
const roomID = document.getElementById('roomId');
const roomUrl = document.createElement("div");

function makeId(length) {
  let result = '';
  const characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
  const charactersLength = characters.length;
  for (var i = 0; i < length; i++) {
    result += characters.charAt(Math.floor(Math.random() * charactersLength));
  }

  return result;
}

button.addEventListener('click', _ => {
  roomID.innerHTML = '';
  const id = makeId(length);
  navigator.permissions.query({
    name: "clipboard-write"
  }).then(permission => {
    if (permission.state == 'granted') navigator.clipboard.writeText(id).then(_ => alert('Successfully copied to clipboard!!'), _ => alert('Error copying id to clipboard'));
    else alert('Error copying id to clipboard');
  });

  roomUrl.innerText = `Room id: ${id}`;
  roomID.append(roomUrl);
});
<div id='roomId'></div>
<button id="copyId">Generate and Copy Id</button>

1 Comment

That looks great, however, I already have a generated room number, I just need to copy it. Maybe somehow make that ID appear in an input element.

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.