Szymon
Szymon

Reputation: 89

JavaScript IF statement problem

I have a problem writing an if statement, due to my lack of programing skills.

there's the code :

   $("div.footerMenu li div.onScreen").click( 
  function(e) { e.stopPropagation(); e.preventDefault(); return false; } 
);

Inside this div I have simple <a></a> links. And the problem is, when i click on that link, nothing happens. I'm trying to make a function, that would not execute that function(e) if the target of .click would be an <a></a> tag. Is there a simple way to do that?

Upvotes: 1

Views: 207

Answers (6)

Umair Jabbar
Umair Jabbar

Reputation: 3666

I had a similar problem and here is the solution that works :)

$("div.footerMenu li div.onScreen").click(function(e) { 
    if( !( $(e.target).is('a') ) ) 
        e.stopPropagation(); e.preventDefault(); return false; 
    } 
);

Upvotes: 1

Jonathon Bolster
Jonathon Bolster

Reputation: 15961

Rather than check if target was an a (to me, it's a bit messy), I'd prefer to separate it out and handle the links separately. By using e.stopPropagation only, you'll be able to click the link and have whatever action you want on it as well as preventing the event from bubbling up to the div.

$("div").click(function(e){
    alert('You clicked me, I am the div!');
});

$("div a").click(function(e){
    // Allows the link to be clicked but prevents
    // the event from bubbling up to the div
    e.stopPropagation();
}); 

Example: http://jsfiddle.net/jonathon/s2TxS/

Upvotes: 0

When you click on an element, only events it will be running. But not events atached on parent elements. You need to change your selector to match all child elements.

$("div.footerMenu li div.onScreen > *") $("div.footerMenu li div.onScreen > a")

Upvotes: 0

xzyfer
xzyfer

Reputation: 14125

You problem is that because you're link is inside the div, your code is blocking the click event, hence why nothing happens. You could try this:

$("div.footerMenu li div.onScreen").click(function(e) { 
    if(e.target.tagName.toLowerCase() != 'a') {
        e.stopPropagation(); 
        e.preventDefault(); 
        return false; 
    }
});

I'm using .toLowerCase() because I'm not 100% the tagName will always be uppercase in all browsers. Just a sanity check.

Upvotes: 2

jishi
jishi

Reputation: 24604

You will need to check if the node has tagName == 'A'

if (this.tagName == 'A')

"this" should reference to the node being clicked, otherwise lookup e.target or e.targetSrc (don't know the jQuery equivalent)

Upvotes: 0

James Long
James Long

Reputation: 4736

Yup, very easy

if (e.target.nodeName !== "A") {
    // your code here
}

Upvotes: 0

Related Questions