Using require_js in a loop in a module

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?

Hi, yes it is in a loop.

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

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.

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
});
});

@ADuff Great to here you have fixed your problem. If your problem is solved. Please mark your problem as solved :blush: