harryngh
harryngh

Reputation: 1859

How to catch the deselection event in Add-on SDK in Firefox

I use the Add-on Builder & SDK to develop Firefox add-on. I catch the event when users select a piece of text by the snippet:

var selection = require("sdk/selection");
selection.on('select', function () {
//Doing something
});

However, what I want also is to do other things when users does not select that text anymore, but I can not figure it out how to do it. Anyone can help me with this? Thank you very much.

Upvotes: 0

Views: 119

Answers (1)

prasun
prasun

Reputation: 7343

I am not aware if there are events on Deselection of a text.

However, you could register for Mouse click event on body or div containing that text and then in the callback function of the event, you could check if last selected texts is currently selected or not.

 var selection = require("sdk/selection");
 var lastText;

 function addSelection(){
    var selection = false;
    var body = document.body;
    if(!selection.text){
        //deselection
        //remove DOM listeners
        body.removeListener('click', addSelection);
    }
    if (!selection.isContiguous) {
         for (var subselection in selection) {
             if(subselection.text == lastText){
                 selection = true;
             }
         }
    } else if(selection.text && selection.text == lastText){
         selection = true;
    }

    if(!selection){
        //deselected
        //remove DOM listeners
    }

 }
 selection.on('select', function () {
    var body;
    if(lastText !== selection.text){
       //deselected
       //remove listeners
    };
    lastText = selection.text;

    body = document.body;

    //add DOM listeners like click - that can potentially remove selection
    body.addEventListener('click', addSelection);
 });

Upvotes: 1

Related Questions