5

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");}
4
  • Easiest way is to switch to a <button> tag Commented Dec 25, 2014 at 15:27
  • I know but these buttons look ugly and don't fit to my site. Commented Dec 25, 2014 at 15:29
  • Create some button by using <button> tag then give button class to this button. You can use onclick method now. Commented Dec 25, 2014 at 15:30
  • Use Bootstrap for styling? Commented Dec 25, 2014 at 15:31

3 Answers 3

6

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>

Sign up to request clarification or add additional context in comments.

3 Comments

Weird, on snippet it works but when I copy your code on my page it doesn't work anymore?
you need to wrap this part in a block that runs after dom loads, the snippet loads fast but your page loads slower and the button is not found by javascript when the script executes
Boy am I... I've found the mistake. My external javascript file was not linked correctly. Now it works. Phew, thank you anyway! :D
2

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 
 }

Comments

1

try this

You can use jquery.

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.