Reputation: 1284
I'm trying to trigger a click on an element every x seconds. It's not the exact same element every time (depending on which tab a user has selected, it should click that tab), but they are all in the same container (with id #container
. The selected element has the class .selected
and gets that class when it has been clicked on by a user.
This is the code I have:
var feedContainer = $('#container');
window.setInterval(function () {
var selectedTab = feedContainer.find('.selected');
selectedTab.trigger('click');
}, 10000);
The problem is that between the timeouts, if a user clicks on another tab, this part doesn't pick up on that: var selectedTab = feedContainer.find('.selected');
. It just gets the one that was selected before, not the new one that has the class. How do I avoid that?
It works fine if I do the entire selection in the timer each time (var selectedTab = $('#container .selected');
). It seems to be somehow caching the results from the last run.
Why is this and how do I force it to fetch the correct element?
Upvotes: 1
Views: 821
Reputation: 22949
You are already caching the element yourself by doing this:
var feedContainer = $('#container');
If the contents change after you assign it to the variable then that variable won't get updated with the new contents automagically.
Just use it like this $('#container');
directly whenever you want to do operations on it.
Upvotes: 4
Reputation: 2552
I'd do it like this. Short, to the point and no variable assigning thus no caching.
window.setInterval(function () {
$('#container .selected').trigger('click');
}, 10000);
Upvotes: -1
Reputation: 9508
window.setInterval(function () {
var selectedTab = $('#container').find('.selected');
selectedTab.trigger('click');
}, 10000);
As container is not changed above is proposed.
Upvotes: 0
Reputation: 665
First of all, an ID should ideally be used to identify a "single" element, not multiple elements. Changing that would help you out by spreading the elements with the same name using a "class" identifier. Changing that might help you out a lot.
Upvotes: -1
Reputation: 2351
What you're doing is that in the beginning, you gather some elements that match the selection (using $('#container')
) but later on, you change the content of #container
which is not reflected in the jQuery object in feedContainer
. Simply get the container on each iteration.
window.setInterval(function () {
var feedContainer = $('#container');
var selectedTab = feedContainer.find('.selected');
selectedTab.trigger('click');
}, 10000);
Upvotes: 0