Hiding and Showing Elements with Javascript

This is a quick tutorial to explain how you can easily show and hide page elements with javascript.

To begin with, each item that you want to hide/show should have a unique HTML ID. Let’s begin with a very simple HTML page.

<h1>This is my title</h1>
<div id="content">
	<h2>Div1 Follows</h2>
	<div id="div1">
		This is where my first div will be.
	</div>
	<h2>Div2 Follows</h2>
	<div id="div2">
		This is where my second div will be.
	</div>
</div>

We will then write a function that will hide all of the appropriate divs (in this case, div1 and div2).

Javascript and Screen Sizes

With mobile browsers becoming more and more prevalent, it becomes more and more necessary to develop a version of your Web site for those browsers. There are a lot of scripts out there that are designed to detect mobile browsers, but many of them need to be updated every time a new mobile browser is developed.

A quick and easy way to detect mobile browsers is to detect the users’ display resolutions. Certainly, this is far from flawless, but it’s not a bad method. Assuming that the browser supports javascript, you can easily figure out the users’ resolutions by using the screen.width and screen.height properties. You can fairly safely assume that most users with a screen width of less than 600 pixels is viewing your site with a handheld of some sort. Therefore, you should use the following javascript to perform any special actions that need to be taken when being viewed with a handheld.

<script type="text/javascript">
if(screen.width <= 600) {
mobileSite();
}
</script>

In my case, I’m using a similar script to determine whether or not TinyMCE should be initiated or not. My TinyMCE init script looks like:

<script type="text/javascript">
if(screen.width>600) {
tinyMCE.init();
}
</script>

I hope that helps some people.