Djokovic wasted a 5-2 lead, and a match point, in the fourth set but held on for a 6-7 (7), 6-4, 7-6 (4), 5-7, 6-4 victory on Centre Court that returned the Serbian player to the No. 1 ranking in the world.
It was Djokovic's seventh Grand Slam title and broke a streak of three consecutive losses in major finals and in five of his last six.
In the last set, Djokovic broke in the final game with the help of four mistakes by Federer to seal the win.
After the players met at the net, Djokovic went to the middle of the court, knelt down and plucked out a piece of grass and ate it, similar to what he did in 2011 when he won his first title here.
Trailing 5-4 in the fourth set, Federer double-faulted to make it 30-30. He then put a backhand into the net to set up a championship point for Djokovic.
The 32-year-old Federer then hit a serve that was ruled out, but he challenged the call and the Hawk-Eye replay showed that it hit the line for an ace -- one of his 29 in the match. Federer went on to break in the next game before forcing a fifth set.
"I was hoping that Roger was going to miss the first serve, but that didn't happen," Djokovic said. "It rarely happens. That's why he has 17 Grand Slams and he's been the most successful player ever, because in important moments, he comes up with his best shots and top game."
Djokovic said it was difficult to stay focused heading into a deciding set.
"Of course, after dropping a fourth set, it wasn't easy to regroup and compose myself and find that necessary energy to win the fifth," Djokovic said. "I don't know how I managed to do it."
Federer said it was an "amazing" match.
"You know going into a match with Novak, it's always going to be tough," Federer said. "Sometimes rough physically, because we play athletic points. I can only say congratulations today."
Djokovic had 27 unforced errors in the match while Federer had 29. Djokovic broke Federer four times while Federer converted three of his seven break points.
There had been only one service break through the first three sets before a string of three straight in the fourth as Djokovic took a 4-2 lead before holding serve again.
Djokovic returns to the top ranking for the first time since last September, taking over from
The Serbian player first rose to No. 1 when he won Wimbledon in 2011, although he was already guaranteed of securing the top ranking even before beating Nadal in that final.
Djokovic fell awkwardly in the first game of the second set and called for a trainer immediately after he broke Federer's serve to take a 2-1 lead. The trainer worked on Djokovic's left ankle.
Djokovic again called for the trainer after the third game of the final set to have his right calf worked on.
Federer led 3-0 in the first-set tiebreaker but later had three unforced backhand errors to let Djokovic back into it and had to save a set point when the Serb hit a backhand into the net.