Skip to content

Instantly share code, notes, and snippets.

@rolandtoth
Created November 3, 2018 23:56
Show Gist options
  • Save rolandtoth/ce3ca09ac120a9dac05bb019f0a69ee0 to your computer and use it in GitHub Desktop.
Save rolandtoth/ce3ca09ac120a9dac05bb019f0a69ee0 to your computer and use it in GitHub Desktop.
Focus field if hash contains a field name, or focus previously edited field (ProcessWire admin)
/**
* Focus field on page edit screen if hash contains "field=fieldName",
* or focus previously edited field using sessionStorage.
* Eg. /admin/page/edit/?id=1051#focus=title
*/
// need to set before document.ready()
var focusFieldNameFromHash = getFocusFieldNameFromHash();
$(document).ready(function () {
initFocusField();
});
function initFocusField() {
var editedPageId = $("#PageIDIndicator").text();
InputfieldFocus(getFocusField(focusFieldNameFromHash, editedPageId));
setupFocusFieldEventListeners(editedPageId);
}
/**
* Event listeners for field focus.
*/
function setupFocusFieldEventListeners(pageId) {
$(document).on("change", "#ProcessPageEdit .InputfieldContent input, #ProcessPageEdit .InputfieldContent textarea, #ProcessPageEdit .InputfieldContent select", function () {
sessionStorage.setItem("focusField", JSON.stringify({
page: pageId,
field: $(this).parents("li.Inputfield").first().attr("id").replace("wrap_Inputfield_", "")
}));
});
}
/**
* Get focus field name set in location.hash, then remove.
* @param {string} editedPageId
* @returns void
*/
function getFocusFieldNameFromHash() {
var fieldName = "",
identifier = "focus=",
hashValues;
if (location.hash.indexOf(identifier) !== -1) {
hashValues = location.hash.split(identifier);
fieldName = hashValues[1];
location.hash = location.hash.replace(identifier + fieldName, ""); // remove from hash
}
return fieldName;
}
/**
* Get the field (wrapper) to set focus to.
*
* @param {string} fieldName
* @param {string} pageId
* @returns jQuery object
*/
function getFocusField(fieldName, pageId) {
if (fieldName === "" && location.href.indexOf("id=" + pageId !== 0)) {
focusFieldSettings = sessionStorage.getItem("focusField");
if (focusFieldSettings) {
var settings = JSON.parse(focusFieldSettings),
field = settings.field,
page = settings.page;
if (field && page) {
fieldName = field;
}
}
}
return $("#wrap_Inputfield_" + fieldName);
}
@rolandtoth
Copy link
Author

Great, thanks, let me know if you find something. I haven't spent too much time deciding whether the "#focus=FIELDNAME" is the best solution for this, suggestions are welcome.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment