programmatically hide the Blocks using Javascript

213 views
Skip to first unread message

Navjot Singh

unread,
Jun 17, 2021, 3:08:12 AM6/17/21
to Blockly
Hello,

I couldn't find this in the docs, but is it possible to hide a block/set of blocks programmatically using JavaScript, based upon some event/Condition that is triggered from outside of the Blockly workspace?

Thanks

Beka Westberg

unread,
Jun 18, 2021, 9:41:45 AM6/18/21
to Blockly
Hello,

As far as I know, there's no way to hide blocks while having them still on the workspace (ie included in code generation and serialization). However, you can make it look like they've been hidden by serializing them, deleting them, and then deserializing them when you want them to reappear.

For example, if you wanted some blocks to be hidden when a button is clicked you could do something like:
```
myButton.onClick(function() {
  var myBlocks = workspace.getAllBlocks();  // You could filter these.
  // var myBlocks = workspace.getBlocksByType('my_block_type');  If you know the types of the blocks you could do this.
  // var myBlocks = workspace.getBlockById('my_block_id'); If you know the id of the blocks you could do this.

  xmlArray = [];  // Some global variable.
  for (var i = 0; i < myBlocks.length; i++) {
    var block = myBlocks[i];
    xmlArray.push(Blockly.Xml.blockToDomWithXY(block));  // Will serialize this block and all children to XML
    block.dispose();
  }
}
```

Then when you want to show the blocks again, you could do something like:
```
for (var i = 0; i < xmlArray.length; i++) {
  Blockly.Xml.domToBlock(xmlArray[i]);  // Adds the bliock back to the workspace.
}
```

That code is completely untested, and some of the method names may be wrong, but that's the basic idea :D

I hope that helps! If you have any further questions please reply!
--Beka

Navjot Singh

unread,
Jun 22, 2021, 9:08:02 AM6/22/21
to Blockly
Hello ,

That seems to be a reasonable work around. I shall try that. 

Thanks,
Navjot
Reply all
Reply to author
Forward
0 new messages