ColdStormy
ColdStormy

Reputation: 572

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");}

Upvotes: 5

Views: 9291

Answers (3)

Banana
Banana

Reputation: 7463

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>

Upvotes: 6

A.T.
A.T.

Reputation: 26312

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 
 }

Upvotes: 2

Muhammed Shuhaib
Muhammed Shuhaib

Reputation: 314

try this

You can use jquery.

$('.button').click(function(){ -- code --});

Upvotes: 1

Related Questions