Tiarnan Swayne
Tiarnan Swayne

Reputation: 17

Execute a function when pressing a button in jQuery

I am quite new to programming, and have met a problem.

I really want to run this function, when I press a button. Here is the function that I want to run:

function generateTip() {
    var tip = tipsList[generateNumber()];
    var tipElement = document.querySelector('.js-tip');

    tipElement.innerHTML = tip;
}

Alright, I want to run this function, when pressing a button, and here is the code for my jQuery button:

$(document).ready(function(){
    $('button').click(function() {
      //run function here 
    });
});

It doesn't have to be jQuery, I just thought that would be easier. I would be very grateful if somebody would help and explain.

Thanks in advance.

Upvotes: 1

Views: 7302

Answers (4)

Ray A
Ray A

Reputation: 1341

To execute the function generateTip() on click, put this in your button code:

<input type="button" name="any" onclick="generateTip()"/>

Upvotes: 0

clearshot66
clearshot66

Reputation: 2302

You're already there?

JQUERY Script:

<script>
    $(document).ready(function(){
      $('button').click(function() {
          generateTip();
      }); 
    });

    function generateTip() {
    var tip = tipsList[generateNumber()];
    var tipElement = document.querySelector('.js-tip');

    tipElement.innerHTML = tip;
    }
</script>

or by onclick only in the actual HTML and a script above:

<script>
function generateTip() {
var tip = tipsList[generateNumber()];
var tipElement = document.querySelector('.js-tip');

tipElement.innerHTML = tip;
</script>

Then in your HTML something like this

<input type="button" name"button" onclick="generateTip()";

Upvotes: 0

Dragomir Kolev
Dragomir Kolev

Reputation: 1108

So if you have a .js file with this code:

function generateTip() {
var tip = tipsList[generateNumber()];
var tipElement = document.querySelector('.js-tip');
tipElement.innerHTML = tip;
}

You can then attach it to an HTML element like so:

<button onclick="generateTip()"> Button </button>

Hope that helps

Upvotes: 0

bamtheboozle
bamtheboozle

Reputation: 6416

Inside your HTML, you can use the onclick event handler to call a function when the button is clicked, using vanilla javascript. Like so:

<button onclick="generateTip()">button text</button>

If you want a solution using jQuery and your current code, all you have to do is call the generateTip() function inside the $('button').click wrapper:

$(document).ready(function(){
    $('button').click(function() {
        generateTip(); 
    }); 
});

Upvotes: 1

Related Questions