53

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;
});

9 Answers 9

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});
      }
   }
});
3
15

how about this :

document.getElementById("lady").onclick = function () {alert('onclick');};
4
  • looks good. Can you replace given function with ordinary js, without using jquery?
    – Mike
    Commented May 12, 2009 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
    Commented May 12, 2009 at 20:56
  • @Mike: that is "ordinary" javascript. Except it gets the element by id instead of by class like your code.
    – bchhun
    Commented May 12, 2009 at 20:57
  • @Anonymous : thanks, how do you keep track of the atteched events by addEventListener ?
    – Canavar
    Commented May 12, 2009 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.

3
  • 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? Commented May 12, 2009 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). Commented May 12, 2009 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. Commented May 13, 2009 at 5: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>
2
  • can you replace a given function with ordinary js, without using jquery?
    – Mike
    Commented May 12, 2009 at 20:58
  • That is ordinary JavaScript, without using jQuery. Commented May 12, 2009 at 21:00
1
<script>
 function tramtramtram(){
     alert("tram it!");
 }
</script>


<a href="#" onclick="tramtramtram()">tramtram</a>
2
  • I couldn't tell which one of us got here first ;-)
    – Kredns
    Commented May 12, 2009 at 20:49
  • I need to remove all "onclick" from html
    – Mike
    Commented May 12, 2009 at 20:50
1

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

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...

0

Just use the onclick attribute.

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

Or to do it from javascript,

document.getElementById("anchorID").onclick = function(){
   some code
};
2
  • I need to remove all "onclick" from html
    – Mike
    Commented May 12, 2009 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
    Commented May 12, 2009 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.

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.