Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if event target is hyperlink

I have a large div inside there which are smaller divs, achor tags and other elements. Each large div in my program is bound to "mousedown" event and inside the onMouseDown handler, I basically check the event.target.

If a user clicks on an items that is a hyper link, I want to check if event.target was hyperlink and then navigate to that link if event.target was a hyperlink. How can that be done?

Here's the structure of the divsa and elements.

<div class="camp-name">     <span class="btnCampaign"><div class=""></div></span>     <span class="campaign-name">        <a href="http://www.google.com">Some Link here</a>     </span> </div> <div class="campaign-name-sub">    <span class="campaign-accountname">Some Text here</span>    <span class="seprator">|</span>    <span class="brandname">Some Text here</span> </div> 

JS

var label = label.createElement("DIV"); label.innerHMTL = src //src is the above html that is seen here     Plugin.addEventListener(label, "mousedown", params.onMouseDown);   Plugin.onMouseDown() = function(event) { var target = (event.currentTarget) ? event.currentTarget : event.srcElement;         if (target.tagName.toLowerCase() === "a" && target !== undefined) {             console.log(target.href);             Plugin.stopPropagation(event);         } }; 
like image 690
user1240679 Avatar asked Mar 27 '13 14:03

user1240679


People also ask

How do you know if an event target contains a class?

To check if event. target has specific class, call the classList. contains() method on the target object, e.g. event. target.

Is Event target deprecated?

Obsolete This feature is obsolete. Although it may still work in some browsers, its use is discouraged since it could be removed at any time.

How do you get a href from Click event?

To get the value of the href attribute of a clicked link, create an event listener using AddEventListener() and retrieve the value of the href attribute using Element. target() .


2 Answers

You should get it through

if(event.target.tagName.toLowerCase() === 'a') {     event.target.href; //this is the url where the anchor tag points to. } 
like image 85
Parthik Gosar Avatar answered Oct 09 '22 08:10

Parthik Gosar


You could check the tagName property, as said by @parthik-gosar. Another way is to use the instanceof operator to check the element class (hyperlinks are of type HTMLAnchorElement):

if (event.target instanceof HTMLAnchorElement) {   console.log(event.target.href); } 
like image 26
CedX Avatar answered Oct 09 '22 09:10

CedX