Reputation: 21170
I'm trying to dynamically change the background of my page using the jquery waypoint plugin (which tells you when an element is at the top or bottom of the viewport). My HTML is simple - I have multiple headings with the id of #part1',
#part2' and so on and so forth. When part[x]
is at the top of the viewport, I want img[x]
to be displayed.
The following code works:
$("#part2").waypoint(function(event, direction) {
if (direction === 'down') {
$(".container").attr("id", "img2");
}
else {
$(".container").attr("id", "img2");
}
});
However, I have 18 'parts' and I don't want this code 18 times. I tried using a for
loop
like this:
var chapters = $("[id^='part']");
for (var i=1; i<=chapters.length; i++){
$("#part[i]").waypoint(function(event, direction) {
if (direction === 'down') {
$(".container").attr("id", "img[i]");
}
else {
$(".container").attr("id", "img[i]");
}
});
}
But again, not working. Is it possible to escape the selector with square brackets like I've done? If not, what's the correct way to achieve this?
Upvotes: 2
Views: 577
Reputation: 339955
Assuming the waypoint plugin is written correctly and handles multiple elements:
$("[id^='part']").waypoint(function(event, direction) {
$(".container").attr('id', this.id.replace('part', 'img'));
});
add direction checks as required.
I'm not familiar with this plugin but the key part is that you should be able to bind the waypoint plugin to multiple elements, and then within the event handler this
should be the element that triggered the event, whose ID is then just this.id
.
NB: just changing the ID on .container
wouldn't normally change the image on it, unless you've got a stack of CSS rules that look like:
#img1 { background-image: ... }
#img2 { background-image: ... }
...
However in that case you should use classes instead of IDs - it's much more normal for the ID of an element to be constant through its lifetime and for its CSS classes to change.
If .container
has no other CSS classes it would make sense to give it a fixed ID of container
instead and use a variant of the above code:
$("[id^='part']").waypoint(function(event, direction) {
$("#container").attr('class', this.id.replace('part', 'img'));
});
The constraint on not having any other CSS classes is that since class
can contain multiple values it's far simpler to just completely overwrite the class list than it is to remove the previous class (whatever that was) and then add the new one.
Upvotes: 4
Reputation: 24276
You can try it like this
for (var i=1; i<=chapters.length; i++){
$("#part" + i).waypoint(function(event, direction) {
if (direction === 'down') {
$(".container").attr("id", "img" + i);
}
else {
$(".container").attr("id", "img" + i);
}
});
}
instead of separate ids I would use css classes and doing like that you'll don't need a loop
Upvotes: 1
Reputation: 16743
Instead if using square brackets, why not:
$("#part" + i)
"img" + i
You then just select by id, and are creating the id dynamically.
Upvotes: 0