JavaScript Utilities

The JavaScript utilities are a set of methods that can be used to simplify the development process.

Copy to Clipboard

Copy text to the clipboard by using the window.copyToClipboard(idOrText) method.

If you want to copy the innerHTML of an element, pass the element's ID as the argument. The ID must start with a # symbol.

If you pass an id and it's an <code>-tag or the element has the attribute data-html-decode, the innerHTML will be html-decoded. That means, symbols like &lt; will be converted to <.

1<x-button id="copy-btn">Copy</x-button>
2 
3@script
4<script>
5document.getElementById('copy-btn').addEventListener('click', function() {
6 window.copyToClipboard('Basic-Components for Livewire is awesome.');
7 // window.copyToClipboard('#copy-btn'); (Will copy the innerHTML of the element)
8 alert('Text copied to clipboard!');
9});
10</script>
11@endscript

Focus Input

Use window.focusInput(domElementOrId) to focus an input element and set the cursor to the end of the text.

1<!-- Input -->
2<x-input id="focus-input" value="Focus at the end" />
3 
4<!-- Button -->
5<x-button x-on:click="window.focusInput('#focus-input')">Focus</x-button>

Add Errors manually

You can change the state of any input element to an error state by using the window.addError(domElementOrId, message) method. Remove the error by using the window.removeError(domElementOrId) method.

1<x-input id="error-input" />
2 
3<x-button x-on:click="window.addError('#error-input', 'Add any error you want.')">Add Error</x-button>
4<x-button x-on:click="window.removeError('#error-input')">Remove</x-button>

Add Errors manually

You can change the state of any input element to an error state by using the window.addError(domElementOrId, message) method. Remove the error by using the window.removeError(domElementOrId) method.

Important: This will only add an error on the client-side, not in Livewire!

1<x-input id="error-input" />
2 
3<x-button x-on:click="window.addError('#error-input', 'Add any error you want.')">Add Error</x-button>
4<x-button x-on:click="window.removeError('#error-input')">Remove</x-button>

Disable / Enable Scrolling

If you want to disable scrolling on the body (e. G. for popups, modals, etc…), you can use the window.disableScrolling() and window.enableScrolling() methods. This method fixes the layout shift, which occurs when the browser scrollbar disappears.

1<x-button type="danger" x-on:click="window.disableScrolling(); toast.warning('Scrolling disabled.')">Disable Scrolling</x-button>
2<x-button type="success" x-on:click="window.enableScrolling(); toast.success('Scrolling enabled.')">Enable Scrolling</x-button>