Click event running multiple times

h ttp://co de repo.d em o.fi nal site.co m/ca mp us-m ap-v3

I’m trying to get the mouse coordinates relative to the .map-container element, yet the console log is running multiple times on click. Why is this?

if($('body.campus-map').length) {
    var container = $(".map-container");
    var containerWidth = container.width();
    var containerHeight = container.height();
    function getRelativeCoordinates(e,f) {
      var posXX = f.offset().left,
             posYY = f.offset().top;
      f.on("click",function() {
        console.log("X Coor: "+((e.pageX - posXX) * 100) / containerWidth + "%");
        console.log("Y Coor: "+((e.pageY - posYY) * 100) / containerHeight + "%");
      });
    }
    $(".map-container").on("mousemove",function(event) {
      getRelativeCoordinates(event,container);
    });
  }

Because every time the mouse moves, you are registering an on click event.

I think you will simply want to invoke an existing event, using trigger or maybe invoke an event once, using .one instead of .on

But I’m guessing at a possible solution as I don’t know what the intent is.

1 Like

The ideal solution is that at any point of clicking the map, the end game is to have a popup showing the position you are at (converted to percentage), which the person will then be able to use elsewhere in this.

I understand about the mousemove registering it multiple times, but shouldn’t the click only run once? Does all the mousemove’s get backlogged or something?

Thanks :slight_smile:

if($('body.campus-map').length) {
    var container = $(".map-container");
    var containerWidth = container.width();
    var containerHeight = container.height();
    function getRelativeCoordinates(e,f) {
      var posXX = f.offset().left,
             posYY = f.offset().top;
      console.log("X Coor: "+(((e.pageX - posXX) / containerWidth) * 100) + "%");
      console.log("Y Coor: "+(((e.pageY - posYY) / containerHeight) * 100) + "%");
    }
    $(".map-container").on("click",function(event) {
      getRelativeCoordinates(event,container);
    });
  }
1 Like

In addition to what @cpradio said, event.stopPropagation() probably won’t hurt either. It will stop any events from triggering on different layers.

The problem with stopPropagation would be that you have no idea which of the mousemove .on events registered is firing. It could be the very first one, thus where the mouse was 20 seconds ago, or it could be the very last one (not sure what the browsers do in that scenario or if it varies by browser or is purely controlled by jquery)…

The correct approach, was a simple single on-click event that @RyanReese figured out :slight_smile:

Ah yeah, I see what’s going on now. Nvm.

2 Likes

Fully done the functionality :slight_smile: .

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.