We already have <button x-on:click="foo = 'bar'"></button> to add click event to the button element.
Let say I have a reading content with multiple paragraphs
<div class="content">
<p id="p1">Paragraph 1 <strong>Not this</strong></p>
<p id="p2">Paragraph 2 <div class="more">Also not this</div></p>
<p id="p2">Paragraph 3 <ilatic>Include this</italic></p>
</div>
How do I attach events to selected element of my choice. If it has not already implemented, I do want to work on it but my javascript knowledge is limited, I may not make it efficient enough for this case.
You'll have to clarify the question a little bit. I'm sorry I don't understand what you're looking for. Thanks.
@calebporzio I'm sorry if it was confusing.
So I want to add click event listener to all the <p> elements inside div.content. However I want to define the event just once, but apply to all children <p>.
It is like the Jquery $('div.content p').on('click', () => ...);
Have we had this yet?
You can do what you want in x-init handler
<div x-data="scope()" x-init="addListeners()" class="content">
<p id="p1">Paragraph 1 <strong>Not this</strong></p>
<p id="p2">Paragraph 2 <span class="more">Also not this</span></p>
<p id="p3">Paragraph 3 <span>Include this</span></p>
</div>
function scope(){
return {
addListeners(){
this.$el.querySelectorAll('p').forEach(el => el.addEventListener('click',(e)=>console.log(el)))
}
};
}
Thank you @rzenkov x-init solved my problem. I didn't figure it out.
:thinking: Thinking of this, wouldn't it be better if you turn this list of paragraphs to a for loop? @baoanhng That way you will need to add the event a single time inside the loop. Although both ways work efficiently.
馃 Thinking of this, wouldn't it be better if you turn this list of paragraphs to a for loop? @baoanhng That way you will need to add the event a single time inside the loop. Although both ways work efficiently.
It works, but depends on your case. I need to pull multiple paragraphs from saved html in database, so I cannot use for loop there, and it won't be efficient. It is also syntactically ugly if you have thousands of paragraphs.
@baoanhng You're right馃槄. That makes sense now. Pulling from a database can make things more frustrating sometimes.
Most helpful comment
You can do what you want in x-init handler