I have inserted a large image onto my HTML page and to manage its size, I am displaying it within a div that allows for scrolling like a map. Using jQuery, I have placed 3 markers on the image.
The issue I am facing is that when I scroll the image, the markers do not move along with it. How can I resolve this?
Check out my JS Fiddle demo and view the code below:
var Markers = {
fn: {
addMarkers: function() {
var target = $('#image-wrapper');
var data = target.attr('data-captions');
var captions = $.parseJSON(data);
var coords = captions.coords;
for (var i = 0; i < coords.length; i++) {
var obj = coords[i];
var top = obj.top;
var left = obj.left;
var text = obj.text;
$('<span class="marker"/>').css({
top: top,
left: left
}).html('<span class="caption">' + text + '</span>').
appendTo(target);
}
},
showCaptions: function() {
$('span.marker').live('click', function() {
var $marker = $(this),
$caption = $('span.caption', $marker);
if ($caption.is(':hidden')) {
$caption.slideDown(300);
} else {
$caption.slideUp(300);
}
});
}
},
init: function() {
this.fn.addMarkers();
this.fn.showCaptions();
}
};
$(function() {
Markers.init();
});
#mydiv {
overflow: auto;
max-width: 800px;
max-height: 600px;
}
#image-wrapper {
width: 400px;
height: 400px;
position: relative;
margin: 2em auto;
background: #f6f6f6;
border: 2px solid #ddd;
}
#image-wrapper img {
display: block;
margin: 25px auto;
}
span.marker {
width: 20px;
height: 20px;
background: #f66;
color: #fff;
text-align: center;
position: absolute;
line-height: 20px;
cursor: pointer;
}
span.marker:before {
content: '+';
}
span.caption {
width: 180px;
background: #f66;
color: #fff;
padding: 4px;
position: absolute;
top: 20px;
left: 0;
display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<div id="image-wrapper"
data-captions='{"coords": [
{"top":180,"left":160,"text":"iMac 1"},
{"top":250,"left":300,"text":"iMac 2"},
{"top":250,"left":360,"text":"iMac 2"}
]}'>
<div id='mydiv'>
<img src="https://cdn.vectorstock.com/i/1000x1000/96/84/top-view-city-map-abstract-town-flat-design-vector-11299684.jpg" alt="" />
</div>
</div>
How do I modify my JS Fiddle to ensure that the pins on the image remain sticky in their designated locations even when scrolling?