+ 1

why this isn't working?

I have a simple code: uno() is called via an onclick event in a button and is supposed to make visible a div with some text in it. The div is set to hidden in the css: function uno(){ var v=document.getElementsByClassName("descript 1"); v.style.visibility= "visible"; setTimeout(ocultar(),3000); } function ocultar(){ v.style.visibility = "hidden"; } But i get this error "Uncaught TypeError: Cannot set property 'visibility' of undefined" when i look on the console and the debugger signals this line v.style.visibility= "visible"; as the source of the error" What mistake can i possibly making? All help is much appreciated.

29th Aug 2017, 8:10 AM
Milo Il Giovane
Milo Il Giovane - avatar
3 Answers
+ 11
@Milo i also noticed you used the getElementsByClassName selector, you should specify what element you want to use. - 1 - E.g - First element with "dog" class getElementsByClassName('dog')[0] - 2 - ... and i also noticed you called the ocultar() function in a wrong way, it should be: setTimeout(ocultar,3000); ... rather than: setTimeout(ocultar(), 3000);
29th Aug 2017, 9:49 AM
Maz
Maz - avatar
+ 11
onload = function(){ // ... all your code goes here! } Highly recommended to use events inside the Javascript code and not inside the HTML to prevent errors, in this case you would prefer to use: onload = function(){ element.onclick = uno; function uno(){ // code... }; } // best practice. In alternative pass the element as an argument in the HTML by using the "this" keyword, as i already said if the element is not ready you can't use it in you Js. You could also put your function in the <script></script> tag at the end of your body to solve it easily. :)
29th Aug 2017, 8:42 AM
Maz
Maz - avatar
+ 10
@kay Sololearn places the script in the head element when using the JS tab that way the script loads before the doc is ready and you get the error. https://www.sololearn.com/discuss/300061/?ref=app
29th Aug 2017, 9:31 AM
Lord Krishna
Lord Krishna - avatar