Wednesday, July 6, 2011

When you can't onclick() in html

Change:

<button onclick="myFunction()">Click me</button>

To one of:
way 1 with .onclick with anonymous function
<body>
    <button id="myButton">Click me</button>
    <script>document.getElementById("myButton").onclick = function(){ stuff };</script>
</body>

way 2 with .onclick with named function
<body>
    <button id="myButton">Click me</button>
    <script>function myFunction() { stuff };
    document.getElementById("myButton").onclick = myFunction;</script>
</body>

way 3 with .addEventListener() with named function
<body>
    <button id="myButton">Click me</button>
    <script>document.getElementById("myButton").addEventListener('click', myFunction, false);</script>
</body>

Remember to put the addEventListener script after you have created the button. If you have to put it in the head, put the line of script inside a jQuery ready like
<!-- try not to do this though -->
<head>
    <script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script>
    <script type="text/javascript">
        $(document).ready(function() {
            document.getElementById("myButton").addEventListener('click', myFunction, false);
        }
</script>
</head> 

<body>
    <button id="checkButton">Click me</button>
</body>

But it's better practice to put js right before the closing of the body tag.



If your function has arguments...

Change:

<button onclick="myFunction('arg1')">Click me</button>

To
<body>
    <button id="myButton">Click me</button>
    <script>document.getElementById("myButton").addEventListener('click', function(){ myFunction('arg1') }, false);</script>
</body>

No comments:

Post a Comment