-3

I wrote this code:

<div onclick="f()"></div>

But this code doesn't work on some systems, I think "onclick" may work with other tags properly, Is there anybody have same experience with this problem?

BenMorel
  • 34,448
  • 50
  • 182
  • 322
Kourosh
  • 917
  • 1
  • 11
  • 24
  • 2
    did you write function `f()` anywhere? – Aman Arora Jan 16 '14 at 06:40
  • possible duplicate of [jQuery.click() vs onClick](http://stackoverflow.com/questions/12627443/jquery-click-vs-onclick) – Sujit Agarwal Jan 16 '14 at 06:40
  • 5
    doesn;t work on which systems? – gaurav5430 Jan 16 '14 at 06:40
  • . This is how it is done. But whats is your problem? which are the tags in which on click is not working. Share info. – Vinayak Pingale Jan 16 '14 at 06:41
  • do elaborate your problem – VijayB Jan 16 '14 at 06:42
  • In the old days, `onclick` only worked on links (i.e., anchor elements `a`), and only on links with an `href` specified. It's been a long time since those days, so now you can safely use `onclick` on almost any displayed element not containing another HTML resource (because the HTML displayed in that resource would be given its own click handling abilities). – Joseph Myers Jan 16 '14 at 06:43

2 Answers2

1

Your onclick works fine.

If you have it on a div, you might have problems of it not actually having any size (often an empty div will have 100% width and 0px height, unless something's in it).

I'd suggest double checking that your div has size to it.

Here's a working jsbin:

http://jsbin.com/UmelibO/1/edit

Keith
  • 4,144
  • 7
  • 25
  • 43
1

I don't like use javascript mixed with HTML, when you have a large app debug would be messy, I prefer delegate an onClick event on this fashion:

<button id="my_button">Click me!</div>

<script>
    (function () {
        var btn = document.getElementById('my_button');
        btn.addEventListener('click', function (event) {
            alert('Click!');
        });
    }());
</script>

In the code before we are setting an event listener to the button which will invoke that callback function. I have used a button, but it is the same with a div. The live example: http://jsfiddle.net/TonyMtz/pT4nw/2/

Cheers.

TonyMtz
  • 46
  • 3