Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unobtrusive Javascript onclick

I was recently reading on Unobtrusive javascript and decided to give it a shot. Whether or not I decide to use this style is to be determined at a later time. This is just for my own curiosity and not for any time restricted project.

Now, I was looking at example code and a lot of the examples seem to be using, what took me forever to discover, jQuery. They use a function like $('class-name').whatever(...);

Well I rather like the look of $('class').function, so I tried to emulate it without using jQuery(as I don't know jQuery and don't care about it atm). I'm unable, however, to make this example work.

Here is my jsFiddle: http://jsfiddle.net/dethnull/K3eAc/3/

<!DOCTYPE html>
<html>
<head>
    <title>Unobtrusive Javascript test</title>
<script>
    function $(id) {
        return document.getElementById(id);
    }

    $('tester').onclick(function () {
        alert('Hello world');
    });
</script>
<style>
    .styled {
        width: 200px;
        margin-left: auto;
        margin-right: auto;
        font-size: 2em;
    }
    a {
        cursor: pointer;
        color: blue;
    }
    a:hover {
        text-decoration: underline;
    }   
</style>
</head>
    <body>
        <div class='styled'>
            <ul>
                <li><a id='tester'>CLICK ME</a></li>
            </ul>

         </div> 
     </body>
</html>

I was expecting an alert box to pop up when you click on the link, but doesn't seem to happen. When checking the console in chrome it gives this message "Uncaught TypeError: Cannot call method 'onClick' of null"

I'm not a javascript expert, so more than likely I'm doing something wrong. Any help is appreciated.

like image 921
DerekE Avatar asked Apr 13 '13 12:04

DerekE


1 Answers

Try this code,

Script

function $(id) {
    return document.getElementById(id);
}

$('tester').addEventListener('click', function () {
    alert('Hello world');
});

When you console this $('tester') selector, it simply returns <a id='tester'>CLICK ME</a> which is a html element not an object so you cannot use onclick directly. Instead you have to use addEventListener or attachEvent to bind a click event

Demo JS http://jsfiddle.net/K3eAc/4/

like image 133
moustacheman Avatar answered Jan 03 '23 13:01

moustacheman