Created
February 23, 2022 10:21
-
-
Save percysnoodle/aa843cb942f8be1b4fd51ec36bba8e8a to your computer and use it in GitHub Desktop.
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
import { Controller } from "@hotwired/stimulus"; | |
export default class ApplyCssController extends Controller { | |
static targets = ["element"]; | |
static values = { | |
selector: String, | |
onConnect: { type: Boolean, default: false }, | |
}; | |
static classes = ["add", "remove"]; | |
connect() { | |
if (this.onConnectValue) { | |
this.apply(); | |
} | |
} | |
apply() { | |
let elements; | |
if (this.hasElementTarget) { | |
elements = this.elementTargets; | |
} else if (this.hasSelectorValue) { | |
elements = document.querySelectorAll(this.selectorValue); | |
} | |
elements.forEach((element) => { | |
if (this.hasAddClass) { | |
this.addClasses.forEach((cssClass) => element.classList.add(cssClass)); | |
} | |
if (this.hasRemoveClass) { | |
this.removeClasses.forEach((cssClass) => element.classList.remove(cssClass)); | |
} | |
}); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Example of use:
or: