I’m showing a loading indicator while some external iframes are loaded with the following code:
<html>
<head>
<title>Loading iframe</title>
</head>
<script>
function loading_iframe(){
document.getElementById('loading_iframe').style.display = "none";
document.getElementById('loading').style.display = "";
document.getElementById('loading_iframe').onload = function(){
document.getElementById('loading').style.display = "none";
document.getElementById('loading_iframe').style.display = "";
}
}
</script>
<body>
<iframe id="loading_iframe" src="iframe.html" width="800" height="100"></iframe>
<div id="loading">Loading...</div>
<script>
loading_iframe();
</script>
</body>
</html>
Problem is I’m running around 50 mini iframes per page and I don’t fancy rewriting the code above to match each iframe id.
Is there a way I could match each iframe id with a regex, for example:
- loading_iframe1
- loading_iframe2
- loading_iframe3
Using plain vanilla JavaScript: Assuming the
loading_iframefunction performs the exact same action for every iframe, what you can do is have an array that contains the IDs of all iframes, then loop through that array.Alternatively, this version of
load_iframeswill work if you’re going to have a sequential number in your iframe IDs starting at 1 and ending at 50, and you don’t need to list all your iframe IDs in an array:Using jQuery: Give all iframes a CSS class such as
loading_iframe. You can then use jQuery to select all elements that have theloading_iframeclass.