+ 3

how to make less expensive javascript code

function tapAddButton(){ var page1 = document.getElementById("page1"); var page2 = document.getElementById("page2"); Page1.style.display = "none" Page2.style.display = "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??

3rd Sep 2019, 8:15 PM
Bee David
Bee David - avatar
6 Respuestas
+ 3
var page1, page2; window.onload = function () { page1 = document.getElementByIf("page1"); page2 = document.getElementById("page2"); } function tapAddButton() { page1.style.display = "none"; page2.style.display = "block"; }
3rd Sep 2019, 9:35 PM
Zeke Williams
Zeke Williams - avatar
+ 3
Save those two variables globally and initialize them on document ready. And on the tap you only change the display value.
3rd Sep 2019, 8:47 PM
Dragonxiv
Dragonxiv - avatar
+ 3
function tapAddButton(){ page1.style.display = "none" page2.style.display = "block" } var page1 = document.getElementById("page1") var page2 = document.getElementById("page2")
3rd Sep 2019, 8:54 PM
Dragonxiv
Dragonxiv - avatar
+ 2
Dragonxiv can you show me an example please
3rd Sep 2019, 8:49 PM
Bee David
Bee David - avatar
+ 2
Zeke Williams it works!, thank you so much for your help :)
3rd Sep 2019, 9:42 PM
Bee David
Bee David - avatar
+ 1
But i think it will give an error. Because when i access DOM outside the function it always like that
3rd Sep 2019, 8:56 PM
Bee David
Bee David - avatar