0

I am wondering if I could have a function that is triggered by either clicking on a div or pressing space bar. I can't ever remember seeing a function like this... is there a way to do it?

$('.button').click || keypress.keyCode === 32 (function() { 
    //do something
)};
Jeff
  • 1,018
  • 1
  • 15
  • 33

4 Answers4

1

Like this:

$(function(){
    $('#div').on('keypress click', function(e){
    if (e.which === 32 || e.type === 'click') {

    }
  });
 });

Trigger an event on `click` and `enter`

1

You can directly invoke the function by using the event "onclick" on div.

<div onclick='invokeAFuntion' id='div-element'></div>

If you want to trigger the function when the space is pressed anywhere on the screen then use the document element as the selector, otherwise change the selector as per the element.

$(document).on('keypress',function(e) {
    if(e.which == 32) {
        alert('You pressed enter!');
    }
});

function invokeAFuntion(){
 alert('You have invoked the function!');
}
Helper
  • 776
  • 7
  • 17
1

You can try this also check here live demo Click here.

Note: you can handle globally any click event and keypress event

$(document).ready(function(){
  $(document).on('keypress click','button,input,textarea', function(e){
    if (e.which === 32 || (e.type === 'click' && e.currentTarget.localName =="button")) {
     console.log("which "+ e.which);
      console.log("Type "+ e.type);
      $("#result").html(" which "+ e.which + " Type "+ e.type);
      console.log($(this));
      console.log(e);
      console.log(e.currentTarget.localName);
    }
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="form-group col-4" style="margin-bottom: 20px;">
 
  <input type="text"><br/>
  <button type="button">
  Click
  </button>
  <br/>
  <span id="result"></span>
</div>

Please check updated fiddle link also Click here

jishan siddique
  • 1,848
  • 2
  • 12
  • 23
  • My goal is to have it so click only enacts the function if button is clicked. Right now if I click anywhere on page it enacts the functions. Space bar works... but click should only work if $(.button) is clicked not entire document. Thanks! – Jeff Oct 23 '19 at 14:24
  • Sure I'll do just changes `On` in documents selectior – jishan siddique Oct 23 '19 at 14:41
1

I was able to achieve the goal by creating two separate events / functions but have the functions do the same thing.

// If Button is Clicked
$('.button').click(function() { 
//do something
});

// If space bar is pressed
$(window).keypress(function (e) {
  if (e.keyCode === 32) {
    e.preventDefault()
//do same thing as if .button is clicked)
});
Jeff
  • 1,018
  • 1
  • 15
  • 33