how to hide/show dom element in google closure
Asked Answered
H

3

9

domA.style.display = "none"; domA.style.display = "block;

I could not find such functions in the library, but I guess they must have it somewhere.

Hypocycloid answered 23/12, 2009 at 19:34 Comment(0)
L
15
<html>
<head>
<script src="http://closure-library.googlecode.com/svn/trunk/closure/goog/base.js" type="text/javascript"></script>
<script language="JavaScript">
    goog.require('goog.style');
</script>
</head>
<body>
   <div id="myElement">test</div>
</body>
</html>
<script> 
    goog.style.setStyle(goog.dom.$("myElement"), "display", "none");
    // or
    goog.style.showElement(goog.dom.$("myElement"), false);
</script>
Lacagnia answered 29/12, 2009 at 21:1 Comment(2)
according to what folks say on closure group, $ functions will probably be removed in favor of goog.dom.getElement('myElement') style functionsComedo
This approach is now outdated, as below :)Tallyman
P
5

Another option is

var elA = goog.dom.getElementByClass('sdf');

goog.style.showElement(elA, true) // show element

goog.style.showElement(elA, false) // hide element

Premier answered 24/4, 2013 at 12:10 Comment(1)
This is deprecated. Use setElementShown() instead.Aspergillosis
T
4

According to the more recent official documentation here, the following is recommended for setStyle:

Sets a style value on an element. ... When possible, use native APIs: elem.style.propertyKey = 'value' or (if obliterating old styles is fine) elem.style.cssText = 'property1: value1; property2: value2'.

This would suggest goog.dom.getElement('myElement').style.display = 'block'; as in your question.

It's also helpful to note that if you use showElement, setting the second argument to true will return the element to its default style. As it says:

True to render the element in its default style, false to disable rendering the element.

What this means, though, is that if you set display: none in your CSS, setting true still won't show the element because the CSS default style is to hide the element!! This is different than, say, with jQuery.

To toggle, you can do this:

var el_style = goog.dom.getElement('myElement').style;
el_style.display = (el_style.display === "none" ? "block" : "none");
Tallyman answered 14/12, 2013 at 2:28 Comment(1)
The link "official documentation here" seems now broken.Kneehigh

© 2022 - 2024 — McMap. All rights reserved.