Turk Turk - 3 months ago 11
Javascript Question

Wrapping an Image Map in <div></div>

I am having some difficulty getting the .wrap and .wrapAll methods to work on my image map. I am assuming this is because map does not self close like an image or input tag.

HTML:

<img class="img_class" id="bottle_map" src="../images/bottle.jpg" usemap="#bottle_map">
<map name="bottle_map">
<area shape="rect" alt="" coords="3,6,258,31" href="1" title="Saranac Legacy IPA">
<area shape="rect" alt="" coords="279,5,336,32" href="2" title="four generations">
<area shape="rect" alt="" coords="2,37,425,64" href="2" title="four generations">
<area shape="rect" alt="" coords="1,69,386,95" href="2" title="four generations">
<area shape="rect" alt="" coords="243,121,444,142" href="3" title="Matt Brewing Company">
<area shape="rect" alt="" coords="4,143,186,163" href="3" title="Matt Brewing Company">
<area shape="rect" alt="" coords="194,144,400,163" href="4" title="Our (great) grandfather">
<area shape="rect" alt="" coords="3,163,252,187" href="4" title="Our (great) grandfather">
<area shape="rect" alt="" coords="295,166,419,185" href="5" title="it's still family">
<area shape="rect" alt="" coords="3,189,363,209" href="5" title="it's still family">
</map>


JS/jQuery:

$.fn.setupV2 = function(map) {
map_ref = "map[attribute='"+ map + "']";
img_ref = "img[usemap='\\#" + map + "']";
$(map_ref).wrapAll('<div class="mapContainer"></div>');
};


Basically I want to wrap the image and the image map into a div together so I can insert a canvas and CSS styling in. Is there a way to do this outside of injecting the HTML or having it done in the HTML to begin with?

Answer

You'd need to adjust your selectors so that jQuery grabs both the map, and the img. Something like this would work:

$.fn.setupV2 = function(map) {
  map_ref = "map[name='"+ map+"']";  
  img_ref = "img[usemap='#" + map + "']";
  $(map_ref + ', ' + img_ref).wrapAll('<div class="mapContainer"></div>');
};

JS Fiddle: https://jsfiddle.net/igor_9000/p0mLhecg/

I am having some difficulty getting the .wrap and .wrapAll methods to work on my image map. I am assuming this is because map does not self close like an image or input tag.

Not exactly. Your selector for map_ref and img_ref waren't matching any elements. You'd need to update them so they match an the elements, and include both of them in the jQuery selector.

Hope that helps!

Comments