I have different headers that I would like to loop through based on a timer which should be executed every time a page loads. Currently what I have works one time but then stops after it changes the header the first time. I am not very good with javascript and would appreciate it if someone could point me in the right direction.
Below is what I have in place currently.
In lib/Rotator.rb:
class Rotator
def self.header_rotator(number)
partials = ["header", "header2", "header3", "header4", "header5"]
random_header = partials[number]
return random_header
end
end
Then in the header section of application.html.haml I have:
var start_rotate = setTimeout(rotate, 5000);
function rotate() {
remote_function(:url => {:action})
$("#header").replaceWith('#{escape_javascript( render :partial => "shared/#{Rotator.header_rotator(rand(5))}")}')
start_rotate = setTimeout(rotate, 5000);
}
As I said this works fine but only rotates one time then stops.
Any help would be greatly appreciated!
This is less about js and more about understanding what is running where and when.
If you look at the HTML that is being rendered things should become clearer. That call to
escape_javascript,renderhappens precisely once: when that string gets interpolated during the rendering of the main page load. So the second (and third, fourth, fifth…) times rotate() runs it is replacing the header with exactly the same HTML.Assuming you are using jquery, the load method can do this:
Don’t forget to render without the layout when you respond to this request.
Lastly, are you sure you want to use Ajax at all? You could just load all the header variants up front and use JavaScript to show them in turn. (there are a number of jquery cycle or slideshiw plugins that do precisely this)