Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CSS Button calling a javascript function

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");}
like image 694
ColdStormy Avatar asked Dec 25 '14 15:12

ColdStormy


People also ask

Can you call a JavaScript function in CSS?

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.

How do you call a JavaScript function from a button in HTML?

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.

How do you call a script in a 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.

How do you call a function in JavaScript?

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.


2 Answers

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>
like image 91
Banana Avatar answered Sep 17 '22 13:09

Banana


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 
 }
like image 28
A.T. Avatar answered Sep 19 '22 13:09

A.T.