Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to handle a clicked link in JavaScript?

Tags:

javascript

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?

like image 916
streetparade Avatar asked Nov 29 '22 05:11

streetparade


2 Answers

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();
like image 146
systempuntoout Avatar answered Dec 09 '22 17:12

systempuntoout


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")
}
like image 39
Nick Retallack Avatar answered Dec 09 '22 16:12

Nick Retallack