Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery: How to stop propagation of Ctrl + A?

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?

like image 528
fgysin Avatar asked Nov 26 '12 09:11

fgysin


1 Answers

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

like image 179
Viktor S. Avatar answered Sep 24 '22 21:09

Viktor S.