views:

1465

answers:

9

How to make OnClick without jQuery, with no extra code in html, such as:

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

just using an extrnal js file?

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


Need to replace this code:

 $("a.scroll-up, a.scroll-down").click(function(){SNavigate($(this).attr("href").substr(7));return false;});
+2  A: 
<script>
 function tramtramtram(){
     alert("tram it!");
 }
</script>


<a href="#" onclick="tramtramtram()">tramtram</a>
bchhun
I couldn't tell which one of us got here first ;-)
Lucas McCoy
I need to remove all "onclick" from html
Mike
Then Canavar's answer is the good one.
bchhun
+6  A: 

how about this :

document.getElementById("lady").onclick = function () {alert('onclick');};
Canavar
looks good. Can you replace given function with ordinary js, without using jquery?
Mike
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
@Mike:that is "ordinary" javascript. Except it gets the element by id instead of by class like your code.
bchhun
@Bernard: Mike changed the question quite a bit in his edit.
null
@Anonymous : thanks, how do you keep track of the atteched events by addEventListener ?
Canavar
A: 

Just use the onclick attribute.

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

Or to do it from javascript,

document.getElementById("anchorID").onclick = function(){
   some code
};
null
I need to remove all "onclick" from html
Mike
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
+1  A: 

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

ka3751
A: 

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
onload - waste, isn't it?
Mike
+10  A: 

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
goood, thanks. Thats what I need.
Mike
You might also find Dean Edwards solution interesting - http://dean.edwards.name/weblog/2005/10/add-event/
Russ Cam
@Russ Cam: Dean Edwards solution has one disadvantage, what Dean described later: http://dean.edwards.name/weblog/
Rafael
@Rafael - Interesting, thanks for the link
Russ Cam
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
+1  A: 

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
can you replace a given function with ordinary js, without using jquery?
Mike
That *is* ordinary JavaScript, without using jQuery.
RichieHindle
there is a new code in the question
Mike
+4  A: 

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
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?
Dr.Dredel
(I'm just curious, btw, I have no need for this code... was just reading this post and the question occurred to me).
Dr.Dredel
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
+1  A: 

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