JQuery: How to stop the spread of Ctrl + A?

I am currently developing a map-based application (OpenStreetMap data via Leaflet.js) and markers displayed on the map.

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

Now, I would like the user to be able to select all the markers currently on the map by pressing Ctrl A. The code I use to achieve this is as follows:

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 is triggered by simultaneously pressing the keys Ctrl and A, the selection is made as desired.

My problem: Despite the fact that I added a line to stop the event from spreading, the browser (tested in Chrome and Opera) still performs the usual Ctrl + A-Selection, that is, in addition to my markers selected by my implementation of the selection on the map, entire web page selected. This is annoying: next to the map there is no text on this page that can be selected, so it makes no sense - I would disable Ctrl A while my map is displayed.

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

+7
source share
2 answers

Suppose your mistake is that you are using e.stopPropagation() , which simply stops sending further events (since your event is attached to a document - it is useless). Instead, try e.preventDefault() :

 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 great for me on this demo.

+10
source

Ah, I found a trick:

 e.preventDefault(); 

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

0
source

All Articles