jQuery: How to stop propagation of Ctrl + A?
Asked Answered
A

2

8

I'm currently developping an application that relies on a map (OpenStreetMap data via Leaflet.js) and markers displayed on the map.

I implemented selection for the user, so he can click on markers to select them and Ctrl-click to add markers to selection. This works well.

Now I'd like for the user to be able to select all markers currently on the map by hitting CtrlA. The code I use to achieve this looks like this:

jQuery(document).keydown(function(e) {
  if (e.ctrlKey) {
    if (e.keyCode == 65 || e.keyCode == 97) { // 'A' or 'a'
      e.stopPropagation();
      // SELECT ALL MARKERS HERE...
    }
  }
});

This works as far as triggering on simultaneous Ctrl and A key presses is concerned, the selection is done as I wish.

My Problem: Even though I added the line to stop propagation of the event, the browser (tested on Chrome and Opera) still does the usual Ctrl+A-Selection, i.e. additionally to my markers getting selected by my custom selection implementation on the map, the entire web page is selected. This is annoying: beside the map there is no text on this page that can be selected, so there is really no point - I would like to disable CtrlA while my map is shown.

P.S. I tried to use the code shown in How can I disable Ctrl+A (select all) using jquery in a browser? but was not able to get it to work. Is this functionality really in the API?

Arwood answered 26/11, 2012 at 9:36 Comment(0)
P
11

Suppose your mistake is that your are using e.stopPropagation() which just stops further bubling of an event (as your event is attached to a document - it is useless). Try e.preventDefault() instead:

jQuery(document).keydown(function(e) {
  if (e.ctrlKey) {
    if (e.keyCode == 65 || e.keyCode == 97) { // 'A' or 'a'
      e.preventDefault();
      // SELECT ALL MARKERS HERE...
    }
  }
});

This works fine for me on this demo

Photojournalism answered 26/11, 2012 at 10:10 Comment(1)
Ah, we found it the very same second... :) Here you go good sir, have an accept.Arwood
A
-1

Ah, I found the trick:

e.preventDefault();

Stops the browser from performing any default actions. In the case described above this prevents the select-all event normally triggered on Ctrl+A.

Arwood answered 26/11, 2012 at 10:11 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.