Created
October 9, 2020 11:33
-
-
Save Akjosch/dd606c80b94bff4af574f3e2c50fa808 to your computer and use it in GitHub Desktop.
Image-with-replacement for SugarCube
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
/** | |
* Usage: | |
* <<animg source.jpg class imageclass class anotherclass id image42 replacement.jpg>> | |
*/ | |
Macro.add("animg", { | |
handler() { | |
if(this.args.length === 0) { | |
return this.error("No image source given."); | |
} | |
var src = this.args[0] | |
var classes = []; | |
var id = null; | |
var replacement = null; | |
/* parse arguments - for now just "class" and "id" */ | |
for(var i = 1; i < this.args.length; ++ i) { | |
switch(this.args[i]) { | |
case "class": | |
if(this.args.length === i + 1) { | |
return this.error("No class given after 'class' argument."); | |
} | |
classes.push(this.args[++ i]); | |
break; | |
case "id": | |
if(id) { | |
return this.error("Multiple IDs found."); | |
} | |
if(this.args.length === i + 1) { | |
return this.error("No ID given after 'id' argument."); | |
} | |
id = this.args[++ i]; | |
break; | |
default: | |
if(replacement) { | |
return this.error("Multiple replacement URLs found."); | |
} | |
replacement = this.args[i]; | |
break; | |
} | |
} | |
var img = document.createElement("img"); | |
if(id) { | |
img.id = id; | |
} | |
if(classes.length > 0) { | |
classes.forEach(function(cls) { | |
img.classList.add(cls); | |
}); | |
} | |
if(replacement) { | |
img.addEventListener("error", function listener() { | |
img.src = replacement; | |
/* avoid endless loops in case replacement doesn't exist either */ | |
img.removeEventListener("error", listener); | |
}); | |
} | |
img.src = src; | |
this.output.appendChild(img); | |
} | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment