How to hide or show content based on links or urls via JavaScript/jQuery

I have received many requests for a tutorial that shows how to hide or show content based on links or options that a user picks and reflected on a different page so here it is =)

You can see a working demo here.

Here is the plain HTML:

If you had to choose a drink, what would you choose:
<ul>
	<li><a href="/demo/demo-show-hide-based-on-url.html?option=coke">Coke</a></li>
	<li><a href="/demo/demo-show-hide-based-on-url.html?option=bubble-tea">Bubble Tea</a></li>
	<li><a href="/demo/demo-show-hide-based-on-url.html?option=milk">Milk</a></li>
</ul>

It is a simple list of options for a user to select and the key is in the linking url. There is an option parameter where we are passing over the user’s selected option. The option values (coke, bubble-tea, and milk) will map to their respective div ids on the following page that we will dynamically hide or show.

Here is the JavaScript/jQuery code that executes on the linking page:

1
2
3
4
5
6
7
8
9
10
11
12
13
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
	var option = 'coke';
	var url = window.location.href;
	option = url.match(/option=(.*)/)[1];
	showDiv(option);
});
function showDiv(option) {
	$('.boxes').hide();
	$('#' + option).show();
}
</script>

Line 1 imports the jQuery library from Google’s content distribution network (CDN). There are a couple of reasons why you should use CDNs including decreased latency and increased parallelism. If you are interested in reading the details, here is a nice post.

Line 4 assigns the default div id that will be shown which in this case is coke.

Lines 5-6 parses the option value from the url information.

Line 7 calls the showDiv() function and passes the option value as an argument.

In line 10 of the showDiv() function, we hide all the divs in case there are any that are opened. We do this using the jQuery class selector where we select all the elements with the boxes class.

Line 11 will use the id (e.g. #) jQuery selector using the option parameter that was passed over and show the element via the jQuery .show() method.

Here is the HTML code for the second page with our dynamic displayed content:

1
2
3
4
5
6
7
8
9
10
11
12
<div class="boxes" id="coke">Coke is awesome!</div>
<div class="boxes" id="bubble-tea">Bubble tea is da bomb!</div>
<div class="boxes" id="milk">Milk is healthy!</div>
<p>
	I change my mind:
	<ul>
		<li><a href="javascript:showDiv('coke')">Coke</a></li>
		<li><a href="javascript:showDiv('bubble-tea')">Bubble Tea</a></li>
		<li><a href="javascript:showDiv('milk')">Milk</a></li>
	</ul>
</p>
<a href="/demo/demo.html">Back to main page</a>

We begin with the divs, each with their respective ids (coke, bubble-tea, milk). We then re-list our options on this page as well. The links here do not link to another page though. Instead, they call the showDiv() function and pass over the selected option.

If you found that my code was helpful in any way, shape, or form and would like to buy me a beer, please use the Donate button below =) Cheers! OR…you can sign up for a free Dropbox account using my referral link =) If you are not aware of what Dropbox is, it is the most awesomest online backup application there and so much more…all for free.





How to dynamically remove elements from the DOM via jQuery


jQuery is an awesome JavaScript library that can do some very heavy lifting in very small amounts of code. Take the example below where we are simply removing a div element from the DOM.

Demo
Remove me by clicking the button below.


Continue reading

JavaScript Date Ranges/Calculations with Datejs



If there is anything I hate more than the smell of durian, it is having to deal with date range calculations in JavaScript. Luckily though, we have the Datejs JavaScript Date Library to prevent us from having to pull our hair out.

Mission

I was recently faced with having to implement a date range drop-down menu very similar to of the one that is beautifully implemented in Google Adwords:

Google Adwords Date Range Pull-Down Menu

The select input element had to return 3 pieces of information: The name of the option, start date, and end date of the selected option.

Here are the specific options that I had to implement for the date ranges:

  • This month to date
  • This quarter to date
  • Last 7 days
  • Last 30 days
  • Last 365 days
  • Last week (Mon to Sun)
  • Last full month
  • Last full quarter
  • Last full year

The Plan

Continue reading

How to hide, show, or toggle your div with jQuery


Hiding and showing content is MUCH easier with the magic of jQuery. Here is a simple demo of the jQuery .toggle() function.

Demo

Toggle Button

The content in this div will hide and show (toggle) when the toggle is pressed.

Here is the JavaScript needed to run this demo:

1
2
3
4
5
6
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script>
<script type="text/javascript">
function toggleDiv(divId) {
   $("#"+divId).toggle();
}
</script>

Continue reading

Parsing XML data from hostip.info API service with PHP

If you ended up here, then you most likely experienced what I did in trying to figure out how to parse the XML data from the hostip.info web API service.

Basically, it is down to the namespaces that are not accessible by normal means.

