Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Div's clicking through each other?

Tags:

javascript

I have a containing div, which acts as a button all by itself...

When clicked though, I have it setup to expand and reveal more information, at the same time revealing a close button on the top right...

Now, When i click the close button, the close function executes, but also the div's onclick to open, so the end result is, well... Nothing happens...

Lol...

The fiddle example isn't working either, and I'm near the end of my wits...

http://jsfiddle.net/VeyeY/5/

like image 261
Abhishek Avatar asked Jun 14 '11 08:06

Abhishek


1 Answers

You could either return false from the onclick to close the div. That will make sure that the click event is not propagated.

Another solution would be to call preventDefault() and stopPropagation() on the event itself. That will also make sure that the event does not go on.

Edit:

In all the Events that happens ( onclick, onchange, onmouseover, etc ) there is always an event variable possible that you can either ignore if you want to, or extract information from. In your example I think the easiest way to work with the event variable would be to do something like this:

<div id="inner" onclick="toggle(false); event.preventDefault(); event.stopPropagation();">

Now this is a bit ugly to look at and you really dont want to deal with this in the html markup either so another option would be to pass the event variable to your function like this:

<div id="inner" onclick="toggle(event, false)">

and then in the javascript:

function toggle(event, x){
    // Do your thing

    event.preventDefault();
    event.stopPropagation();
}

There are a lot of things you could do with the event variable. For example, instead of passing true or false to your function, you could check which node that originated the event like this:

if(event.originalTarget.id == "inner"){
    // Inner was clicked
}else if(event.originalTarget.id == "outer"){
    // Outer was clicked
}
like image 107
DanneManne Avatar answered Oct 15 '22 06:10

DanneManne