"Go in unto thy brother's wife," Er's father Judah dutifully tells his second son Onan, "and marry her, and raise up seed to thy brother."
Onan doesn't like the idea that any child he gives Er's widow Tamar will not be his own. So he tries to get around his obligation: when Onan, we are told, "went in unto his brother's wife, he spilled (the semen) on the ground."
These boys of Judah really try the Lord's patience: Yahweh now slays Onan too. Historically some have tried to see this as a condemnation of masturbation, with Onan's sin even named after him. But onanism in the sense of masturbation for self-gratification is not what is involved here. (No such act is mentioned in the Bible, unless one so interprets Ezek. 16:17, in which the harlot Jerusalem made for herself "images of men, and didst commit whoredom with them," or, as suggested by Gerald Larue, Matt. 5:30, "If thy right hand offend thee, cut it off.") Whether Onan masturbates or, more in context, performs coitus interruptus, his intent is to avoid impregnating Tamar "lest that he should give seed to his brother." Onan's sin is thus one of omission, specifically non-fulfillment of the levirate law.
Er still has one brother left, but Judah has to wonder if trying to impregnate Tamar is worth risking a third son's life. For Tamar's own answer to the problem, see JUDAH AND TAMAR. (Genesis 38)
Judah Solicits Tamar
Pitts Theological Library