Home > Enterprise >  Call JS function onclick
Call JS function onclick

Time:01-29

The sample code below loads a page with a "Show 3D" clickable div. Onclick, it should load a 3D viewer and display associated data.

<!DOCTYPE html>
<html lang="en">

<head>

  <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous">

  <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X 965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH 8abtTE1Pi6jizo" crossorigin="anonymous"></script>
  <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js" integrity="sha384-ChfqqxuZUCnJSK3 MXmPNIyE6ZbWh2IMqE241rYiqJxyMiZ6OW/JmZQ5stwEULTy" crossorigin="anonymous"></script>

  <script src="https://cdn.jsdelivr.net/npm/ngl@latest/dist/ngl.min.js"></script>

  <script>
  function showPDB(path,id) {
    var stage = new NGL.Stage(id, {backgroundColor:'white'});
    stage.loadFile(path).then(function (o) {
      o.addRepresentation("cartoon", {color: 'white' });
      o.autoView();
    });
  };
  </script>

</head>

<body>

  <div >

    <div  data-toggle="collapse" data-target="#show_0" id="_show_0" onclick="showPDB('https://alphafold.ebi.ac.uk/files/AF-P08047-F1-model_v4.pdb', 'viewport_0')">

      <b>Show 3D</b>

    </div>

  </div>

  <div id="show_0" >

    <div >

      <div >

        <div id="viewport_0" style="width:100%; height:800px;"></div>

      </div>

    </div>

  </div>

</body>

</html>

It seems that "Show 3D" needs to be clicked twice for the 3D viewer to load. I would like it to load upon a single click.

I guess this function should be triggered only when the inside of the collapsible element has been fully loaded. I tried to tweak in this direction but I could not find a fix yet.

CodePudding user response:

As it is a collapsible, just give some time to the collapsible to load. TO do that, you can wrap the entire script inside a set timeout like below

function showPDB(path,id) {
  setTimeout(() => {
    var stage = new NGL.Stage(id, {backgroundColor:'white'});
    stage.loadFile(path).then(function (o) {
      o.addRepresentation("cartoon", {color: 'white' });
      o.autoView();
    });
  });
};
  • Related