Here is the basic XML response from a typical hostip.info call such as http://api.hostip.info/?ip=[IP-ADDRESS]

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
< ?xml version="1.0" encoding="ISO-8859-1" ?>
<hostiplookupresultset version="1.0.1" xmlns:gml="http://www.opengis.net/gml" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="http://www.hostip.info/api/hostip-1.0.1.xsd">
   <gml:description>This is the Hostip Lookup Service</gml:description>
   <gml:name>hostip</gml:name>
   <gml:boundedby>
      <gml:null>inapplicable</gml:null>
   </gml:boundedby>
   <gml:featuremember>
      <hostip>
         <ip>12.215.42.19</ip>
         <gml:name>Sugar Grove, IL</gml:name>
         <countryname>UNITED STATES</countryname>
         <countryabbrev>US</countryabbrev>
         <!-- Co-ordinates are available as lng,lat -->
         <iplocation>
            <gml:pointproperty>
               <gml:point srsName="http://www.opengis.net/gml/srs/epsg.xml#4326">
                  <gml:coordinates>-88.4588,41.7696</gml:coordinates>
               </gml:point>
            </gml:pointproperty>
         </iplocation>
      </hostip>
   </gml:featuremember>
</hostiplookupresultset>

Continue reading

Groupon – Commission Junction (CJ) WordPress Widget Plugin that Displays Local Deals

I have developed a Groupon -Commission Junction (CJ) WordPress Widget Plugin that automatically displays the local deals for the visitor. It allows you to plugin your Commission Junction (CJ) PID account number and display the local links according to the visitor IP address. The demo of this widget is currently running on this site in the upper right-hand corner.
Continue reading

Sorting 2D associative arrays in PHP

Surprisingly, it took me a long time to find this solution so I decided to post it for anyone who had a situation similar to mine.

Let’s say you have the following 2D associative array in PHP of fruits and their corresponding prices and you want to have them sorted by price:

$fruits = array
(
    [0] => array
        (
            ['product'] => 'banana',
            ['price']     => 2.99
        ),
    [1] => array
        (
            ['product'] => 'apple',
            ['price']     => 1.99
        ),
    [2] => array
        (
            ['product'] => 'durian',  //these smell by the way - i do not know how people can like them =)
            ['price']     => 19.99
        ),
    [3] => array
        (
            ['product'] => 'starfruit', //not too stinky but still stinky nonetheless
            ['price']     => 5.99
        )
);

Continue reading

Dynamic or on-the-fly percentage calculations with JavaScript


Here is a simple JavaScript function that does dynamic or on-the-fly percentage calculations.

Demo




You have saved 50 %

Continue reading

The dangers of embedding the notorious “void(0)” JavaScript code in the href attribute of the “a” tag

I recent ran into an interesting IE bug involving the following bit of html code:

<a href="javascript: void(0);" onclick="dosomething();">click me</a>

I honestly did not write this one but I will leave names out of this to protect the innocent =)

The void(0) JavaScript code is usually used to prevent loading or reloading of the page when the user clicks the link.

What we were trying to do here was have the dosomething JavaScript function execute when a user clicks on the link. This works fine in FireFox, Chrome, Safari but not IE. When a user clicks on the link in IE, nothing happens: i.e. (no pun intended) the JavaScript does not execute.

It took us a good amount of time to realize what the issue was with IE. It turns out that the void(0) function was preventing the onclick event to fire.

Although it may not be pretty, this is what we ended up doing and it appears to be cross-browser friendly:

<a href="<?=$_SERVER['PHP_SELF'];>#" onclick="dosomething(); return false;">click me</a>

Update: Here is an updated version of the code that accounts for users with JavaScript disabled:

<a href="[alternative link]" onclick="dosomething(); return false;">click me</a>

Thanks Ulrich for the suggestion! In this version, if a user has JavaScript disabled, a click on this link will take them to the [alternative link]. If JavaScript is enabled, then dosomething() will execute and the return false will prevent the browser from going to the [alternative link].

Anyway, I hope this helps someone out there in the universe.

How to randomly order or select rows in a MySQL query

I was looking for a way to order the rows randomly in a MySQL query and the solution was not easy for me to come by. I am posting the solution here in hopes of helping others.

1
2
3
SELECT * 
FROM my_table
ORDER BY RAND()

RAND() returns a random floating-point value but functions to randomly order the selection of rows in the above usage.

If you combine the query with LIMIT, you will end up with a random selection of rows from your table.

1
2
3
4
SELECT * 
FROM my_table
ORDER BY RAND()
LIMIT 3

Assuming you have more than 3 rows in your table, you will always get 3 random rows from the query.

How to convert MySQL timestamp to PHP date type

Let’s say you have the following PHP code that extracts the date from the times table in your MySQL database. The date is of timestamp type which has the following format: ‘YYYY-MM-DD HH:MM:SS’ or ‘2008-10-05 21:34:02.’

