how to make less expensive javascript code | Sololearn: Learn to code for FREE!


how to make less expensive javascript code

function tapAddButton(){ var page1 = document.getElementById("page1"); var page2 = document.getElementById("page2"); = "none" = "block" } //Everytime i tap the button. It going to execute var page1 and var page2, but its expensive if execute var everytime i tap the button. //What is the solution??

9/3/2019 8:15:10 PM

Bee David

6 Answers

New Answer


var page1, page2; window.onload = function () { page1 = document.getElementByIf("page1"); page2 = document.getElementById("page2"); } function tapAddButton() { = "none"; = "block"; }


Save those two variables globally and initialize them on document ready. And on the tap you only change the display value.


function tapAddButton(){ = "none" = "block" } var page1 = document.getElementById("page1") var page2 = document.getElementById("page2")


Dragonxiv can you show me an example please


Zeke Williams it works!, thank you so much for your help :)


But i think it will give an error. Because when i access DOM outside the function it always like that