1

Ok, this is my HTML

<div id="plus" style="margin-left: 10px; margin-top: 303px;">
      <div id="plus-back"> </div>
      <div id="plus-ex"> X </div>
</div>

NOTE: the #plus element's inline styles was declared previuously by another script

And this is my JS

document.getElementById("plus").onclick = showNav 
document.getElementById("plus-ex").onclick = hideNav

function showNav(){
    this.style.width="200px"
    this.style.height="200px"
    document.getElementById("plus-ex").style.display="block"
}
function hideNav(){
    document.getElementById("plus").style.width="48px"
    document.getElementById("plus").style.height="48px"
}

Well.. this is what i have. The goal is simple, when you click #plus, this is expanded to show some content, and appears a "X" that is inside #plus-ex, and when you click that "X", #plus go back to the start (that is a div with 48px of height and width thanks to stylesheet). The problem with this, is that hideNav() is not doing a good work. When you click #plus, showNav() function is fired successfully, but after that, when you click the "X" and hideNav() is fired (successfully too), that should apply the initial style, but does anything. I have tested applying another CSS propieties like background-color and works OK, but not with width and height.

I think that the problem is that i can't override the styles applied by showNav()

What should i do?

3
  • maybe the problem is .style.display="block" ? Commented Aug 18, 2013 at 4:45
  • @muratgu No, i deleted .style.display="block" but the problem persist. Commented Aug 18, 2013 at 4:50
  • @Yavierre: <div> by default will shrink/wrap its height based on its content. I'm afraid you cannot set its height explicitly. Commented Aug 18, 2013 at 4:56

1 Answer 1

4

The problem is when you click X the event is bubbling up to the #plus div. You can prevent this by calling:

event.stopPropagation();

Update your code as follows and give it a try:

document.getElementById("plus").onclick = showNav 
document.getElementById("plus-ex").onclick = hideNav

function showNav(){
    this.style.width="200px"
    this.style.height="200px"
    document.getElementById("plus-ex").style.display="block" // Don't need this line as it's a block element i.e. already a div

    event.stopPropagation(); // add this line
}
function hideNav(){
    document.getElementById("plus").style.width="48px"
    document.getElementById("plus").style.height="48px"

    event.stopPropagation(); // add this line
}
Sign up to request clarification or add additional context in comments.

1 Comment

THAT WORKS! i didn't know about "bubbling", and event.stopPropagation() have a bug in IE but i have found a solution. Thanks!

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.