March 20, 2012

Change the background image "on click" with jQuery

Question by wpdesign

I´m new to jQuery and I´m intressred in showing different background image
on click event. Is there any easy way?

Answer by Starx

Its as simple as this

$("#mylink").click(function() { 
           // ^ Attach a function on click event of an element with id="mylink"
  //Change the css of a element with id="myDiv"
  $("#myDiv").css("backgroundImage", "url(newimage.jpg)");
               // Note ^: In jQuery, the parameters with "-" as define that way
               // But of course .css() supports "-" also, but make a habit of doing in camel-case
});

Demo

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!