Showing posts with label javascript. Show all posts
Showing posts with label javascript. Show all posts

Sunday, July 17, 2011

jQuery hosting

<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script>

I am tired of going to my site every time and get it from its source.

Monday, July 11, 2011

Javascript indentation with beautifier

So useful!!!

Javascript comma!

The comma operator evaluates both of its operands (from left to right) and returns the value of the second operand.

as seen in Google recaptcha's js:

if (RecaptchaOptions.theme == "custom") {
    if (RecaptchaOptions.custom_theme_widget) Recaptcha.widget = Recaptcha.$(RecaptchaOptions.custom_theme_widget);
    Recaptcha.challenge_callback()
} else 
    document.write('<div id="recaptcha_widget_div" style="display:none"></div>'),
    document.write('<script>Recaptcha.widget = Recaptcha.$("recaptcha_widget_div"); Recaptcha.challenge_callback();<\/script>');

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>

Where to put JS

I learned that JS is executed as soon as its parsed. So it's best to put <script> right before the </body> closing tag. For example: http://support.mozilla.com/en-US/home