Reputation: 1
I am making a website in which there are around 20 modals (bootstrap) on a single page. Each modal contains an iframe which plays a youtube video.
Till now, all I did was created all 20 modals with div #myModal1, #myModal2 ........... #myModal20.
Then, I looked for a javascript code which can stop a youtube video when I close the modal and found the jquery code (shown below)
jQuery(".modal-backdrop, #myModal2 .close, #myModal2 .btn").on("click", function() {
jQuery("#myModal2 iframe").attr("src", jQuery("#myModal2 iframe").attr("src"));
});
The above code stops the youtube video when I close the modal with div #myModal2.
Now, since there are 20 modals and I wrote the same code for all of them just changing #myModal3, #myModal4,...........and so on.
Can I do the same using for loop (I am new to this javascript) but I tried something and it is not working.
The code I wrote was:
for(i=1; i<21; i++) {
var modal = "#myModal"+i;
jQuery(".modal-backdrop, " + modal +" .close, " + modal +".btn").on("click", function() {
jQuery(modal+" iframe").attr("src", jQuery(modal+" iframe").attr("src"));
});
}
It is not working.
Upvotes: 0
Views: 171
Reputation: 1
I changed my code a little bit by defining immediately-invoked function expression IIFE.
I had the jquery to stop the youtube video on clicking close button and just needed to input a variable which will work for all the modals so I added [id^='myModal] to the input that is i which the function takes to execute the code.
(function(i) {
//Defining a variable "modal" equating it to "[id^='myModal']"
//'i' will be any modal having id starting with **myModal**
var modal = i;
//Jquery to stop the youtube video
jQuery(".modal-backdrop, " + modal +" .close, " + modal +".btn").on("click", function() {
jQuery(modal+" iframe").attr("src", jQuery(modal+" iframe").attr("src"));
});
}
("[id^='myModal']"));
Upvotes: 0
Reputation: 36703
Essentially you do not need a for loop for this, just bind a click handler to [id*='myModal']
which are all the elements having id starting with myModal
jQuery("[id*='myModal'] .close, [id*='myModal'] .btn").on("click", function() {
var that = this;
jQuery(that).find("iframe").attr("src", jQuery(that).find("iframe").attr("src"));
});
And now clicking on the backdrop should stop all the videos
jQuery(".modal-backdrop").on("click", function() {
jQuery([id*='myModal']).find("iframe").attr("src", jQuery([id*='myModal']).find("iframe").attr("src"));
});
Why your code is not working because the value of i
is constantly changing and is not preserved per click handler.
To make it work you should use IIFE.
Upvotes: 0