Reputation: 317
How do I run this function If I click on the button?
<button id="button">Button</button>
var tween = new TWEEN.Tween(mesh.scale).to({ x: 1, y: 0.05, z:2 }, 1000).start();
tween.easing(TWEEN.Easing.Elastic.InOut);
tween.repeat(Infinity);
tween.yoyo(true);
Upvotes: 3
Views: 1944
Reputation: 17487
The onclick attribute on a button will accept a JavaScript function to call whenever it is clicked, like so:
<button id="button" type="button" onclick="functionToCall">Button</button>
<script>
function functionToCall() {
// ...
}
</script>
However, it is often better to attach an eventListener to the button, like so:
<button id="button" type="button">Button</button>
<script>
// Plain JS
document.getElementById('button').addEventListener('click', function() {
// ...
});
// jQuery
$('#button').click(function() {
// ...
});
</script>
Using the onclick attribute will overwrite any previously attached listeners, and in modern applications it is common to see multiple event handlers associated with an DOM node.
Using addEventListener will ensure that the previously attached handlers remain in tact and can executed at the same time.
There is also a removeEventListener method that can be used to stop execution of a function when an event is triggered if you ever need to do something only once. In those instances, it is common to use a named function instead of an anonymous function like the one in my previous example.
document.getElementById("button").addEventListener("click", clickHandlerOnce);
function clickHandlerOnce() {
// ...
this.removeListener("click", clickHandlerOnce);
}
Upvotes: 3
Reputation: 742
The problem here is that you want to be able to run your JavaScript code when you click the button. The solution to this is to create a function, then set the 'onclick' property of the button to the name of your function. Like this:
<button id="button" onclick="functionName()">Button</button>
<script>
function functionName ()
{
var tween = new TWEEN.Tween(mesh.scale).to({ x: 1, y: 0.05, z:2 }, 1000).start();
tween.easing(TWEEN.Easing.Elastic.InOut);
tween.repeat(Infinity);
tween.yoyo(true);
}
</script>
Upvotes: 3
Reputation: 5199
Using jQuery:
$('#button').click(function(){
var tween = new TWEEN.Tween(mesh.scale).to({ x: 1, y: 0.05, z:2 }, 1000).start();
tween.easing(TWEEN.Easing.Elastic.InOut);
tween.repeat(Infinity);
tween.yoyo(true);
return false; //if you want the button to not process anything further
});
Upvotes: 2