Kevin Yuen
Kevin Yuen

Reputation: 21

Check link click happen within a div

I would like the Javascript returning true when users click on the links within specific div

For example: When users click on links in div having class="span1", it will return true

<div class="span1">
   <h3>Title 3</h3>
      <ul class="stages" dir="ltr">
          <li><a href="http://www.example.com" >Example 1</a></li>
          <li><a href="http://www.example.com" >Example 2</a></li>
      </ul>
</div>

<div class="span2">
   <h3>Title 4</h3>
      <ul class="stages" dir="ltr">
          <li><a href="http://www.example.com" >Example 1</a></li>
          <li><a href="http://www.example.com" >Example 2</a></li>
      </ul>
</div>

Thanks a lot!!

Upvotes: 0

Views: 61

Answers (2)

Michelangelo
Michelangelo

Reputation: 5948

Here in pure Javascript: http://jsfiddle.net/xxx96bta/5/

var links = document.getElementsByTagName('a'); //collect your elements

for (i = 0; i < links.length; i++) {
    (function () {
        links[i].addEventListener('click', whatSpan, false);
    })();
}

function whatSpan() {
    var parentspan = this.parentNode.parentNode.parentNode.className;
    if (parentspan == "span1") {
        alert("you clicked span 1");
    } else {
        alert("you clicked span 2");
    }

}

Upvotes: 0

jmore009
jmore009

Reputation: 12923

Simply use an if statement for .hasClass:

$("div").click(function(){
  if($(this).hasClass("span1")){
    alert("SPAN 1 CLICKED");
    return true;
  }
});

FIDDLE

UPDATE: I read your question too quick, here is a new fiddle which targets your a's instead of the div

NEW FIDDLE

should be this instead:

if($(this).closest("div").hasClass("span1")){

Upvotes: 1

Related Questions