Gen 38:10 And the thing which he did displeased the LORD: wherefore he slew him also.
Q - Why did God kill Onan Judah's son. A - Because it was Onan's responsibility to marry his brother's widow so she would not be childless. (Deu 25:5) "If brothers dwell together, and one of them dies and has no son, the wife of the dead man shall not be married outside the family to a stranger. Her husband's brother shall go in to her and take her as his wife and perform the duty of a husband's brother to her. (Deu 25:6) And the first son whom she bears shall succeed to the name of his dead brother, that his name may not be blotted out of Israel.