1
2
3
4
$res = mysql_query("SELECT date FROM times;");
while ( $row = mysql_fetch_array($res) ) {
   echo $row['date'] . "<br />";
}

Continue reading

How to count values with MySQL queries

Let’s say you have the following table called votes that keeps track of how people voted and you want a query to count the number of votes for you instead of having to loop through all the rows with a counter in PHP.

person vote
obama yes
mccain no
obama yes
obama no
mccain yes
obama yes
obama yes
obama no
mccain no

Continue reading

How to confirm or prompt user for input via JavaScript


JavaScript has a built-in function called confirm which takes a string argument that poses the question to the user and gives them the option to click the OK or Cancel buttons and returns true if the user clicks OK.

Demo
green box

yellow box


Continue reading

How to find and access parent nodes via JavaScript


Have you ever had to access a parent node from a given child node? In this example, we are going to traverse up the DOM tree starting from the button to look for the parent node with the name attribute itsMe.

Demo
My name is notMe

My name is itsMe

My name is notMeEither

My name is tryAgain

My name is sorryNotMe

My name is nopeSorry

Continue reading

How to loop through checkboxes or radio button groups via JavaScript


Do you have a form with checkboxes or radio buttons that you would like to loop through via JavaScript? This JavaScript function will do just that!

Demo
I like to program in:

PHP

Perl

Ruby

ASP


I like to eat:

Snickers

Hershey's

M&M's

Nerds


I like to drink:

Coke

Gatorade

Pepsi

Milk


Continue reading

How to create your own customized calculator via JavaScript

This is a simple example of implementing a calculator with JavaScript and HTML. This calculator will only have the division, multiplication, addition, and subtraction operators but you can easily tack on more functions if needed.

Demo

Continue reading

How to dynamically add content to a div and store the content to a cookie via JavaScript


This is an example of adding dynamic content via JavaScript by allowing the user type in the actual content.

Demo
Content to be added:


Your content will be added dynamically below:

Continue reading

How to validate email format via JavaScript


This JavaScript demo verifies that an email address is in the correct format and that the user has typed in the same address in both fields to prevent mistyping of the address. I have borrowed the regex for verifying the correct email format from a different site.

Demo
Email:

Please type in your email again:

Continue reading

How to dynamically remove/delete elements via JavaScript


This post is in response to one of the comments on have received regarding the removal of elements via JavaScript. I have taken the original function posted and edited it a little bit for the demo.

Demo
I am the parent div.

I am a child div within the parent div.

 


Continue reading

How to find and replace text dynamically via JavaScript


This is a neat little script that demonstrates two things:

1) Find – If only the Find box is filled in, then the findMyText() JavaScript function will just perform a find for the div that is given. If there is a match, the text will be highlighted and marked in bold.

2) Find and Replace – If both the Find and Replace boxes are filled in, then the findMyText() JavaScript function will do just that.

Demo
Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

Find
Replacment


Continue reading

Simulate a button click via JavaScript

There is a rare need for this type of functionality but I have found myself in a couple of situations where I needed it. Here is a quick demo of a button click that is simulated from another event handler. In this case, the button click is invoked by checking a checkbox.

Demo

Check the box to simulate a button click


Continue reading

JavaScript to select all or none of the checkboxes in a form


Here is a quick demo of the select all or none JavaScript function that automatically toggles all of your checkboxes in a given form.

Demo
My favorite programming/scripting language is:

Select All | None

JavaScript

Perl

PHP

C++

Continue reading

Dynamically edit font styling of HTML content via JavaScript

The Document Object Model (DOM) allows for dynamic styling because it makes all HTML elements and attributes readily accessible using JavaScript. Here is a simple demo of how powerful this technology can be:

Demo
Hello world!







Continue reading

How to dynamically add form elements via JavaScript



Not all forms are meant to be static. Sometimes, you want to allow the users to add certain parts of the form as they need them. Here is a nice example of dynamically adding inputs to your form as users need them. In addition, an input limit has been implemented in the script and it is set to 3.

Demo
Entry 1


Continue reading

How to hide, show, or toggle your div

Are you trying to find a way to hide and show your content? The demo below shows a simple yet elegant way of toggling your content and toggling the control text via Javascript and styling.

Demo
Let’s use images! click image to expand/collapse==>

This demo uses plus and minus images for hiding and showing your div dynamically via JavaScript. This content will toggle.

We will cover how to implement this example later on in the tutorial but first let’s start with a simple example.

Demo

show < == click here

Continue reading

Dynamic Country State Javascript Menu Example


I have found myself in a couple of situations where I needed a simple dynamic javascript menu where the user would make a selection from one select list and depending on what the user selected from the first select list a second list would offer further options. Here is a perfect example:

Demo

Country:

State/Province:

Country value:

 

State/Province value:
 

Continue reading