I am working on a simple example, if a user clicks on element then all the elements above it should have a class and all elements below it should not have any class applied to them.
Here is my code:
<style>
p {
background-color: skyblue;
text-align: center;
color: white;
width: 50px;
height: 50px;
cursor: pointer;
}
.active {
color: red;
background-color: black;
}
</style>
<div id="divid">
<p id="p1">one</p>
<p id="p2">two</p>
<p id="p3">three</p>
<p id="p4">four</p>
</div>
<script>
function myFunction(index) {
for (let i = 0; i <= index; i++) {
paragraphs[i].classList.add('active');
}
for (let i = index; i < paragraphs.length; i++) {
paragraphs[i].classList.remove('active');
}
}
var paragraphs = document.querySelectorAll("p");
console.log(paragraphs);
for(var j=0;j<paragraphs.length; j++) {
paragraphs[j].addEventListener("click", myFunction(j));
}
</script>
When I run this code it is directly setting the class active to first 3 paragraph tags which is not the expected behaviour, and also the click function is not working.
If I replace the javascrip code with inline function, it is working without issues.
var paragraphs = document.querySelectorAll("p");
console.log(paragraphs);
for(var j=0;j<paragraphs.length; j++) {
paragraphs[j].addEventListener("click", (function(index) {
return function() {
for (let i = 0; i <= index; i++) {
paragraphs[i].classList.add('active');
}
for (let i = index; i < paragraphs.length; i++) {
paragraphs[i].classList.remove('active');
}
}
})(j));
}
Can you please help me what is the issue with my code if I place it as external function?
with inline functionWhat do you mean? The second snippet doesn't look like an inline function, it looks like a standard script, which there's nothing wrong with. It is in the Javascript and not the HTML, right?