0

Is there a way to detect clicks on the css margin of an element?

I'm working with a tagging system in a textbox a bit like this one. What I want to be able to do, is register when a user clicks between two tags, and position the cursor as such. This space is created by a margin on the tags - is there a way I can detect a click in that zone?

The space is otherwise just part of the ul element, where of course, I could detect a click, but couldn't tell where it was (could I?) so wouldn't know where to position the cursor. The only solution I can think of is to create two 3px wide empty span's to use in place of the margins, and register clicks on them instead...but obviously that's not such a neat solution. Is there a better way to do this?

Here is a jsfiddle: http://jsfiddle.net/78rhB/1/ The bit of CSS I'm looking at detecting is:

    li.token-input-token-facebook {
        margin: 3px;
}
Chris
  • 5,882
  • 2
  • 32
  • 57
  • consider to provide a jsfiddle or at least post relevant code... – A. Wolff Jun 26 '13 at 10:23
  • 1
    you might use a padding (inside the `li`) instead of a margin – Fabrizio Calderan Jun 26 '13 at 10:24
  • roasted - Sorted, although I'm not sure how much more it lends to the question over the demo I linked to. Fabrizio - the li is surrounded by a styled border, so unless I could somehow set my border not to be round then edge of the li, then I don't think that is possible. – Chris Jun 26 '13 at 10:39

2 Answers2

2

using label wrapping inputs , it should work without jQuery. http://codepen.io/anon/pen/Aviwf increased margin and bg color for demo

input {margin:0 3em;}
label {display:inline-block;background:rgba(0,0,0,0.1)}
G-Cyrillus
  • 101,410
  • 14
  • 105
  • 129
  • Thank you. Apologies for the delay, this took some serious messing around with css to get a working version, as I was using li elements inside an input, instead of input elements themselves. (And there was a stray input floating around as well.) Thanks! – Chris Jun 26 '13 at 13:32
0

You cat bind click event handler for parent ul element and look for closest for click point li

$('ul.required').on('click', function(e){

   var y = e.pageY;

   var closestLiElem = findClosest('ul.required li', y); /// this is li you need

});

var findClosest = function(selector, y) {
    var closest, closestY;

    $(selector).each(function() {    
       var elem = $(this);
       // here find minimal distanse of  y to bounds of element
       var centerY =  parseInt(elem.offset().top) + parseInt(elem.height()) / 2;
       var localY = Math.abs(centerY - y);
       if(closestY==null || (localY  < closestY)) {
            closestY = localY;
            closest = elem;
       }
    });

    return closest;
}

This code just a sample and required debug

Chris
  • 5,882
  • 2
  • 32
  • 57
YD1m
  • 5,845
  • 2
  • 19
  • 23