Changing button text / visibility using the while function?

Hi all,

I’ve been setting up some basic stuff for my own use at work to make life easier for myself, I’m trying to include a “view more / less button” that shows / hides a full cost breakdown of whatever I’m pricing up at the time. I’ve created an onload function which initially will hide the button, but once the first form is submitted the button becomes visible and the text changes depending on what state it’s in. Here’s my code:

var visibility = 1;

var buttontext = 1;

function load() {

while (visibility == 1) {

document.GetElementByID('viewtype').style.visiblility = 'hidden';

}

while (visibility == 2) {

document.GetElementByID('viewtype').style.visiblility = 'visible';

}

while (buttontext == 1) {

el4 = document.GetElementByID('viewtype'),

el4.innerHTML = "View More";

}

while (buttontext == 2) {

el = document.GetElementByID('viewtype'),

el.innerHTML = "View Less";

}

}

But it doesn’t work at all. Can anyone help me out?

Cheers!

First off, why are you using while instead of if?

Secondly, there are some commas where semi-colons should be.

my initial thought process was that I need the script to constantly check for state changes so I thought “if” wouldn’t be the right one to use, I haven’t done JavaScript before so everything’s trial and error (hence why I always ask probably really obvious questions on the forums).

How would you recommend handling this sort of situation? :slight_smile:

While would be correct when you’re listening for an event

Hi @aaron51connelly, there are some misspellings in your code – .getElementById() starts lower case. You can see these kinds of errors in the console of the browser dev tools.

Also as @DaveMaxwell using while won’t work here; it will actually cause an infinite loop as the value of visibility never changes, and freeze the entire page. But where is that load() function getting called in the first place?

That’s true. It looked odd to me in the first place (hence the “why not if” question)

Thanks guys,

The function starts on page load.

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.