52

How to make onclick without jQuery, with no extra code in HTML, such as:

<a href="#" onclick="tramtramtram">

Just using an external js file?

<script type="text/javascript" src="functions.js"></script>

I need to replace this code:

$("a.scroll-up, a.scroll-down").click(function(){
    SNavigate($(this).attr("href").substr(7));return false;
});
Roman Pokrovskij
  • 9,449
  • 21
  • 87
  • 142
Mike
  • 1,825
  • 3
  • 21
  • 26

9 Answers9

66

When this anchor will contain only one function to handle on click, than you can just write

document.getElementById('anchorID').onclick=function(){/* some code */}

otherwise, you have to use DOM method addEventListener

function clickHandler(){ /* some code */ }
var anchor = document.getElementById('anchorID');
if(anchor.addEventListener) // DOM method
  anchor.addEventListener('click', clickHandler, false);
else if(anchor.attachEvent) // this is for IE, because it doesn't support addEventListener
   anchor.attachEvent('onclick', function(){ return clickHandler.apply(anchor, [window.event]}); // this strange part for making the keyword 'this' indicate the clicked anchor

also remember to call the above code when all elements are loaded (eg. on window.onload)

-- edit

I see you added some details. If you want to replace the code below

$("a.scroll-up, a.scroll-down").click(function(){SNavigate($(this).attr("href").substr(7));return false;});

with sth that doesn't use jQuery, this should do the job

function addEvent(obj, type, fn) {
        if (obj.addEventListener)
                obj.addEventListener(type, fn, false);
        else if (obj.attachEvent)
                obj.attachEvent('on' + type, function() { return fn.apply(obj, [window.event]);});
}
addEvent(window, 'load', function(){
   for(var i=0, a=document.anchors, l=a.length; i<l;++i){
      if(a[i].className == 'scroll-up' || a[i].className == 'scroll-down'){
         addEvent(a[i], 'click', function(e){ SNavigate(this.href.substr(7)); e.returnValue=false; if(e.preventDefault)e.preventDefault();return false});
      }
   }
});
Rafael
  • 18,349
  • 5
  • 58
  • 67
  • You might also find Dean Edwards solution interesting - http://dean.edwards.name/weblog/2005/10/add-event/ – Russ Cam May 12 '09 at 21:54
  • 1
    @Russ Cam: Dean Edwards solution has one disadvantage, what Dean described later: http://dean.edwards.name/weblog/ – Rafael May 13 '09 at 08:48
  • oh, pasted incomplete URL, sorry ;-) This one is fine: http://dean.edwards.name/weblog/2009/03/callbacks-vs-events/ but I see you already found what I meant. – Rafael May 13 '09 at 12:08
15

how about this :

document.getElementById("lady").onclick = function () {alert('onclick');};
Canavar
  • 47,715
  • 17
  • 91
  • 122
  • looks good. Can you replace given function with ordinary js, without using jquery? – Mike May 12 '09 at 20:53
  • Just overwrite the onlick property. If you were using addEventListener, you'd also have to keep track of what you added to remove it later (which is doubtless what JQuery uses itself). – Anonymous May 12 '09 at 20:56
  • @Mike: that is "ordinary" javascript. Except it gets the element by id instead of by class like your code. – bchhun May 12 '09 at 20:57
  • @Anonymous : thanks, how do you keep track of the atteched events by addEventListener ? – Canavar May 12 '09 at 21:01
5

W3C suggests:

element.addEventListener('click',doSomething,false)

Microsoft uses:

element.attachEvent('onclick',doSomething)

You can do some feature detection and determine which call to use.

From http://www.quirksmode.org/js/events_advanced.html.

Corbin March
  • 25,526
  • 6
  • 73
  • 100
  • can you then remove the event later? What if it was a nameless event, like a function declaration ie. foo.addEventListener('onclick', function(){alert('bar') ); or is it attached for ever? – Yevgeny Simkin May 12 '09 at 22:46
  • (I'm just curious, btw, I have no need for this code... was just reading this post and the question occurred to me). – Yevgeny Simkin May 12 '09 at 22:47
  • You remove the event via element.removeEventListener (WC3) or element.detachEvent (MS). Unfortunately, this doesn't work for anonymous functions. I'd stay with named functions for event handlers. – Corbin March May 13 '09 at 05:18
2

With no extra code in the html, here's a way to do it:

<html><body><head><script>  // This script could be in an external JS file
function my_handler(elt) {
    alert("Yay!");
    return false;
}

function setup() {
    document.getElementById('lady').onclick = my_handler;
}

window.onload = setup;
</script></head>
<body><a href='#' id='lady'>Test</a></body>
</html>
RichieHindle
  • 272,464
  • 47
  • 358
  • 399
1
<script>
 function tramtramtram(){
     alert("tram it!");
 }
</script>


<a href="#" onclick="tramtramtram()">tramtram</a>
bchhun
  • 18,116
  • 8
  • 28
  • 31
1

var el =document.getElementById('lady'); el.addEventListener( "click", tramtramtram, false );

ka3751
  • 51
  • 4
1

Execute this script when document loads (replacing alert with your stuff):

var rgLinks = document.getElementsByTagName("A");

for (var x=0; x<rgLinks.length; x++) {
    el = rgLinks[x];

    if (el.className == 'scroll-down' || el.className == 'scroll-down')
        {
        el.onclick = function () {alert('onclick');};
        }
    }

Maybe that is what you are asking about...

buti-oxa
  • 11,261
  • 5
  • 35
  • 44
0

Just use the onclick attribute.

<a href="#" onclick="functionName(someParam)">

Or to do it from javascript,

document.getElementById("anchorID").onclick = function(){
   some code
};
null
  • 878
  • 6
  • 11
  • I need to remove all "onclick" from html – Mike May 12 '09 at 20:52
  • Since the new question uses a class selector rather than an id, you have to first find all elements using that class yourself. see the many implementations of getElementsByClass in google. – null May 12 '09 at 21:17
0

You need to use getElementById to add the onclick handler. However you need to initiate your code somewhere. Without jQuery you can only use the body onload handler:

<body onload="myinitfunction()">

myinitfunction can be in an external js file.

kgiannakakis
  • 103,016
  • 27
  • 158
  • 194