0

Onmouseover description box

Anyone knows a simpler code compared to what ive created ? https://code.sololearn.com/Wh6vc2k5aqd5/?ref=app

26th Oct 2017, 10:01 AM
Lee Jing Yong
Lee Jing Yong - avatar
3 ответов
+ 6
Your 'y' variables aren't declared in local scope of your functions, because there was no 'var' keyword: so JS interpreter will declare them in global scope... in your (simple) case, that doesn't matter, but could be a hudge source of bugs ^^ Anyway, you doesn't need them, as you could simply (directly) do: function showDes(x){ document.getElementById(x).style.display = "block" } function hideDes(x){ document.getElementById(x).style.display = "none" } ... as getElementById() method return the reference, you can do it in one line, without intermediate variable created (or you can also reuse the 'x' variable, as you doesn't need the 'id' string value later ;)
26th Oct 2017, 12:23 PM
visph
visph - avatar
+ 5
In this case, that clean almost js rather than html ;) To more clean your html, you can avoid event listeners declaration in inlined attributes, and do it dynamically (on page loaded): this will also make you able to call functions which are not in the global scope (more clean/safe js), even if it add some lines of js code (cleaning code is not necessarly minimizing it ;P)... Try this next code, where I handle two ways of layout (hidden element child or next neighbour of master element) at once (try also with and without the css rules added to the children description of #first to see differences ;)): <div id="first" class="sites"> First <div class="description" style="position:absolute;"> first description </div> </div> <br> <div> <div id="second" class="sites">Second</div> <div class="description"> second description </div> </div> document.addEventListener('DOMContentLoaded',function() { var sites = document.querySelectorAll('.sites'); var i = sites.length; while (i--) { sites[i].addEventListener('mouseover',showDes); sites[i].addEventListener('mouseout',hideDes); } function showDes(){ var target = document.querySelector('#'+this.id+' > .description')||document.querySelector('#'+this.id+' + .description'); target.style.display = 'block'; } function hideDes(){ var target = document.querySelector('#'+this.id+' > .description')||document.querySelector('#'+this.id+' + .description'); target.style.display = 'none'; } });
26th Oct 2017, 5:38 PM
visph
visph - avatar
0
thanks for the answer. That helped alot in making the html clean
26th Oct 2017, 4:07 PM
Lee Jing Yong
Lee Jing Yong - avatar