0

I want to fix a problem I have attaching an onclick element to a div ( and only to it! )

Please look at following code :

<script>
function  goToo(url,idd){
alert(idd);
if (idd=="onlyMe")
window.location=url;
}
</script>
<div id="onlyMe" onclick="javascript:goToo('http://www.google.com', this.id)" style="<-index:-150">
<form><input type="text" name="coap"></form>

<h3>This is an element where click should work!</h3>

<div id="notME">
<h3>In this point it should not work!</h3>
</div>

</div>

I want the onlick to be triggered only in the div clicking.

Please check the example live @ http://modacalcio.com/HtmlProblemForm.html

The click is triggered everywhere, expecially in the form input.

Obiovusly I wish to use this without deleting onclick in children nodes, as they have their own onclick that still need to work

Also with jquery I have same problem any help?

3
  • Well, if it works in the form, which is inside the div, it is normal behavior. Jun 6, 2012 at 10:01
  • yes, it may be normal but I want only to works in the div and not in children, to use maybe as a website background link. Is it possible?
    – giuseppe
    Jun 6, 2012 at 10:06
  • Oh. Yes, it is possible. Let me think about it :) Jun 6, 2012 at 10:07

2 Answers 2

2
$('#onlyMe').on('click', function(evt) {
    if ($(evt.target).parents('#notME').length === 0 && evt.target.id !== 'notME') {
        location.href = "http://...";
    }       
});

example fiddle: http://jsfiddle.net/zhkr2/2/

the idea is to check if the event was triggered on #notME element or inside an element contained in #notME, so I check if an ancestor is that element

4
  • Seeing OP's code, you should definitely state the jQuery dependency :) Jun 6, 2012 at 10:12
  • I just noticed the jQuery tag :) Jun 6, 2012 at 10:13
  • Oh, I didn't! I guess this answer is fine then. Jun 6, 2012 at 10:14
  • Florian you are too nice :D yes I am opened to jqeury solution I have written it in question but maybe is not clear. This solution works effectively but I need the revers, so to verify that the click comes ONLY BY the only Me and not his children. This because I don't know how many element I can have inside the div I want to be clickable as a background website rotator. There is no way really to determine which element is triggering the click effectively and not composite ?
    – giuseppe
    Jun 6, 2012 at 10:26
0

just give for 'div' some width

#onlyMe
{
width:
height:

}

and close the div properly .

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.