Created
December 18, 2015 04:07
-
-
Save traviswaelbro/a98cfd2fb74d212cf03e to your computer and use it in GitHub Desktop.
This generic JavaScript function allows the user to easily add a function call inline, without having to do a lot of work. It can use any trigger, such as onchange or onclick, to launch a custom action, like updating its own content or the content of another element. I will update to cover more situations later, as well as creating a jQuery vers…
This file contains hidden or 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
"use strict"; | |
function change(idToChange, valueToChange, newValue) { | |
var element = document.getElementById(idToChange); | |
switch(valueToChange) { | |
case 'href': | |
element.href = newValue; | |
break; | |
case 'innerHTML': | |
element.innerHTML = newValue; | |
break; | |
default: | |
console.log("Sorry, this function doesn't support changing " + valueToChange + " at this time."); | |
break; | |
} | |
} | |
// Examples: | |
// | |
// On change of a dropdown | |
// This example assumes each select option is set like this: | |
// <option value="medium" data-short="0.48" data-medium="$4.37" data-long="$8.40">Medium</option> | |
// | |
// (change this element's... attribute... to this...) | |
// (this select's selected child's value for {variable}) | |
// onchange="change("price1", "innerHTML", document.getElementById(this.id).children[this.selectedIndex].getAttribute("data-short")); | |
// change("price2", "innerHTML", document.getElementById(this.id).children[this.selectedIndex].getAttribute("data-medium")); | |
// change("price3", "innerHTML", document.getElementById(this.id).children[this.selectedIndex].getAttribute("data-long"));" | |
// | |
// You can add as many change function calls to the onchange value as you would like | |
// To update an image: | |
// change("image-id", "href", "new/path/to/imaage.jpg"); | |
// | |
// In most cases it makes sense to keep track of all related data in data-{description} tags, like above or data-image, etc. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment