Genesis 38:6-10 Judah got a wife for Er, his firstborn, and her name was Tamar. But Er, Judah's firstborn, was wicked in the LORD's sight; so the LORD put him to death. Then Judah said to Onan, "Lie with your brother's wife and fulfill your duty to her as a brother-in-law to produce offspring for your brother." But Onan knew that the offspring would not be his; so whenever he lay with his brother's wife, he spilled his semen on the ground to keep from producing offspring for his brother. What he did was wicked in the LORD's sight; so he put him to death also.
So, the time had come for Er to marry and it was up to Judah to arrange that (as was custom during this time). Keep in mind that this was not the same respect that Judah gave his dad, as he did not wait for an arrangement.
See what it says here about Er, not too much: God found him wicked and killed him. WOW. How bad must he have been for our loving and patient God who is just and forgives to outright kill him? And what about Tamar having to marry such a man as this. Even so, her husband (duty, job, etc.) did not give her a child - so as we mentioned before, someone else had to step up.
Judah told his second son, Onan, that he was responsible for giving a child to Tamar for Er. Couple of things here - there were no fertilization clinics at this time - no labs, no petri dishes - for this to happen, Onan had to have sex with Tamar. As we all know, pregnancy does not always happen on the first time around either. So, that thought alone that Tamar had to marry a wicked man at a young age to begin with - and then as a widow to sleep with her brother-in-law. . . yuck!
Onan, however, was not the man he should've been either. He did not want to give his offspring to Er - he was selfish and wanted his own line. But that certainly didn't stop him from having sex now did it. From what the Bible tells us - everytime he did sleep with Tamar he removed himself before his "seed" could reach her egg. How demeaning that must have been for poor Tamar. She knew the only reason to do this was so that she could get pregnant and continue for Er's children, but that would never happen if Onan kept doing that.
Turns out God thought that was just awful too, so Onan was "put to death". Now the Bible doesn't say how either brother died - it justs says they were put to death. Perhaps a heart attack in their sleep, maybe they slipped and hit their head - or it could've been two completely different ways that they each died - However, one thing was for sure - they were both married to Tamar when they died. Judah had to notice that as well . . .