First let's try to understand why planets migrate inwards. Planets are formed in a protoplanetary disk; a huge disk of gas and dust that accretes on to a newly forming star at the centre. Gravitational interactions between the planets and the gas in the disk play a very important role in planetary formation and evolution.
As planets orbits within the disk, they generate 'spiral density waves'. These are simply changes to the density of the gas in the region local to the planet, which move at a different speed compared to the rest of the material in the disk. The consequence is that the wave exterior to the planet exerts a negative torque and acts to slow the planet down. The wave interior to the planet exerts a positive torque and speeds it up. The net effect is that the negative torque wins, which causes the planet to lose angular momentum and migrate towards the star. On the timescales of planetary formation this is a relatively fast process, and typically affects lower mass planets.
When you have a planet as large as Jupiter, something else happens. The torques that the planet exerts on the disk are so strong that the repel the gas away from its orbital region entirely, opening up a 'gap' in the disk. The planet now migrates inwards following the natural evolution of the disk ie. the timescale that gas naturally migrates and accretes on to the star. The planet and the gap migrate inwards together as one. This is a much slower than the process than the one described for smaller planets, hence why Saturn was able to catch up with Jupiter.
So, why did Jupiter migrate outwards?
When Jupiter and Saturn became locked in an orbital resonance, they formed a common gap in the disk. Saturn essentially cleared the region exterior to Jupiter, reducing the torque exerted on Jupiter by the outer part of the disk. But the gas repelled away by Jupiter in the inner region became piled up at the inner edge of the disk, increasing in density and enhancing its own torques back on Jupiter. The net effect is now that the positive torques from the inner disk overcome the negative torques from the outer disk, and the planets migrate outwards.
For this to work, you need quite a specific scenario. Modelling suggests that outward migration can only occur when the inner planet is 2-4x larger that the outer planet. For further reading I would highly suggest this recent review by Raymond & Morbidelli (2020), which gives an excellent description of our best current models of the formation of the Solar System.