1 Replies - 909 Views - Last Post: 01 June 2012 - 05:10 PM

#1 fallenreaper   User is offline

  • D.I.C Head

Reputation: 3
  • View blog
  • Posts: 240
  • Joined: 19-June 10

Get clicked element ID ONLY if it matches a desired class

Posted 01 June 2012 - 06:43 AM

I have code below to get the clicked element below:
var SELECTED_ELEMENT = null;
function getEl(mouse) {
                var ev = mouse || window.event;
                SELECTED_ELEMENT = ev.target || ev.srcElement;
}
document.onclick = getEL;


which works fine for most instances of click but i noticed some elements which were being stored in the "SELECTED_ELEMENT" field which shouldnt be.

With that said, i was thinking to do something like:
...
var ev = mouse || window.event;
var t_select = ev.target || ev.srcElement;
if ($(t_select).attr("class") == "derp"){
  SELECTED_ELEMENT = t_select;
}
...



that way the code would only override the selected element if the selected element or one of its parents has the class "derp"

Maybe i could change the if statement to something like
if ($(t_select).closest(".derp").length > 0){SELECTED_ELEMENT = t_select; }



What do you all think?

Is This A Good Question/Topic? 0
  • +

Replies To: Get clicked element ID ONLY if it matches a desired class

#2 Dormilich   User is offline

  • 痛覚残留
  • member icon

Reputation: 4303
  • View blog
  • Posts: 13,677
  • Joined: 08-June 10

Re: Get clicked element ID ONLY if it matches a desired class

Posted 01 June 2012 - 05:10 PM

too complicated. if you already use jQuery, set the event on the elements with the desired class.
$(".derpt").click(function() { /* … */ });


but generally, why a global variable for that? there are usually better alternatives than unpredictable globals.
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1