Guide: "Adding markers to user-uploaded images - A step-by-step tutorial"

I'm struggling to create a website that allows users to upload images and use specific tools. However, I am facing an issue where the marker I want to add is appearing all over the webpage instead of just on the image itself. How can I confine it to only the img element?

<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
  <meta charset="utf-8>
  <title></title>
</head>
<body>
  <input type="file" onchange="previewFile()"><br>
  <img id="myImg" src="" alt="Image preview...">
  <script src="https://code.jquery.com/jquery-3.1.1.min.js" integrity="sha256-hVVnYaiADRTO2PzUGmuLJr8BLUSjGIZsDYGmIJLv2b8=" crossorigin="anonymous">
  </script>
  <script>
    $(document).ready(function() {
      $(function() {
        $(":file").change(function() {
          if (this.files && this.files[0]) {
            var reader = new FileReader();
            reader.onload = imageIsLoaded;
            reader.readAsDataURL(this.files[0]);
          }
        });
      });

      function imageIsLoaded(e) {
        $('#myImg').attr('src', e.target.result);
      };
      
      $(document).click(function(ev) {
        $(".marker").remove();
        $("body").append(
          $('<div class="marker"></div>').css({
            position: 'absolute',
            top: ev.pageY + 'px',
            left: ev.pageX + 'px',
            width: '10px',
            height: '10px',
            background: '#000000'
          })
        );
      });
    });
  </script>
</body>
</html>

Answer №1

To begin, create a container for the preview image to capture the marker within the image.

<div class='img-preview'>
      <img id="myImg" src="" alt="Image preview...">
</div>

Next, apply the following CSS to the container. The container's position should be set as relative in order to contain the position: absolute element.

.img-preview{
     position: relative;
     overflow: hidden;
}

When clicking on the document, append the marker inside the container to keep it contained. Then adjust the element's top and left position by subtracting the container's top and left position. This is necessary because the position: absolute element will be positioned relative to its parent with position: relative.

$(document).click(function (ev) {
    var prevPos = $(".img-preview").position();
    $(".marker").remove();
    $(".img-preview").append(
        $('<div class="marker"></div>').css({
           position: 'absolute',
           top: (ev.pageY-prevPos.top) + 'px',
           left: (ev.pageX-prevPos.left) + 'px',
           width: '10px',
           height: '10px',
           background: '#000000'
        })
    );
});

That's all there is to it!

If you'd like to see the end result:

<!DOCTYPE html>
<html lang="en" dir="ltr">
  <head>
    <meta charset="utf-8">
    <title></title>
    <style>
    .img-preview{
         overflow: hidden;
         position: relative;
    }
    </style>
  </head>
  <body>
    <input type="file" onchange="previewFile()"><br>
    <div class='img-preview'>
      <img id="myImg" src="" alt="Image preview...">
    </div>
    <script
    src="https://code.jquery.com/jquery-3.1.1.min.js"
    integrity="sha256-hVVnYaiADRTO2PzUGmuLJr8BLUSjGIZsDYGmIJLv2b8="
    crossorigin="anonymous">
    </script>
    <script>
    $(document).ready(function(){
      $(function () {
    $(":file").change(function () {
        if (this.files && this.files[0]) {
            var reader = new FileReader();
            reader.onload = imageIsLoaded;
            reader.readAsDataURL(this.files[0]);
        }
    });
});

function imageIsLoaded(e) {
    $('#myImg').attr('src', e.target.result);
};
        $(document).click(function (ev) {
          var prevPos = $(".img-preview").position();
          $(".marker").remove();
          $(".img-preview").append(
            $('<div class="marker"></div>').css({
              position: 'absolute',
              top: (ev.pageY-prevPos.top) + 'px',
              left: (ev.pageX-prevPos.left) + 'px',
              width: '10px',
              height: '10px',
              background: '#000000'
            })
          );
        });

    });
    </script>
  </body>
</html>

Answer №2

Give this code a try

let image = "https://encrypted-tbn1.gstatic.com/images?q=tbn:ANd9GcQxFoh469eOsZQkuPOLpZn3R6yyIExkZCxOxf4ywfeY3v330EwP3Q";
let marker = new google.maps.Marker({
        position: location,
        map: globalMap,
        icon: image
});

To learn more, check out How can I modify the markers?

Answer №3

Not quite sure what you're asking, but if you want to place your "marker" only within images, you can try this approach:

Replace


