I'm trying to replace this set of if statements as an each statement. but I'm a little confused on how to do this. I just want to cycle through a series of images that have the class .hotspots and change source, after detecting whether they have one of 4 other classes as well.

$('.hotspots').each(function(i, obj) {
        // I want something like this, but not sure how...
        });

// but I currently have...  
   if ($(".hotspots").hasClass('restaurant')) {
              var active_hotspot = 'images/icon_restaurant.png';
   } else if ( $(".hotspots").hasClass('shopping') ) {
            var active_hotspot = 'images/icon_shopping.png';
   } else if ( $(".hotspots").hasClass('convenience') ) {
            var active_hotspot = 'images/icon_convenience.png';
   } else if ( $(".hotspots").hasClass('landmark') ) {
            var active_hotspot = 'images/icon_landmark.png';
   };

$(this).attr('src',active_hotspot);

and the relevant divs look like this:

<div style="height:0px;overflow:visible;">   <img id="hotspot_1" class="hotspots shopping" src="images/icon_shopping.png">    </div>
                     <div style="height:0px;overflow:visible;">  <img id="hotspot_2" class="hotspots restaurant" src="images/icon_restaurant.png">    </div>
                     <div style="height:0px;overflow:visible;"> <img id="hotspot_3" class="hotspots landmark" src="images/icon_landmark.png"> </div>
                     <div style="height:0px;overflow:visible;">  <img id="hotspot_4" class="hotspots restaurant" src="images/icon_restaurant.png">    </div>
                     <div style="height:0px;overflow:visible;"> <img id="hotspot_5" class="hotspots restaurant" src="images/icon_restaurant.png"> </div>
                     <div style="height:0px;overflow:visible;"> <img id="hotspot_6" class="hotspots shopping" src="images/icon_shopping.png"> </div>
                     <!-- and so on -->

Recommended Answers

All 3 Replies

Completely untested, but you might be after something like this:

$('.hotspots').each(function(i, obj) {
    var className = $(this).attr('class').split(' ').slice(-1);
    var active_hotspot = 'images/icon_' + className + '.png';
});

This code assumes (as you've written), that the class you're identifying is last in the class list - i.e. comes after "hotspots".

This code assumes (as you've written), that the class you're identifying is last in the class list

Be careful with such an assumption. As soon as you add/have code changing classes, this may no longer be valid and can lead to strange results.

You're right @priteas, but the question is a little vague.

The code I offered is a guide - something to illustrate the basic functionality of each(), rather than focussing on the class retrieval method.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.