Reputation: 1
I have really simple question for someone with js skill. I have elements with numbered ids like: pictureframe-0, pictureframe-1, pictureframe-3.... and I want to make universal js based on this below:
$(document).ready(function() {$("#pictureframe-0").hover(function() {
$("#cover-0").slideDown(500);
}, function() {
$("#cover-0").slideUp(500);
});
});
where "0" will variate. Thank you for solution.
I know, when I duplicate this script like 20x times with numbers 1-20 it works separetly: pictureframe-0 will activate cover-0, pictureframe-1 will activate cover-1 etc.
Code is like this:
<div class="pictureframe">
<div class="cover">this is cover</div>
</div>
Upvotes: 0
Views: 34
Reputation: 1252
Try changing your selector. If you use a prefix attribute selector, you could select leaving the rest of the id as a wildcard:
$(document).ready(function() {$("[id^=pictureframe-]").hover(function() {
$("#cover-" + this.id.slice(-1)).slideDown(500);
}, function() {
$("#cover-" + this.id.slice(-1)).slideUp(500);
});
});
UPDATE: As I mentioned in the comments, yes, you could also do this using a for
loop, though personally I prefer the first way:
$(document).ready(function() {
for (let i = 0; i < $("[id^=pictureframe-]").length; i++) {
$("#pictureframe-" + i).hover(function() {
$("#cover-" + i).slideDown(500);
}, function() {
$("#cover-" + i).slideUp(500);
});
}
});
Upvotes: 2