IT, Islam, Social, My life

Web Programming: Show / Hide Elements with JavaScript

If you would like to show / hide certain elements of your page based on user action, such as clicking a button or choosing a value from a select box, you can use JavaScript to achieve your task.

The first thing we need to do is decide which user action will cause elements to appear / disappear on the page. Lets say, for example, that we we want to show a disclaimer, and only allow the user to continue if they agree to the disclaimer. We will create two radio buttons, and one submit button:

Now, lets start building the JavaScript. At the end of your HTML file, lets define the following script:<script>
var continue_button = document.getElementById('continue');
continue_button.style.visibility = 'hidden';
</script>

So far, the script we just created will cause the Continue button to disappear once the page is loaded.
Now, we want the user to be able to see the Continue button if they choose ‘Yes’ from the radio button group. We also want the Continue button to disappear again if they choose the ‘No’ radio button.

Now, when a user clicks either ‘Yes’ or ‘No’, the JavaScript toggle function will be called, and the current agree object will be passed to the function with the this keyword. Let’s define the toggle function and add it to our existing JavaScript above:

Notice that we define continue_button outside of the toggle function. We do this so that document.getElementById only needs to be called once for each page load. Had you defined continue_button inside the toggle function, the script would have to retrieve the Continue button element and assign it to a JavaScript variable each time you call toggle.

You could have also set the visibility of the Continue button with the HTML style attribute as follows: