Showing posts with label display. Show all posts
Showing posts with label display. Show all posts

Oct 31, 2009

JavaScript Switch Statement and Hiding elements

I have been planning to hide some images in my personal project and cycle through them when a button is clicked but never managed to get to that. However, after placing a Utube video on the Home page of our group project and then having one of our group members add Weather information, via an API, we discussed having one present on our Home page and the other present on a different page.

So I decided to experiment with hiding / un-hiding the Utube video and Weather forecast on our website. Initially, I started by using some IF statements but that got a little messy so I decided to use a JavaScript switch statement instead. This is what I came up with:



Basically, the switch statement takes the variable ‘title’ and depending, on what its value is, executes some statements. This is so much cleaner than using a bunch of IF / ELSE statements.

If ‘title’ equals ‘Trails’ or ‘Events’ then specific things are preformed according to the code defined in the relevant section, otherwise, the default section is executed.

The only other thing I had to do to hide / un-hide the Utube video or Weather forecast was to define a CSS class of ‘hidden’ or ‘unhidden’ and place the action (hide / un-hide) in the proper section of the switch statement.



The only thing you need to decide is whether to use visibility: hidden or display: none. Visibility hidden hides the element but it still takes up space and display: none removes the element completely from the document. When un-hiding an element you can either use display: block or display: inline. Display block only allows one element of its kind to be displayed (starts a new paragraph). Display inline allows multiple elements to be displayed on one line. There are a few more display properties but I am not currently concerned with them.