I am using the accordion that is part of the jquery-ui framework. I want the accordion to collapse completely when the user clicks on another part of the screen.
I have tried to attach a blur event to the acco开发者_C百科rdion container but this never seems to fire an unexpected times.
Here is an example on JSFiddle
As you can see, the blur event is fired when an accordion section is closed and at no other time. I want an event to fire only when an open accordion section loses focus.
I have also tried attaching a blur event to the accordion sections but this never seems to fire. Example
This looks like it's not as easy as you might think. See this for a partial solution:
function activate() {
$('.container').accordion("destroy");
$('.container').accordion({
collapsible: true,
active: false
});
}
activate();
$('.container h3').live( 'blur', function() {
$(".container").accordion('activate', false);
activate(); // this should be delayed until the elements are closed
});
It destroys and reactivates the accordion, the only solution I found right now.
It works, but the closing animation does not. Maybe with a little bit trying you can get it to work properly (see the hint in the code).
EDIT:
note I removed the <a>
-tags, so the headers look like this:
<h3>Example</h3>
my second try, without a plugin (but still somewhat heavy): Simply compares mouse position with container's dimensions.
EDIT: Now with focus, too.
See jsfiddle
EDIT 2: Unfortunately a little but buggy, collapsed items sometimes do not open again... you have to click a second time outside the container. Don't know why.
I managed to do this successfully using the events outside plugin. I think this is quite a heavy solution so if anybody has a better one, that would be great.
Instead of using a blur event, just use a 'clickoutside' event binded to the container element:
$('.container').bind('clickoutside', function() {
$(this).accordion("activate", false);
});
This won't work if the user tabs outside the element or otherwise loses focus without clicking but it was sufficient for my purposes.
You can use the JQuery's mouseleave
event
From the documentation:
The mouseleave JavaScript event is proprietary to Internet Explorer. Because of the event's general utility, jQuery simulates this event so that it can be used regardless of browser. This event is sent to an element when the mouse pointer leaves the element. Any HTML element can receive this event.
Here's a demo
HTML
<div id="outside"></div>
<div id="accordion">
<div>Panel 0</div>
<div>Content 0</div>
<div>Panel 1</div>
<div>Content 1</div>
<div>Panel2</div>
<div>Content 2</div>
JS
$('#accordion').accordion({
heightStyle: "content",
collapsible: true,
active: false
});
$('#accordion').on('mouseleave', function() {
$(this).accordion("activate", false);
});
精彩评论