3dmol/3Dmol.js

Unable to access viewer object created using viewer_3Dmoljs[BUG]

sdr0598 opened this issue · 2 comments

I followed this tutorial for embedding a viewer.
Once I have created a viewer, I am trying to style it by accessing it from $3Dmol.viewers["insert_id"].
The issue here is that this approach is not working for me. $3Dmol.viewers["insert_id"] returns {}.

Here is a reduced version of my code (My apologies: I am having trouble to format my code correctly)

<!DOCTYPE html>
<html lang="en">
<head>
<script src="https://3Dmol.org/build/3Dmol-min.js"></script>
<script src="https://3Dmol.org/build/3Dmol.ui-min.js"></script>
</head>
<body>
<div
id="viewer"
style="height: 400px; width: 400px; position: relative"
class="viewer_3Dmoljs"
data-pdb="1ebt"
data-backgroundcolor="white"
data-style="stick"
></div>
<script>
let viewer = $3Dmol.viewers["viewer"];
viewer.setBackgroundColor("orange");
</script>
</body>
</html>

Here is my error message: Uncaught TypeError TypeError: Cannot read properties of undefined (reading 'setBackgroundColor')

  • OS: Windows
  • Browser: Microsoft Edge
  • Version 118.0.2088.46 (Official build) (64-bit)
dkoes commented

The problem is your code is running before the viewer has been instantiated. You need to wait until after the DOM is fully rendered (and even then I'm not 100% you can be guaranteed your code will run after 3Dmol).

You can provide a string of your function in a data-callback attribute. It will be passed an instance of the created viewer.

You could also call $3Dmol.autoload manually (as long as enough of the DOM has been rendered) and pass it a callback that way.

Or you could move away from the embedding approach and use the JavaScript API.

Ok. Thank you for the help. I appreciate it