I am trying to go from a Bootstrap 4 framework to a Bootstrap 5 framework - which means moving away from jQuery.
I have several elements on a page all with the classname .info-box and an attribute as follows
<div class="card card-icon col-md-4 info-box" data-href="file.php?e=AA">
<div class="card card-icon col-md-4 info-box" data-href="file.php?e=BB">
<div class="card card-icon col-md-4 info-box" data-href="file.php?e=CC">
When the user clicks on the card element, the intent is to open the link. The following JS gets close, but it links all three card elements to the Last Link (=CC)
var elements = document.getElementsByClassName('info-box');
for(var i = 0; i < elements.length; i++) {
var element = elements[i];
var newLoc= elements[i].getAttribute('data-href');
element.onclick = function() {window.location = newLoc;}
}
Can you suggest a way to make the correct data-href attribute link to the correct card?
I think I found a solution .. Does this seem efficient?
<script>
var elements = document.getElementsByClassName('info-box');
[].forEach.call(elements, function(elements) {
elements.onclick = function() {
var newLoc= this.getAttribute('data-href');
window.location = newLoc;
}
})
</script>
Found it over here .. javascript: call function by classname
var elements = document.getElementsByClassName('info-box');
for(let i = 0; i < elements.length; i++) {
let element = elements[i];
let newLoc= elements[i].getAttribute('data-href');
element.onclick = function() {window.location = newLoc;}
}
Use let instead of var.
The problem is that var does not have block scope, which means in your case the variable newLocis defined globally. Use let instead of var.
I think I found a solution .. Does this seem efficient?
Your solution should also work fine, because it wraps the var newLoc in a function, which limits its scope. Using let is generally good practise though.