Is there a way to automatically adjust the positioning of added pins on an image as I scroll through the image?

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?

Answer №1

Is this what you intended to do? You need to place the overflow: auto; in a different location if this is your desired outcome.

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 {
    max-width: 800px;
    max-height: 600px;
}


#image-wrapper {
    overflow: auto;
    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" 
<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>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The checkbox appears unchecked, yet the content normally associated with a checked checkbox is still visible

As the title suggests, I am encountering an issue with my code. Here is the snippet: $('#somediv').change(function() { if(this.checked) { $('.leaflet-marker-pane').show(1); } else { $('.leaflet-marker-p ...

Prevent the need to go through the keycloak callback process each time the page is

I have integrated keycloak as an identity provider into my React application. I successfully added the keycloak react dependency via npm. Below are the versions of the keycloak react npm modules on which my application depends : "@react-keycloak/web ...

obtaining Json format from an array: a comprehensive guide

Hey there, I am looking to convert my array into JSON format. Currently, my array structure looks like this: Array[0] abc: Array[1] 0: "English" length: 1 abc1: Array[2] 0: "English" 1: "Urdu" length: 2 Here is the structure that I want in JSON using Jav ...

What is the process for adding a download link to my canvas once I have updated the image?

Is it possible to create a download link for an image that rotates when clicked, and then allows the user to download the updated image? Any help would be appreciated.////////////////////////////////////////////////////////////////////// <!DOCTYPE ht ...

Using the DatePicker component with non-escaped Latin alphabet characters in date-fns for ReactJS

While attempting to integrate the DatePicker component from Material UI into my React project, I encountered an error. Although many attributed the issue to a version discrepancy, what ultimately resolved the problem for me was assigning a value to the Da ...

Creating a Fixed Footer with CSS

Another question on the same topic, with a twist. Despite trying various solutions found in countless articles, none seem to work for me. My familiarity with HTML/CSS is limited due to just a few months of off-and-on practice. Hence, I'm seeking help ...

the label remains grounded even as the browser autocompletes passwords with the password manager

https://i.stack.imgur.com/vJMyg.png I noticed that the password label on my login form does not float when the browser's password manager auto-completes. Can someone help me fix this issue? Attached is an image for reference. /* login form ...

Custom virtual properties can be set in Mongoose by utilizing the return value in a callback function

I've been searching all over for a solution to my issue, but I can't seem to find the right answer. I'm currently using MongooseJS as my ODM and I'm attempting to create virtual getters that can retrieve, process, and display informatio ...

Create an interactive visualization using d3.js

Currently, I am on the hunt for a technology that can help me render a tree structure based on Json data. After researching options like graphViz and d3, it seems like d3 is more optimized for modern browsers. With the extracted Json data, my goal is to c ...

What are the steps to creating a webpage with scrolling in HTML?

Essentially, I have a question that may sound similar to others, but please hear me out. What I am looking for is the ability to have one photo fixed in place while being able to scroll within it. To provide a better understanding, here is an example: www. ...

Tips for activating an HTML input field using Javascript

I am currently using localStorage to store a string input by the user as a title, which will be saved for future visits. I would like to implement a button that allows the user to delete the displayed text (from localstorage) and enables the input field fo ...

I need help determining the starting date and ending date of the week based on a given date

I am looking to determine the starting date (Monday) and ending date of a specified date using Javascript. For instance, if my date is 2015-11-20, then the starting date would be 2015-11-16 and the ending date would be 2015-11-21. ...

Using Selenium to interact with drop-down lists using div tags instead of select tags

As a newcomer to automated testing using Selenium Web Driver, I am struggling to test drop down lists for the location type without relying on the select command. The element in question is enclosed within a div tag. I attempted sending keys but that meth ...

Implementing Laravel's functionality for calculating average ratings with the help of jQuery

In my database, I have two tables named Users and ratings. The Users can give ratings to consultants, and the Ratings table structure is as follows: User_id | consultant_id | rating --------------------------------- 1 1 2 ...

Find the HTML elements within an XDocument that need to be replaced and converted into Json format

XML contains HTML tags that need to be removed using XDocument. Is there a way to identify nodes with HTML tags and replace them throughout the entire document? Below is a sample of the XML structure: <?xml version="1.0" encoding="utf-8"?> <myFie ...

What could be the reason for Python requests giving me a different text output compared to when I manually visit the website?

I'm in the process of creating a basic 'stock-checker' for a T-shirt that I have my eye on. The link to the product is available here: https://i.stack.imgur.com/usSJN.jpg Upon visiting the page, I noticed that it displays 'Coming Soon ...

How can we monitor the value of $route.params.someKey in Nuxt.js?

When working with Nuxt.js, I am trying to keep track of the value associated with a key called key1 in the $route.params. The values for key1 are determined using a function called someFunction(). Is there a way for me to monitor $route.params.key1 as a ...

Need assistance with jQuery AJAX?

Hey there, I'm a new member and I've gone through the different Ajax Help topics but still can't figure out why my code isn't working. Here's what I have: $(document).ready(function(){ $.ajax({ type: "GET", ur ...

Adding images to HTML using JavaScript below existing images

I'm currently working on a JavaScript game and I want to implement a feature where my character can move under blocks (isometric PNG images) instead of just sliding through them. Is there a way to dynamically adjust my character's position in the ...

How can jQuery incorporate additional selection criteria for a parent element?

How can I apply a specific criteria to a node that has been selected using jQuery? let objDIV = $("#selindividual").parent(); After retrieving the DIV, I want to target the following: button:contains(\"Submit\") If I had to do this in ...