0

I have a few hidden divs which reveal themselves "onmousedown." However, you have to click the link twice for the hidden content to disappear. I'd like the content to disappear when you click any other "onmousedown" link on the page, instead of having to click the same link twice. It ends up that, if you don't click the link twice, and you click another onmousedown link, the content becomes nested and overlaps. Here's the code I'm using to toggle visibility:

function toggleVisibility(id) {
   var e = document.getElementById(id);
   if(e.style.display == 'block')
      e.style.display = 'none';
   else
      e.style.display = 'block';
}

Here's the jsfiddle. (Forgive me -- for some reason the jquery isn't functioning. Perhaps some expert will see where I copied things incorrectly, but otherwise I think one can see pretty clearly what's going on -- just imagine the hidden content for each div appearing all at once nested below the links.)

user2985093
  • 63
  • 1
  • 2
  • 13

1 Answers1

1

Try

<div class="nav">
    <a href="#hello">Hello</a>
    <a href="#hi">Hi</a>
    <a href="#howdy">Howdy</a>
</div>

<div class="sub" id="hello">a
    Hello hello hello
</div>

<div class="sub" id="hi">
    Hi hi hi hi hi hi
</div>

<div class="sub" id="howdy">
    Howdy Howdy Howdy
</div>

then

jQuery(function () {
    var $subs = $('.sub');
    $('.nav a').on('mouseenter', function () {
        var $target = $($(this).attr('href'));
        $subs.not($target).hide();
        $target.toggle();
    });
});

Demo: Fiddle

Why your fiddle was not working? You were using the function toggleVisibility in the inline mode where the function will be looked up in the global scope, but you added your function definition in the onload callback(selected onload in the second dropdown in the left panel) making in a closure scoped function. Select Nowrap Header/Body to fix it.

Why your code was not working? whenever you do a mouseover you need to first hide the previously opened navigation item then open the new one. It is much easier to do with jQuery way, so in my solution I adapted a jQuery solution as given above.

Arun P Johny
  • 384,651
  • 66
  • 527
  • 531
  • Thanks so much, Arun. I was able to implement this and it works perfectly. Much better than what I had before. Is it possible, however, to make this work by "clicking" rather than "hovering" over the link? – user2985093 Nov 15 '13 at 00:38
  • Thank you so much. Perfect. A final question: if I were to go with the hover method (or even the click method), could I set it up in such a way that when the user hovered over some other element on the page -- say, an image -- all the hidden divs would disappear again? – user2985093 Nov 15 '13 at 00:59
  • @user2985093 http://jsfiddle.net/arunpjohny/7DJjY/3/ or http://jsfiddle.net/arunpjohny/7DJjY/4/ – Arun P Johny Nov 15 '13 at 01:09