Javascript detect ID clicked ?

error77
error77 used Ask the Experts™
on
Hi all,

Is it possible at all to detect if an id has been clicked?

For example: I want a link on a page containing an ID to be detected by javascript if it was click.

The javascript would look like this...

if (ID was clicked) {
   alert("id was clicked");
}

something like that anyway..

Can this be done?

Thanks

Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
The best way to do it would be to just add a class to an element once it has been clicked (ex. 'clicked'), and then check to see if that element has the class 'clicked' during your check.

Are you using a library like jQuery, or just straight up javascript?
leakim971Multitechnician
Top Expert 2014

Commented:
$("a").click(function() { if( $(this).attr("id") == "ID" ) {
    alert("id was clicked");
}});

Open in new window


or if you create the link dynamically :

$("a").live("click", function() { if( $(this).attr("id") == "ID" ) {
    alert("id was clicked");
}});

Open in new window



Author

Commented:
Looks perfect but I need to change the code in the plugin js file so I don't think I can use JQuery for this.

What would the pure javascript translation be please?
Multitechnician
Top Expert 2014
Commented:
window.onload = function() {
    var anchors = document.getElementsByTagName("a");
    for(var i=0;i<anchors.length;i++) {
        anchors[i].onclick = function() {
            if( this.id == "ID" ) {
                 alert("id was clicked");
            }
            //return false;
        }
    }
}

Open in new window

Author

Commented:
Thanks !!!

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial