jQuery UI Accordion - does refresh method overwrites initialisation settings? - jquery-ui

Currently I am working on a project for which I use the jQuery UI Accordion.
Therefore I initialise the accordion on an element by doing
<div id="accordion"></div>
$('#accordion').accordion({
collapsible: true,
active: false,
heightStyle: "content"
});
After init the accordion I append some data coming from an AJAX request. (depends on user interaction)
In a simplified jsfiddle - which does exact the same thing as the ajax call - you can see how this looks like.
So far it seems to be working quite well but there is one problem I face.
In my initialisation I say that I want all panels to be closed but after calling refresh on the accordion everything of those settings seems to be gone and one panel opens.
Note that I implemented jQuery UI v1.10.2 in my fiddle. Update notes say
The refresh method will now recognize panels that have been added or removed. This brings accordion in line with tabs and other widgets that parse the markup to find changes.
Well it does but why has it to "overwrite" the settings I defined for this accordion?
I also thought about the possibility that it might be wrong to create the accordion on an empty <div> so I tested it with a given entry and added some elements afterwards.
But the jsfiddle shows exactly the same results.
In a recent SO thread I found someone who basically does the same thing as I do but in his jsfiddle he faces the same "issue".
He adds a new panel and the first panel opens after the refresh.
My current solution for this issue is to destroy the accordion and recreate it each time there's new content for it.
But this seems quite rough to me and I thought the refresh method solves the need to destroy the accordion each time new content gets applied.
See the last jsfiddle
$(document).ready(function () {
//variable to show "new" content gets appended correctly
var foo = 1;
$('#clickMe').on('click', function () {
var data = '';
for (var i = 0; i < 3; i++) {
data += '<h3>title' + foo + '</h3><div>content</div>';
foo++;
}
if ($('#accordion').hasClass('ui-accordion')) {
$('#accordion').accordion('destroy');
}
$('#accordion').empty().append(data).accordion({
collapsible: true,
active: false,
heightStyle: "content"
});
});
});
Unfortunately it is not an option for me to change the content of the given 3 entries because the amount of panels varies.
So my questions are the one in the title and if this behaviour is wanted like that or if anybody faces the same problem?

For the explanation of this behaviour, have a look in the refresh() method of the jquery-ui accordion widget, the problem you are facing is at line 10 :
refresh: function() {
var options = this.options;
this._processPanels();
// was collapsed or no panel
if ((options.active === false && options.collapsible === true) || !this.headers.length) {
options.active = false;
this.active = $();
// active false only when collapsible is true
} if (options.active === false) {
this._activate(0); // <-- YOUR PROBLEM IS HERE
// was active, but active panel is gone
} else if (this.active.length && !$.contains(this.element[0], this.active[0])) {
// all remaining panel are disabled
if (this.headers.length === this.headers.find(".ui-state-disabled").length) {
options.active = false;
this.active = $();
// activate previous panel
} else {
this._activate(Math.max(0, options.active - 1));
}
// was active, active panel still exists
} else {
// make sure active index is correct
options.active = this.headers.index(this.active);
}
this._destroyIcons();
this._refresh();
}

Related

Drag and Drop with Angular JS and JQuery

Couple of days ago I found this interesting post at http://www.smartjava.org/content/drag-and-drop-angularjs-using-jquery-ui and applied it into my website. However when I progressively using it there is a bug I identified, basically you can not move an item directly from one div to another's bottom, it has to go through the parts above and progress to the bottom. Anyone can suggest where does it goes wrong? The example is at http://www.smartjava.org/examples/dnd/double.html
Troubling me for days already.....
I did this a bit differently. Instead of attaching a jquery ui element inside the directive's controller, I instead did it inside the directive's link function. I came up with my solution, based on a blog post by Ben Farrell.
Note, that this is a Rails app, and I am using the acts_as_list gem to calculate positioning.
app.directive('sortable', function() {
return {
restrict: 'A',
link: function(scope, elt, attrs) {
// the card that will be moved
scope.movedCard = {};
return elt.sortable({
connectWith: ".deck",
revert: true,
items: '.card',
stop: function(evt, ui) {
return scope.$apply(function() {
// the deck the card is being moved to
// deck-id is an element attribute I defined
scope.movedCard.toDeck = parseInt(ui.item[0].parentElement.attributes['deck-id'].value);
// the id of the card being moved
// the card id is an attribute I definied
scope.movedCard.id = parseInt(ui.item[0].attributes['card-id'].value);
// edge case that handles a card being added to the end of the list
if (ui.item[0].nextElementSibling !== null) {
scope.movedCard.pos = parseInt(ui.item[0].nextElementSibling.attributes['card-pos'].value - 1);
} else {
// the card is being added to the very end of the list
scope.movedCard.pos = parseInt(ui.item[0].previousElementSibling.attributes['card-pos'].value + 1);
}
// broadcast to child scopes the movedCard event
return scope.$broadcast('movedCardEvent', scope.movedCard);
});
}
});
}
};
});
Important points
I utilize card attributes to store a card's id, deck, and position, in order to allow the jQuery sortable widget to grab onto.
After the stop event is called, I immediately execute a scope.$apply function to get back into, what Misko Hevery call,s the angular execution context.
I have a working example of this in action, up in a GitHub Repo of mine.

jQuery UI autocomplete select event not working with mouse click

I have a list of links, and I have this search box #reportname. When the user types in the search box, autocomplete will show the text of the links in a list.
<div class="inline">
<div class="span-10">
<label for="reportname">Report Name</label>
<input type="text" name="reportname" id="reportname" />
</div>
<div class="span-10 last">
<button type="button" id="reportfind">Select</button>
</div>
</div>
The user can then use the keyboard arrow to select one of the text, and when he press ENTER, browser will go to the address of the link. So far so good.
<script type="text/javascript">
$(document).ready(function () {
$("#reportname").autocomplete({
source: $.map($("a.large"), function (a) { return a.text }),
select: function () { $("#reportfind").click() }
})
$("#reportfind").click(function () {
var reportname = $("#reportname")[0].value
var thelinks = $('a.large:contains("' + reportname + '")').filter(
function (i) { return (this.text === reportname) })
window.location = thelinks[0].href
})
});
</script>
The issue is when the user types, autocomplete shows a list, and then the user use the mouse to click one of the result. With keyboard navigation, the content of the search box is changed, but if the user clicks one of the options, the search box is not modified and the select event is immediately triggered.
How can I make the script work with keyboard selection and mouse selection? How can I differentiate between select events that are triggered by keyboard with the ones triggered by mouse?
To your 2nd question: "How can I differentiate between select events that are triggered by keyboard with the ones triggered by mouse?"
The event object in the jQuery UI events would include a .originalEvent, the original event it wrapped. It could have been wrapped multiple times though, such as in the case of Autocomplete widget. So, you need to trace up the tree to get the original event object, then you can check for the event type:
$("#reportname").autocomplete({
select: function(event, ui) {
var origEvent = event;
while (origEvent.originalEvent !== undefined)
origEvent = origEvent.originalEvent;
if (origEvent.type == 'keydown')
$("#reportfind").click();
},
...
});
Thanks to #William Niu and firebug, I found that the select event parameter 'ui' contains the complete selected value: ui.item.value. So instead of depending on jquery UI to change the text of the textbox, which didn't happen if the user clicks with mouse, I just pick up the selected value from 'ui':
$("#reportname").autocomplete({
select: function (event, ui) {
var reportname = ui.item.value
var thelinks = $('a.large:contains("' + reportname + '")').filter(
function (i) { return (this.text === reportname) })
window.location = thelinks[0].href
};
})
I tested it in all version of IE (inlcuding 9) and always ended up with an empty input-control after I selected the item using the mouse. This caused some headaches. I even went down to the source code of jQuery UI to see what happens there but didn’t find any hints either.
We can do this by setting a timeout, which internally queues an event in the javascript-engine of IE. Because it is guaranteed, that this timeout-event will be queued after the focus event (this has already been triggered before by IE itself).
select: function (event, ui) {
var label = ui.item.label;
var value = ui.item.value;
$this = $(this);
setTimeout(function () {
$('#txtBoxRole').val(value);
}, 1);
},
Had the same issue / problem.
Jquery: 1.11.1
UI: 1.11.0
Question: Do you use bassistance jquery validte plugin simultanously?
If positive: update this to a newest version or just disable it for tests.
I updated from 1.5.5 to 1.13.0
Helped for me. Good luck!
I recently encountered the exact same problem (autocomplete items not clickable, keyboard events working).
Turned out that in my case the answer was not at all JS related. The autocomplete UI was not clickable simply because it was lacking an appropriate value for the z-index CSS property.
.ui-autocomplete {
z-index: 99999; /* adjust this value */
}
That did the trick.
This may be a bit farshot, but I had a similar situation where selecting an autocomplete value left the input field empty. The answer was to ignore the "change" events (as those were handled by default) and replace them with binds to "autocompletechange" events.
The "change" event gets triggered before the value from autocomplete is in the field => the field had "empty" value when handling the normal "change" event.
// ignore the "change" event for the field
var item = $("#"+id); // JQuery for getting the element
item.bind("autocompletechange", function(event, ui) { [call your handler function here] }
I was facing a similar problem. I wanted to submit the form when the user clicked on an option. But the form got submitted even before the value of the input could be set. Hence on the server side the controller got a null value.
I solved it using a modified version of William Niu's answer.
Check this post - https://stackoverflow.com/a/19781850/1565521
I had the same issue, mouse click was not selecting the item which was clicked.My code was supposed to make an ajax call to fetch the data as per the selection item from autocomplete source.
Previous code: mouse click not working.
select: function(event, ui) {
event.preventDefault();
for(i= 0; i< customer.length; i++)
if(document.getElementById('inputBox').value == customer[i].name)
{
$.ajax({
call
})
Changed code :mouse click working
select: function(event, ui) {
// event.preventDefault();
for(i= 0; i< customer.length; i++)
// if(document.getElementById('inputBox').value == customer[i].fields.name)
if(ui.item.value == customer[i].name)
{
$.ajax({
call
})
After inspecting the code in the developer tools console, I noticed there were two list items added. I removed the pairing <li></li> from my response code and oh yeah, the links worked
I also added this function as the click event:
$("#main-search").result(function ()
{
$("#main-search").val("redirecting...."), window.location.href = $("#main-search").attr("href").match(/page=([0-9]+)/)[1];
})
This works and you can test it here: Search for the term dress -->

jQuery ui - datepicker prevent refresh onSelect

I'm using jQuery ui Datepicker to display a yearly inline calendar full of "special dates" (with colors).
This is to allow users to batch special dates by selecting a range and some other details.
$('#calendar').datepicker({
...
, onSelect: function (selectedDate, inst) {
$('.date_pick').toggleClass('focused');
if ($('.date_pick.end').hasClass('focused')) {
$('.date_pick.end').val('');
}
# inst.preventDefault() ? <- not a function
# inst.stopPropagation() ? <- not a function
# return (false) ? <- calendar refreshes anyway
}
...
});
I'm also using qtip to show the details on each date
My problem is when I click on the calendar, it reloads itself entirely, so I loose my qtips.
I'd prefer not to use live() with qtip because I don't like the behavior.
I'd also prefer that the calendar not refresh each time I click on it (but this does not seem possible anyway) but I would probably no longer be able to highlight my selection anymore.
Do you have a suggestion for my problems ?
I was having a similar problem. I was adding custom buttons to the bottom of the datepicker (using $(id).append), but when I would select a date the datepicker would refresh and destroy them.
This is the date selection function for the datepicker in the jquery-ui library:
_selectDate: function(id, dateStr) {
...
if (onSelect)
onSelect.apply((inst.input ? inst.input[0] : null), [dateStr, inst]);
...
if (inst.inline)
this._updateDatepicker(inst);
...
},
As you can see, the function first calls the onSelect event, and then calls _updateDatepicker (which is what redraws the form) if inst.inline is true.
This is my workaround to prevent the form from refreshing while maintaining the selection functionality:
$("#cal_id").datepicker({
onSelect: function(date, inst){
//This is the important line.
//Setting this to false prevents the redraw.
inst.inline = false;
//The remainder of the function simply preserves the
//highlighting functionality without completely redrawing.
//This removes any existing selection styling.
$(".ui-datepicker-calendar .ui-datepicker-current-day").removeClass("ui-datepicker-current-day").children().removeClass("ui-state-active");
//This finds the selected link and styles it accordingly.
//You can probably change the selectors, depending on your layout.
$(".ui-datepicker-calendar TBODY A").each(function(){
if ($(this).text() == inst.selectedDay) {
$(this).addClass("ui-state-active");
$(this).parent().addClass("ui-datepicker-current-day");
}
});
}
});
setting inst.inline to false inside the onselect won't work.
instead try something like
onSelect: function() {
$(this).data('datepicker').inline = true;
},
onClose: function() {
$(this).data('datepicker').inline = false;
}
I have almost the same problem, like some other people, I have some kind of a solution.... but it's not fair:
$('#calendar').datepicker({
...,
onSelect: function (selectedDate, inst)
{
myFunction(selectedDate, inst);
}
});
function myFunction(selectedDate, inst)
{
$('.date_pick').toggleClass('focused');
if ($('.date_pick.end').hasClass('focused')) {
$('.date_pick.end').val('');
}
inst.preventDefault(); # aa; works too, but writing aa; is going too far xD
}
It is not perfect, but works... I'll try to make it works just fine, till then...
EDIT: Solved adding:
<link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/themes/base/jquery-ui.css" rel="stylesheet" type="text/css"/>
If you just want to select a single day then you have to specify the Month and the Year in JQuery:
$(".ui-datepicker-calendar TBODY [data-month='"+inst.selectedMonth+"'][data-year='"+inst.selectedYear+"'] A").each(function(){
In the case of having some datepickers on the page Yozomiri example will fail. You should do:
onSelect: function(date, inst){
//This is the important line.
//Setting this to false prevents the redraw.
inst.inline = false;
//The remainder of the function simply preserves the
//highlighting functionality without completely redrawing.
//This removes any existing selection styling.
$(this).find(".ui-datepicker-calendar .ui-datepicker-current-day").removeClass("ui-datepicker-current-day").children().removeClass("ui-state-active");
//This finds the selected link and styles it accordingly.
//You can probably change the selectors, depending on your layout.
$(this).find(".ui-datepicker-calendar TBODY td").each(function(){
if ( $(this).find('a').text() == inst.selectedDay && $(this).data('month') == inst.selectedMonth ) {
$(this).find('a').addClass("ui-state-active");
$(this).addClass("ui-datepicker-current-day");
}
});
}
https://jsfiddle.net/g2bgbdne/3/

jquery-ui sortable | How to get it work on iPad/touchdevices?

How do I get the jQuery-UI sortable feature working on iPad and other touch devices?
http://jqueryui.com/demos/sortable/
I tried to using event.preventDefault();, event.cancelBubble=true;, and event.stopPropagation(); with the touchmove and the scroll events, but the result was that the page does not scroll any longer.
Any ideas?
Found a solution (only tested with iPad until now!)!
https://github.com/furf/jquery-ui-touch-punch
To make sortable work on mobile.
Im using touch-punch like this:
$("#target").sortable({
// option: 'value1',
// otherOption: 'value2',
});
$("#target").disableSelection();
Take note of adding disableSelection(); after creating the sortable instance.
The solution provided by #eventhorizon works 100%.
However, when you enable it on phones, you will get problems in scrolling in most cases, and in my case, my accordion stopped working since it went non-clickable. A workaround to solve it is to make the dragging initializable by an icon, for example, then make sortable use it to initialize the dragging like this:
$("#sortableDivId").sortable({
handle: ".ui-icon"
});
where you pass the class name of what you'd like as an initializer.
Tom,
I have added following code to mouseProto._touchStart event:
var time1Sec;
var ifProceed = false, timerStart = false;
mouseProto._touchStart = function (event) {
var self = this;
// Ignore the event if another widget is already being handled
if (touchHandled || !self._mouseCapture(event.originalEvent.changedTouches[0])) {
return;
}
if (!timerStart) {
time1Sec = setTimeout(function () {
ifProceed = true;
}, 1000);
timerStart=true;
}
if (ifProceed) {
// Set the flag to prevent other widgets from inheriting the touch event
touchHandled = true;
// Track movement to determine if interaction was a click
self._touchMoved = false;
// Simulate the mouseover event
simulateMouseEvent(event, 'mouseover');
// Simulate the mousemove event
simulateMouseEvent(event, 'mousemove');
// Simulate the mousedown event
simulateMouseEvent(event, 'mousedown');
ifProceed = false;
timerStart=false;
clearTimeout(time1Sec);
}
};
The link for the top-voted Answer is now broken.
To get jQuery UI Sortable working on mobile:
Add this JavaScript file to your project.
Reference that JS file on your page.
For more information, check out this link.

jquery tabs back button

This post talks about the problem that jQuery tabs is still having with the back button. What the customer needs is fairly simple - when they press back, they want to go back to what they were just looking at. But jQuery tabs loads the first tab, not the one that was selected when the user left the page.
I've read the accompanying link and it says "It is planned and Klaus is working on it whenever he finds the time."
Has anyone solved the back button problem with jQuery UI tabs?
Using the solution to the history problem easement posted, a dirty fix for the back button problem would be to periodically check the location.hash to see if it has changed, and if it has, fire the click event of the appropriate link.
For example, using the zachstronaut.com updated jQuery Tabs Demo, you could add this to the $(document).ready callback, and it would effectively enable the back button to switch tabs, with no more than a 500ms delay:
j_last_known_hash = location.hash;
window.setInterval(function() {
if(j_last_known_hash != location.hash) {
$('#tabs ul li a[href="'+ location.hash +'"]').click();
j_last_known_hash = location.hash;
}
}, 500);
Have you tired updating the browsers location as you switch tabs?
http://www.zachstronaut.com/posts/2009/06/08/jquery-ui-tabs-fix.html
if you had a class on your tab container that was tabContainer, to update the url when user clicks a tab, you could do this:
$(".tabContainer").tabs({
select: function(event, ui) {
window.location.hash = ui.tab.hash;
}
});
then, instead of firing click, you could use the tabs select method if you have some getIndexForHash method that can return the right tab number for the selected hash value:
var j_last_known_hash = location.hash;
window.setInterval(function() {
var newHash = location.hash;
if(j_last_known_hash != newHash) {
var index = getIndexForHash(newHash);
$('.tabContainer').tabs("select",index);
j_last_known_hash = newHash;
}
}, 100);
window.onhashchange = function () {
const $index = $('a[href="' + location.hash + '"]').parent().index();
$('.tabContainer').tabs('option', 'active', $index);
}

Resources