ADuff
1
Hi,
I’m sure I’ve sat in front of a monitor for too long and my brain has simply shut down…
I’ve built a module which encorporates a JQuery script to toggle “More Info”.
{% require_js %}<script>$(".room-container-{{loop.index}} .more-details").click(function(){FUNCTION});</script>{% end_require_js %}
The issue is the script is only appearing in the footer for loop 1. So only the first read more function works. In the footer all I see is:
<script>$(".room-container-1 .more-details").click(function(){FUNCTION});</script>
No mention of .room-container-2, 3 etc. What’s the solution?
@ADuff , is the function within the loop?
@Oezcan , how would you solve for this?
Oezcan
4
Hello @ADuff and @dennisedson
I think you will need something like this.
var i;
for (i = 0; i < substr.length; ++i) {
// do something with `substr[i]`
}
or in ES2015+:
for (let i = 0; i < substr.length; ++i) {
// do something with `substr[i]`
}
Here are some other example:
https://www.sitepoint.com/jquery-each-function-examples/#:~:text=jQuery’s%20each()%20function%20is,arbitrary%20arrays%20and%20object%20properties.
I hope I could help.
Best regards,
Özcan
Indra
5
Hi @ADuff,
As @Oezcan is telling, it’s best to do a loop within your code without repeating your script multiple times.
This will improve your sitespeed and make your script more readable.
So your html sample will be:
<ul class="list">
<li class="item item-1"></li>
<li class="item item-2"></li>
<li class="item item-3"></li>
</ul>
So for example doing:
{% for row in rows %}
{% require_js %}
<script>
var item = document.querySelector('.list > .item-{{ loop.index }}');
item.addEventListener('click', function (event) {
// Do something...
});
</script>
{% end_require_js %}
{% endfor %}
You better do this inside the js tab:
var items = document.querySelectorAll('.list > .item');
items.forEach(function (item, index) {
item.addEventListener('click', function (event) {
// Do something...
});
});
Do you have a demo link for your code? This will help solving your problem.
ADuff
6
Hi,
I was able to use JQuery to achieve this, but essentially using your idea:
$('.room-container').each(function(){
$(this).on('click', '.more-details', function(){
// functions
});
});
Indra
7
@ADuff Great to here you have fixed your problem. If your problem is solved. Please mark your problem as solved 