I\'m working on loading. I have div #loading
which is visible. And more divs #message
which are hidden. I have js function.
function lo
You cannot have same id twice in a document in order to select multiple elements group them by same Class rather than by id and then use the following to select them all.
document.querySelectorAll(".ClassName")
Or
document.getElementsByClassName(".ClassName");
Note that both methods returns a collection of all elements in the document with the specified class name, as a NodeList object.
ID
attribute must be unique. You can't use same ID multiple times on the page. If you like to use same key then use it as a class
or data-id
which can be same or differ.
You need to use unique ID's for your DOM elements. Try modify your code like this:
<script type="text/javascript">
function loading() {
setTimeout(function() {
document.getElementById("loading").style.display = "none";
var el = document.getElementsByClassName('message');
console.log(el);
$.each(el, function(i, item){
item.style.display = 'block';
});
}, 500, "fadeOut");
}
loading();
</script>
<style>
#loading {
display: block;
}
.message{
display: none;
}
</style>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="messages" onload="loading();">
<div id="loading">
...
</div>
<div class="message">
QWERTY
</div>
<div class="message">
123456
</div>
</div>
As the others have mentioned id
s are unique and can only be used once on a page, so use a class instead. Here I've used querySelectorAll to grab a static list of classes.
The other issue is that you seem to be trying to use jQuery to fade the elements out, but you're not using jQuery for anything else. I'm going to suggest you CSS transitions. They're easy to use, and you don't have the need of loading a huge library. Here I add new classes fadein
and fadeout
which (based on your code) increases/reduces the opacity of the specified elements to zero over three seconds.
function loading() {
setTimeout(function() {
// use a class for the loader too otherwise the transition
// won't work properly
const loader = document.querySelector('.loading');
loader.classList.add('fadeout');
// grab the elements with the message class
const messages = document.querySelectorAll('.message');
// loop over them and add a fadeout class to each
[...messages].forEach(message => message.classList.add('fadein'));
}, 500);
}
loading();
.loading {
opacity: 1;
}
.message {
opacity: 0;
}
.fadein {
transition: opacity 3s ease-in-out;
opacity: 1;
}
.fadeout {
transition: opacity 3s ease-in-out;
opacity: 0;
}
<div class="messages">
<div class="loading">
Loading
</div>
<div class="message">
QWERTY
</div>
<div class="message">
123456
</div>
</div>