Beginning in the 850s AD, the Abbasid caliphs of the Islamic Empire were looking for soldiers they would be able to trust, who were not other Arabs who would be trying to get into power. The Abbasids thought that the Turks would be trustworthy soldiers. So they captured a bunch of young Turks as slaves and made them become soldiers. The Turks were in fact very good soldiers. But they were so important to the Abbasids as soldiers that they were able to get more and more power for themselves. In 962 AD, the Abbasid Caliph tried to fire Alptigin, the general in charge of Khurasan (modern Afghanistan).
Mahmud's palace at Lashkari Bazar, near Bost, ca. 1000 AD
But Alptigin didn't want to be fired. He marched south and captured the fort of Ghazni from the Samanids who had been ruling it. He died the next year, but his slave soldiers took over for him and made Afghanistan into their own independent kingdom. These soldiers were known as the Ghaznavids after their fort. They took Kabul in 977. Under their great sultan Mahmud, Alptigin's grandson, they captured Herat from the Samanids in 1000, and ruled part of Persia (modern Iran) too. Then the Ghaznavids began to invade India.
Painting from the Lashkari Bazar of two palace guards
At first Sultan Mahmud's invasions of India were mainly to get gold and slaves and to destroy images, because Islam said that God didn't like any images of people, animals, or even plants or buildings. Many Hindu temples of northern India were destroyed in these raids, including a famous temple to Shiva in Gujarat. Mahmud got so much plunder that he built a beautiful palace at Ghazni. He had 2500 elephants there! In the winter, when it was too cold at Ghazni, Mahmud and his whole court would move down to Bost (with all the elephants).
But eventually Mahmud conquered the Punjab (modern Pakistan and northern India) and took it over as its ruler. Mahmud ruled for about 30 years before he died in 1030 AD. But the Ghaznavids didn't last very long after that. By 1040 they had been conquered by the Seljuks and the Ghuris.