$(document).click(function (ev) ....

with


    $('img' /* or '#myImg' */).click(function(ev) {
      $(".marker").remove();
      $(this).parent().append(
        $('<div>').addClass('marker').css({
          position: 'absolute',
          top: ev.pageY + 'px',
          left: ev.pageX + 'px',
          width: '10px',
          height: '10px',
          background: '#000000'
        })
      );
    });

Now the onClick listener will only respond to clicks on the image.

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

Issue encountered while trying to interpret Bootstrap 4 within Netbeans 8.2

Currently, I am working on an HTML5/JS application using Node.js in Netbeans 8.2. As I develop the welcome page, I intend to incorporate Bootstrap 4. However, when I attempt to add bootstrap.min.css to my stylesheets folder, I encounter an error as shown i ...

Anchor tags are not visible to Jquery

My issue is with integrating JQUERY and PHP. In my external PHP file, I have the following echo statement - `echo ("<a href='#' id='bb'>hello</a>"); Similarly, in my external js file, I have this JQUERY code - $(' ...

React.js - Error message: onChange is not defined

My application has successfully integrated the last.fm API to fetch related artists. The concept is simple - search for an artist and receive a list of related artists in return. While using 'onClick' works flawlessly as it retrieves the input v ...

Conceal dropdown options when there is no text entered

To achieve the functionality of hiding dropdown values when there is no text in the search bar, you can use the following code snippet. The code provided below works perfectly for single selection. However, if you allow multiple value selections, it automa ...

How to utilize hbs variable in an external JavaScript file

Currently, I am utilizing hbs (express handlebars) to display a page. I am interested in retrieving some variables from chat.hbs and accessing them in an external file named chat.js on the client side. Server Side res.render('chat', {chatr ...

Is it feasible to incorporate the CSS and Bootstrap (CDNs) specific to an HTML component without affecting the styling of other pages?

One way I am able to recycle the HTML component is using this code: $.get("nav.html", function(data) { $("#fulloptions").replaceWith(data) }) However, there’s a conflict because nav.html uses a different version of Bootstrap than my index file does ...

Is it possible to incorporate numerous instances of SlickGrid by utilizing an angular directive?

Just started diving into AngularJS and it's been an exciting journey so far. I've come across the suggestion of wrapping external libraries into directories, which definitely seems like a good practice. While trying to create a 'slickgrid& ...

Creating a Timetable Interface; which plugin or tool should I use for this project?

Here is a concept I am looking to develop... I am struggling with the layout using only css/js ... Is there a jquery plugin or tool that could assist with this? Would this be considered a reverse orientation calendar? Starting from scratch has proven to ...

Discovering elements with Selenium

While using selenium, I stumbled upon this web element: <td style="padding-right: 10px; " **onclick="javascript:show_me('CarDetails.php?CarID=2358912&SubCatID=1**', '2358912', 560, 'ActiveLinkVisited');stat( '../& ...

Locating a record within a database that contains an objectId field linking to a separate collection

I have defined two collections in the following manner const BookSchema = new mongoose.Schema({ title: String, author: { type: mongoose.Object.Types.ObjectId, ref: "author" } }) const BookModel = mongoose.model(" ...

PHP handling an undefined index error in AJAX/JQuery file upload for the 8th image

I found this code snippet from the following resource: Uploading Multiple Files using AJAX When trying to upload up to 7 images (each around 1MB in size), everything works smoothly. However, as soon as I attempt to upload the 8th image or select more tha ...

Use a PHP form to send an email with HTML formatting, rather than plain text

I am facing an issue with sending emails from a web form. The received email needs to be displayed as HTML and not text. function createMailBodyLine ( $title, $value ) { $value = nl2br(htmlspecialchars($value)); return "<tr> ...

Is there a way to include various reactions at once?

I've been searching everywhere for solutions but I'm stuck on this issue. Here's the scenario I'm dealing with: I need my bot to execute a command that will send an embed to a specific channel accessible only by admins. Done. Fol ...

Difficulty with Script Causing Margin Bottom to Fail

Check out my website at this link. Below is a div I have created: <div class="home" style="background-image: url(http://payload51.cargocollective.com/1/7/237315/3336908/HomeImage_o.jpg); background-attachment: fixed; height: 660px; width: 100%; opacit ...

Adjust the background color of the date and time selection tool

Trying to customize the background of a datetime picker created using jquery.pttimeselect.js. Despite linking the correct css file (jquery.pttimeselect.css), I am unable to change the background color. Any suggestions on how to successfully modify the ba ...

Transform a dynamic Maya model into JSON format for seamless integration with Three.js

After creating a Maya model in Maya 2008, I need to convert it to a JSON format for use with three.js. I have experimented with different methods including: 1) Utilizing the threeJsFileTranslator.py Maya plugin provided in the threejs package. 2) Trying ...

Issue with allowing the second floating div to occupy the remaining horizontal space inside the container div

Describing the scenario, there is a container division with two floating divisions of different widths. You can view it live by following this link (look for "Hotel booking" section): I have added a border to the second division. My goal is to make this s ...

When emitting events in Vue.js, they do not automatically bubble up to higher level parent or grandparent elements

I'm trying to dispatch a custom event that will bubble up from the grandchild element through the child element to the parent element, but for some reason it's not working. Even manually triggering the event on either the parent or child element ...

Is it possible to integrate ng-repeat with ng-model in Angular?

Is it possible to link the ng-model of a button with the ng-repeat loop? <a ng-repeat="x in [1,2,3,4]" ng-model="myButton[x]">{{myButton[x]}}</a> In the Controller: var id = 4; $scope.myButton[id] = ' :( '; I am interested in crea ...

Trouble with the jQuery sliding animation speed

One of the challenges I'm facing involves two divs: left and right. I want to slide the left div, making the right div's width 100% when the left div is hidden. This setup works well, but when I try to adjust the speed (slow or fast), it doesn&ap ...