Reputation: 11
This is my livewire component where i want to use Jquery: \resources\views\livewire\search.blade.php
<div>
<h1 id="id">Test</h1>
<script>
$('#id').css("background-color", "red");;
</script>
</div>
This is my view: \resources\views\components\sections\search.blade.php
@livewire('forms.search')
This is my app.js: \resources\js\app.js
import $ from 'jquery';
window.$ = $;
\resources\views\components\sections\search.blade.php
<h1 id="id">Test</h1>
<script>
$('#id').css("background-color", "red");;
</script>
Upvotes: 0
Views: 5008
Reputation: 41
use this structure:
document.addEventListener('livewire:load', () => {
Livewire. Hook('message. Received', (message, component) => {
(function($){"use strict";
$.fn.counterUp=function(options)…)(jQuery);
});
});
also you can comment hook when your jQuery code not working
Upvotes: 0
Reputation: 1
I have recently found the solution
Use the following code for your css update:
<script>
$(document).find('#id').css("background-color", "red");
</script>
Upvotes: 0
Reputation: 71
jquery must added first then used, so in component you can't use this way because component in the middle of page, but you can use with DOMContentLoaded event like this:
<script>
document.addEventListener('DOMContentLoaded',function(){
$('#id').css("background-color", "red");
})
</script>
if you want run this script by each render, you must use livewire events, for example this below run the script in each update that livewire make:
document.addEventListener("DOMContentLoaded", () => {
Livewire.hook('element.updated', (el, component) => {
$('#id').css("background-color", "red");;
})
});
of course in this example you can't see the result difference.
see all livewire's hooks in their site: https://laravel-livewire.com/docs/2.x/lifecycle-hooks#js-hooks
Upvotes: 0
Reputation: 81
You can add the jquery js file from cdn, into your "app.blade.php" file. Like this:
<script src="https://code.jquery.com/jquery-3.6.4.min.js" ...
@livewireScripts
</body>
Upvotes: 0
Reputation: 29
There are two options for this. you can do it first by giving wire:ignore to the parent tag of the livewire blade. and the second option :
Add this code inside Livewire's render function
$this->dispatchBrowserEvent('jquery');
and then run it like this
window.addEventListener('jquery', event => {
$('#id').css("background-color", "red");;
});
Additionally, make sure to run this command
npm run watch
After that, make sure to include the public/js/app.js file in the blade file
and
@livewireScripts
</body>
Make sure the code is written
Upvotes: 3