I have created a button with CSS like this:
<div class="button">Click me!</div>
Now I don't know how I can execute a javascript function when this button is clicked?! onClick like for HTML buttons doesn't work here.
Can you please help me? Thank you!
EDIT: This is what I have basically:
The HTML
<span class="button" onClick="farmArbeiter()" style="margin-left: 25%;">Kaufe Arbeiter</span>
Neither onClick nor onclick do work. The javascript
function farmArbeiter() { alert("it works");}
No, you can't trigger JavaScript from CSS directly. What you can do is use CSS selectors to find the elements you want to watch in this way, and then watch for mouse events.
To invoke this function in the html document, we have to create a simple button and using the onclick event attribute (which is an event handler) along with it, we can call the function by clicking on the button.
To call a JavaScript function from a button click, you need to add an event handler and listen for the click event from your <button> element. You can the id attribute to the <button> so that you can fetch it using the document. getElementById() method.
The call() method is a predefined JavaScript method. It can be used to invoke (call) a method with an owner object as an argument (parameter). With call() , an object can use a method belonging to another object.
attach a click event handler to it using javascript:
document.getElementById("BT1").addEventListener("click", function(){
alert("oh snap, i was clicked...");
});
<div class="button" id="BT1">Click me!</div>
there are several ways using jquery..
$(document).on('click','.button',function(e){ //your code });
$('.button').on('click',function(e){ //your code });
$('.button')[0].onclick = MyFunction;
function Myfunction()
{
//your code...
}
with javascript you can:
document.getElementsByClassName('button')[0].onclick = function(event){
//your code
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With