sydcanem / bootstrap-contextmenu

Context menu plugin for Twitter's Bootstrap framework
http://sydcanem.com/bootstrap-contextmenu/
645 stars 193 forks source link

Getting the original element when using the declarative/HTML API #73

Closed multimeric closed 9 years ago

multimeric commented 9 years ago

I know this has been asked before (e.g. #8, #14) but both of them have a link to a gist that doesn't exist any more, so I'll ask this again.

Assuming I have markup like this:

<table>
     <tr>
         <td data-toggle="context" data-target="#context-menu">Delete</td>
         <td data-toggle="context" data-target="#context-menu">Rename</td>
         <td data-toggle="context" data-target="#context-menu">Copy</td>
     </tr>
</table>

<div id="context-menu">
    <ul class="dropdown-menu" role="menu">
        <li><a tabindex="-1" href="#" onclick="eventHandler('Action1')">Action1</a></li>
        <li><a tabindex="-1" href="#" onclick="eventHandler('Action2')">Action2</a></li>
    </ul>
</div>
function eventHandler(action){
   alert(action + ": How do I get the original <td>"?");
}

How do I get the original <td> element that was right-clicked without using $().contextmenu();?

sydcanem commented 9 years ago

The way I see your use case, you can use onItem callback. The first parameter you get is the element that was right-clicked.

'onItem' : eventHandler

function eventHandler ( td, event ) {
     alert( $( td ).text );
}
multimeric commented 9 years ago

Right, but the onItem callback is only accessible if you show the context menu using JavaScript (i.e. $().contextmenu()). Notice that I haven't used that in my code because I want the context menu to work declaratively.

sydcanem commented 9 years ago

I see. I guess you can use events on the menu. I just pushed an update to add the current right-clicked element in the event you get on 'show.bs.context' and 'shown.bs.context' events.

$('#context-menu').on('show.bs.context', function (e) {
   // the currently right-clicked <td> element
   var td = $(e.target);
})
multimeric commented 9 years ago

This is looking promising... but if e.target is the original element I clicked on, how do I get the context menu item that was selected (the <li>)?

sydcanem commented 9 years ago

I guess it's much better to use the plugin manually. See fiddle http://jsfiddle.net/e3Y9u/33/.