Search code examples
javascriptjqueryhtmleventskeypress

Call js function when button is pressed


I want to call a js function when a button is pressed. After reading this and this, I did something like this in the jsFiddle. However, when I press the button, nothing happens! What am I missing?

js code:

jQuery(document).ready(function() {
    $('#ref1').keypress(function() {
        alert('Handler for .keypress() called.');
    });
});

Solution

  • You can't have keypress event on <a> element, use click

    Demo

    jQuery(document).ready(function() {
      $('#ref1').click(function() {
        alert('Handler for .click() called.');
      });
    });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.0/jquery.min.js"></script>
    <div data-role="page" id="pageone">
      <div data-role="main" class="ui-content">
        <a href="#" id="ref1" title="Refresh page if you did shit" data-role="button" data-icon="refresh" data-iconpos="notext" data-theme="b" data-inline="true" class="ui-link ui-btn ui-btn-b ui-icon-refresh ui-btn-icon-notext ui-btn-inline ui-shadow ui-corner-all"
        role="button">
          <p>Refresh page (helpful in case of mistake)</p>
        </a>
    
      </div>
    </div>