Skip to main content
Inspiring
June 19, 2023
Answered

Toggle layer's visibility and reset previous active layer

  • June 19, 2023
  • 2 replies
  • 622 views

Having a senio moment or a Monday morning crisis here. I'm trying to toggle a layer's visibility with a script (so it can be put on an keyboard shortcut with an action v. useful)

// toggle top layer
// app.activeDocument.artLayers[0].visible = !app.activeDocument.artLayers[0].visible;

 

Nice one liner, only works if the layer you want to control is at the very top.

 

// Switch off any dialog boxes
displayDialogs = DialogModes.ERROR; // OFF 


// call the source document
var srcDoc = app.activeDocument;

// current layer
var originalName = app.activeDocument.activeLayer.name;

var myLayerName = "that_toggle_layer"; //layer to be toggled

// select toggle layer
srcDoc.activeLayer = srcDoc.artLayers.getByName(myLayerName);

// toggle the (in)visibility
srcDoc.activeLayer.visible = !srcDoc.activeLayer.visible;

// select original layer, as it was at the start
srcDoc.activeLayer = srcDoc.artLayers.getByName(originalName);


// Reset any dialog boxes
displayDialogs = DialogModes.ALL; // OFF

So I'm a little confused as to why the longer snippet won't work. It should select by name the layer in question, switch ON the visiblity if its OFF (or vice versa)  and then, here's the trick, set the active layer BACK to the one at the start.

 

Only I can't see the wood for the trees this morning. Any help would be appreciated.

 

 

This topic has been closed for replies.
Correct answer c.pfaffenbichler

Please 

var originalLayer = app.activeDocument.activeLayer;

and

app.activeDocument.activeLayer = originalLayer;

 to identify and reselect the originally selected Layer. 

2 replies

Stephen Marsh
Community Expert
Community Expert
June 19, 2023

@c.pfaffenbichler beat me to it... getByName accepts a "string" – whereas you were calling a variable.

 

https://theiviaxx.github.io/photoshop-docs/Photoshop/ArtLayers/getByName.html

Inspiring
June 19, 2023

Also by getting layer by name (and making it the activeLayer) it automatically swiches the visibility to on!

c.pfaffenbichler
Community Expert
Community Expert
June 19, 2023

You don’t need to make the Layer the activeLayer to hide it, by the way. 

c.pfaffenbichler
Community Expert
c.pfaffenbichlerCommunity ExpertCorrect answer
Community Expert
June 19, 2023

Please 

var originalLayer = app.activeDocument.activeLayer;

and

app.activeDocument.activeLayer = originalLayer;

 to identify and reselect the originally selected Layer. 

Inspiring
June 19, 2023

D'oh! 😄 also, thank you!