I am working on creating some dynamic content updating scripting and decided to make a jquery function that can be chained in order to be able to apply my code to multiple functions in a given page. Part of this, however, created some problems and I am hoping one of the more skilled js developers here might be able to help me out.
Basically I have the following JS code that will dynamically update content in the indicated element.
$.fn.updatecontent = function(vars){
id=$(this).children(":first").attr("id");
var i=0;
change_contents = function(){
$("#"+id).fadeOut('slow', function(){
$(this).html(vars.data[i]);
$(this).fadeIn('slow');
});
if(i+1 < vars.data.length){
i++;
}else{
i=0;
}
};
setInterval(change_contents,vars.interval);
};
$(document).ready(function(){
$("#button_one").updatecontent({
interval: 5000,
data: ["button 1 main content", "button 1 secondary content"]
});
$("#button_two").updatecontent({
interval: 7000,
data: ["button 2 main content", "button 2 secondary content"]
});
});
My demo html looks like this
<section id="main_panel">
<section id="button_one" class="button">
<div id="button_one_content">button 1 main content</div>
</section>
<section id="button_two" class="button">
<div id="button_two_content">button 1 main content</div>
</section>
</section>
The problem is, if I call this code on one element only it works fine, on the element I expect ( http://jsfiddle.net/C6h8s/10/ ). However, if I run it on two elements then it only updates the second element but with all 4 strings (I would link to this jsfiddle but I cant post more than two links at the moment and the first and last are the more important. Please uncomment the second call to see the wrong functionality). The problem appears to be with the setInterval function, because if I remove the call for that and call the function on both elements it will update both elements appropriately, though only one time due to the fact that I am no longer causing it to loop indefinitely over the available strings ( http://jsfiddle.net/C6h8s/11/ ).
Any input anyone might have on how to work around this problem would be greatly appreciated.
The second time you call the function, it overwrites
id, since it is global. Usevar:DEMO