The hanky code is a signaling system used by gay men and members of the fetish and BDSM communities to indicate sexual preference (top or bottom, type of sex they are after). The hanky code is also known as the bandana code or flagging. Signals in the hanky code are conveyed by wearing a handkerchief of a specific color or pattern in either the right or left back pocket, conveying preference to anyone in the vicinity who is familiar with the concept of the hanky code. Hanky code was widely used in the 1970s as a gay code, however nowadays it is also used by many bisexual, pansexual, and queer people.
There are a number of advantages to the hanky code which explains how it endures to this day. In the 1970s, when the gay community was less outspoken, the hanky code allowed gay men to communicate with each other without attracting attention and allowed men to more easily scope out potential dates. In communities where the hanky code was prevalent, men knew that pursuing men who weren't flagging could be risky.
The hanky code allowed men to seek out partners on the basis of preference by checking their back pockets. This code turned out to be handy in crowded environments like gay bars, where the noise and crowd could make it hard to establish a connection with someone. As the hanky code spread in the gay community, it began to be picked up more generally in the fetish and BDSM communities. This began a complex permutations of colors, patterns and placements.
There is no universally understood color code, and regional codes vary widely. There is general agreement upon the colors for more common practices, particularly those with an intuitive relation between the color and the practice, such as yellow for urolagnia; brown for coprophilia; and black for SM, but no absolute consensus for more common practices.
As a general rule, someone who flags in the left pocket indicates that he or she is a top, while someone who flags in the right pocket is a bottom. Bottoms prefer to participate as recipients in sexual and fetish encounters, while tops prefer just the opposite.
Knowing about the hanky code can be useful if you are traveling to an area with a large queer or fetish-oriented population, as you might mistakenly send out a signal if you leave a handkerchief in your back pocket. However, many people rely on other social cues beyond the hanky code; if you happen to have for example, a gray handkerchief in your right pocket while innocently riding the subway, you are unlikely to be ravaged by eager bondage tops, although someone might approach with a courteous introduction.
For specific handkerchief colors and their meanings, check out the list on Wikipedia.