Created
May 8, 2021 15:04
-
-
Save simonw/ce890736d333fee55268d528a1141136 to your computer and use it in GitHub Desktop.
Pre-fill the slug form field based on the title, but stop doing that if the slug is manually edited
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function slugify(s) { | |
return s | |
.toLowerCase() | |
.replace(/[^-\w\s]/g, "") // remove non-alphanumerics | |
.trim() | |
.replace(/[-\s]+/g, "-") // spaces to hyphens | |
.replace(/-+$/g, ""); // trim trailing hyphens | |
} | |
function slugAutoFill() { | |
var titleInput = document.querySelector('#id__save-title'); | |
var slugInput = document.querySelector('#id__save-slug'); | |
if (!titleInput) { | |
return; | |
} | |
let slugManuallyEdited = false; | |
slugInput.addEventListener('change', () => { | |
slugManuallyEdited = !!slugInput.value; | |
}); | |
function titleEdited() { | |
if (slugManuallyEdited) { | |
return; | |
} | |
slugInput.value = slugify(titleInput.value); | |
} | |
titleInput.addEventListener('change', titleEdited); | |
titleInput.addEventListener('focus', titleEdited); | |
titleInput.addEventListener('keyup', titleEdited); | |
} | |
slugAutoFill(); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<p><label>Title <input type="text" id="id__save-title"></label> | |
<p><label>Slug <input type="text" id="id__save-slug"></label> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment