tags:

views:

153

answers:

6

How can I handle a link which doesn't have an id? It just has a classname like "classbeauty".

Now I need to know if a user has clicked the link. If the link is clicked I just need to call alert("yes link clicked");.

I don't know how to handle events in JavaScript.

How can I do that?

+4  A: 

If jQuery is an option:

 $("a.classbeauty").click(function(){
   alert("yes link clicked");
 });

If you need pure JavaScript:

var elements = document.getElementsByTagName("a"); 
for(var i=0; i<elements.length; i++){
    if (elements[i].className == 'classbeauty') { 
         elements[i].onclick = function(){ 
           alert("yes link clicked); 
   }
 } 
}

If you need it in Greasemonkey:

function GM_wait() {
    if(typeof unsafeWindow.jQuery != 'function') { 
        window.setTimeout(wait, 100); 
    } else {         
            unsafeWindow.jQuery('a.classbeauty').click(function(){
                    alert('yes link clicked');
                }); 
    }
}
GM_wait();
systempuntoout
Why not `getElementsByTagName("a")`?
BalusC
Yep, updated..thanks.
systempuntoout
+1  A: 
function getElementsByClassName(class_name) {
    var elements = document.getElementsByTagName('*');
    var found = [];

    for (var i = 0; i < elements.length; i++) {
        if (elements[i].className == class_name) {
            found.push(elements[i]);
        }
    }

    return found;
}

getElementsByClassName("YourClass")[0].onclick = function () { alert("clicked"); };

This is pure javascript, by the way. Everyone here loves jQuery (including me).

Francisco Soto
You can't assign `onclick` on an Array.
bobince
You see the [0] right there, don't you?
Francisco Soto
Don't forget that elements can have multiple, space-separated classes, so this solution might miss an anchor with more than one class. An easy fix is to add `var regex = new RegExp("\\b" + class_name + "\\b")` and then `if (regex.test(elements[i].className) {` instead of just checking string equality of class names.
maerics
I was trying to keep it simple but you are right, I didn't think of that, thanks!
Francisco Soto
+1  A: 
for (var i= document.links.length; i-->0;) {
    if (document.links[i].className==='classbeauty') {
        document.links[i].onclick= function() {
            alert('yes link clicked');
            return false; // if you want to stop the link being followed
        }
    }
}
bobince
+1 This is a good answer, please be correct and don't downvote!
systempuntoout
-1 Not enough jQuery (only kidding)
James Westgate
A: 
function handleLinks(className, disableHref) {
    var links = document.body.getElementsByTagName("a");

    for (var i = 0; i < links.length; i++) {
       if (links[i].className == className) {
           links[i].onclick = function(){
               alert('test')
               if (disableHref) {
                   return false; //the link does not follow
               }
           }
       }
    }

}

handleLinks('test', true)

you can test it at this link: http://jsfiddle.net/e7rSb/

meo
A: 

I'm not sure if this is an option, but I would flip a flag when the link is clicked, and then just test for that variable.

//javascript
var _cbClicked = false;   
function checkClicked() {
    if (_cbClicked) alert("link was clicked");
    return false;
} 

//html
<a href="#" class="classbeauty" onclick="_cbClicked = true; return false;">Link Text</a>
<a href="#" onclick="checkClicked();">Check Link</a>

Very simple, and pure JS :)

Khan
+1  A: 

If you control the source code, you could add your script inline.

<a onclick="alert('yes link clicked'); return false">Link</a>

If you're targeting modern browsers, you could select the element with getElementsByClassName. Several other people here have presented their own implementations of this function.

var node = document.getElementsByClassName('classbeauty')[0]
node.onclick = function(event){
    event.preventDefault()
    alert("yes link clicked")
}
Nick Retallack
+1 for preventDefault()
meo