Anjana Sharma
Anjana Sharma

Reputation: 4765

how to make background css url dynamic using jquery

I have a google map with numbered pins. The pins are red colored in the map. The actual addresses in the page should have greyed out markers. I am trying to use the background property to the address element "LocationName" which holds the address to attach the grey marker image background (no repeat left center). images are named greymarker1, greymarker2 etc.. so if it is the first address, greymarker1.png should be the icon infront of the address ONE. I can set the background css property using jquery but i am not sure how to make the URL dynamic.. '/Style Library/Images/design/icons/greymarker1.png') the 1 in the url should change with the counter..when counter is equals 1, it should grab greymarker1.png etc..

 $('.LocationName').each(function(index){
    var counter=index+1;
    //$(this).css('color', 'blue');
    $(this).css("background-image", "url('/Style Library/Images/design/icons/greymarker1.png')");  

 });

Upvotes: 1

Views: 3074

Answers (2)

Mickey Mouse
Mickey Mouse

Reputation: 1771

Am not sure what you are trying to accomplish here, but it seems simple enough, you can attach the counter or the class index number to the image name like this:

 var path = '/Style/Library/Images/design/icons/greymarker';
 $('.LocationName').each(function(index){
    var counter=index+1;
    //$(this).css('color', 'blue');
    $(this).css("background-image", "url(" + path + counter + '.png')");  

 });

You can add as many values to your css by creating a list of attribute and values like this

 var path = '/Style/Library/Images/design/icons/greymarker';
     $('.LocationName').each(function(index){
        var counter=index+1;
                $(this).css({'background-image': 'url(' + path + counter + '.png)', 
                             'background-attribute': 'somevalue'
       });

     });

Upvotes: 0

PiTheNumber
PiTheNumber

Reputation: 23562

$('.LocationName').each(function(index){
    $(this).css("background-image", 
       "url('/Style Library/Images/design/icons/greymarker" + index + ".png')");
});

Upvotes: 6

Related Questions