Search code examples
jqueryeventtrigger

jQuery mouse click event handler


I want to make some keyboard shortcuts where I want to trigger the same thing that happens when a span-box is clicked. It needs to work in IE7. How could I do this? Here's what I have so far:

HTML

<li id="detail">
  <a href="#" onClick="access(this);">
    <span>Detailed Report</span>
  </a>
</li>
<li id="product">
  <a href="#" onClick="access(this);">
    <span>Product Area Report</span>
  </a>
</li>

JQUERY

(document).keypress(function(e){
    if (!$(e.target).is('input, textarea')) {
        var code = e.which || e.keyCode;
        switch ( code ) {
            case 13: //enter
                getTable();
                return false;
            default:
                break;
        }
    }
});

Solution

  • The HTML:

    <li id="detail">
      <a href="#" class="detail-report">
        <span>Detailed Report</span>
      </a>
    </li>
    <li id="product">
      <a href="#" class="product-report">
        <span>Product Area Report</span>
      </a>
    </li>
    

    The jQuery:

      $(function(){
    
            $(".detail-report").click(function(e) {
              e.preventDefault();
              /*trigger the other thing here*/
              alert("clicked on the detail report");
              myevent(); //declare a function somewhere in the scope of your js and call it here :)
            });
    
            $(".product-report").click(function(e) {
              e.preventDefault();
              /*trigger the other thing here*/
              alert("clicked on the product report"); 
            });
        });
    

    My fiddle demo

    You can also blend in this idea with the keydown function like this...

    $(document).keydown(function(e) {
    switch(e.KeyCode) {
    //you just gotta know your key codes and what numbers they are associated to!
    case 68: //when you press the (d) key trigger something...
      alert('i used my keyboard to press the d key.')
     myevent(); //you can call that same function that you created earlier, and place it here.
    break;
      }
    });