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, render happens 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:
$('#header').load('/some/server/path')
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)
Related
I have two Javascript files, both setup to generate an image from base64. The first script, called static.js looks like this.
var element = new Image();
element.src = "data:image/png;base64,..."
document.body.appendChild(element);
I can embed the script into my website using the following code and the image appears with no issues. (To see the full code, including the base64, go here)
<body>
<script src="./static.js"></script>
</body>
Similarly, I have a second script that I found on CodePen by takashi that converts a base64 image into an animated glitch. I was able to take that code and modify it using the same base64 image as the static code but with the glitch (apologies, but the code is really long even without my base64 image so I just included the link). The code for my image can be seen here. Note that while CodePen shows the HTML and Javascript on the same page, I broke mine out into separate files.
Again, if I embed the script into the webpage, it works with no issues.
<body>
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.5.7/p5.min.js"></script>
<script src="./glitch.js"></script>
</body>
The issue I have is that neither code has a dedicated javascript function() attribute, so the only way they work is if I embed the code as indicated above. Using the static image for brevity, if I add a dedicated function:
function isStatic() {
var element = new Image();
element.src = "data:image/png;base64,..."
document.body.appendChild(element);
}
and then try a callback,
<body>
<script src="./static.js">
isStatic();
</script>
</body>
the image does not appear on the webpage any longer. The same happens on the glitched image when I try to wrap the whole script into a function and then try a callback.
The main reason I was trying to turn each JS file into functions is so that I could combine the two into one file (which I did), and then using an embedded script like
<script>
setInterval(function(isStatic) {
// This will be executed every 9 seconds
}, 9000);
setInterval(function(isGlitch) {
// This will be executed every 2 seconds
}, 2000);
</script>
to create an image that switches from static to glitched, and then back again.
Since I was not able to successfully turn each JS file/script into it's own function, what I am trying to figure out is if there is a better way to combine my Static and Glitch JS scripts into one, or if there is a way that I can set the webpage to call each script file individually in such a way that creates a loop of the static and glitched images switching back and forth.
I have scoured the Google-webs looking for anything that describes what I am trying to do visually, but have absolutely nothing to show for it but a whole heap of scripts on various ways to make text and/or images glitch (just not how to make them start out static and then glitch randomly). Essentially what I would like to do with my two scripts is
- run static image (script or call) for *x* seconds (120-180 seconds)
- run glitched image (script or call) for *x* seconds (3-5 seconds)
- reset (loop) the sequence
in order to create the appearance of a single image that seems to randomly glitch for unknown reasons.
Edited answer after your clarifying comment:
Your code uses a library called p5, which is controlling your animation timing, so my previous answer is irrelevant. If you just want to change how often the glitch occurs, you already have almost everything you need. The glitch.js file already has a flag to turn the glitch on and off (this.throughFlag). And, it already has a slight random delay between glitches on line 226:
setTimeout(() => {
this.throughFlag = true;
}, floor(random(40, 400)));
The second parameter to setTimeout controls how long to wait beofre setting this.throughFlag to true (and thus starting to glitch again).
You just need to make this number longer. To do so, you want to make the time on the timeout longer, ie by multiplying it by some constant, which I'll call delayFactor.
const delayFactor = 10;
setTimeout(() => {
this.throughFlag = true;
}, delayFactor * floor(random(40, 400)));
See it in action here.
I've created this code to print data from an iFrame
function (data) {
var frame = $("<iframe>", {
name: "iFrame",
class: "printFrame"
});
frame.appendTo("body");
var head = $("<head></head>");
_.each($("head link[rel=stylesheet]"), function (link) {
var csslink = $("<link/>", { rel: "stylesheet", href: $(link).prop("href") })
head.append(csslink);
;});
frame.contents().find("head")
.replaceWith(head);
frame.contents().find("body")
.append(this.html());
window.frames["iFrame"].focus();
window.frames["iFrame"].print();
}
This creates an iFrame, adds a head to where it sets all the css links that are needed for this website. Then it creates the body.
Trouble is, the styling won't get applied to the print, unless I break at line frame.contents().find("head").replaceWith(head), which means that something in that part is running asynchronously.
Question is, can I somehow get the code to wait for a short while before running that line, or is there perhaps another way to do this? Unfortunately I'm not all that familiar with iFrames, so I have no clue what it's trying to do there.
This turned out to be a real hassle. I've always been reluctant to using iframes, but since there are many resources saying that using an iframe for printing more stuff than what's on the screen, we figured we'd give it a try.
This was instead solved by putting the data inside a hidden div which then was shown before a window.print(). At the same time, all other elements on the page were given a "hidden-print" class which is a class we're already using to hide elements for prints.
This might not be as elegant for the user (The div will show briefly before the user exits the print dialogue), but it's a way more simpler code to use and manage.
I think you could / should move the last focus() and print() calls to a onload handler for the iframe, to get it to happen after styles are loaded and applied.
I've just run into the same issue and did the following:
setTimeout(() => {
window.frames["iFrame"].focus();
window.frames["iFrame"].print();
}, 500)
This appears to have sorted it for me. I hate using timeout and the length is guess work at best but as it's not system critical it's something I can run with for now.
I've been attempting to make an infinite (well semi-infinite) scroll that feeds itself from hard-coded divs (because I don't know any back-end languages yet). My research has turned up a ton of great jQuery for infinite scrolls, but they are all meant to be used with a database, not hard-coded content.
What I'm trying to achieve, ultimately, is an infinite scroll that starts by loading X div into the DOM, and as the user reaches the bottom of the page, loads X more divs, and repeats until no more divs are left to load.
Do any of you know of some good or relevant scripts or any fiddles that may help me? Part of my issue is that I'm still in that learning curve of JS; I often understand what's going on when I look at a script but I still have a hard time writing my own from scratch.
Any help or direction is appreciated. Thanks in advance!!
Based on the code here: Alert using Jquery when Scroll to end of Page
Create a new <div> element when you reach the bottom of the page
$(window).scroll(function() {
if (document.documentElement.clientHeight + $(document).scrollTop() >= document.body.offsetHeight)
{
$('body').append('<div></div>');
}
});
Your HTML needs to be stored somewhere and if you have enough of it to think about infinite scrolling you probably don’t want to load it all with the initial request, so let’s say each “post” is stored in an individual HTML file on your server: /posts/1.html. And you want to append those to a div in your main document: <div id="posts"></div>.
You need a method to download a given post and append it to your div:
function loadPost (id) {
$.get('/posts/'+id+'.html').done(function (html) {
$('#posts').append(html);
});
}
Now you need a way to trigger loadPost() when you scroll to the bottom of the page. This example uses jQuery Waypoints to call a handler function when the bottom of the div comes into view:
var currentPost = 1;
$('#posts').waypoint({
offset: 'bottom-in-view',
handler: function () {
loadPost(currentPost++);
}
});
I have div with vertical scroll bar. Div is being updated dynamically via ajax and html is inserted using jQuery's .html method.
After div is updated scroll bar returns to top and I am trying to keep it in the previous position.
This is how I'm trying it:
var scrollPos = $('div#some_id').scrollTop(); //remember scroll pos
$.ajax({...
success: function(data) {
$('div#some_id').html(data.html_content); //insert html content
$('div#some_id').scrollTop(scrollPos); //restore scroll pos
}
});
This fails. My best guess is that it is failing due to inserted html not rendered (ie. no scroll).
For example this works.
setTimeout(function(){
$('div#some_id').scrollTop(scrollPos);
}, 200);
But this is dirty hack in my opinion. I have no way of knowing that some browsers won't take more then these 200ms to render inserted content.
Is there a way to wait for browser to finish rendering inserted html before continuing ?
It's still a hack, and there really is no callback available for when the HTML is actually inserted and ready, but you could check if the elements in html_content is inserted every 200ms to make sure they really are ready etc.
Check the last element in the HTML from the ajax call:
var timer = setInterval(function(){
if ($("#lastElementFromAjaxID").length) {
$('div#some_id').scrollTop(scrollPos);
clearInterval(timer);
}
}, 200);
For a more advanced option you could probably do something like this without the interval, and bind it to DOMnodeInserted, and check if the last element is inserted.
I will just like to point out one difference here: One thing, is when the .html() have completed loading, but the browser actually render the content is something different. If the loaded content is somewhat complex, like tables, divs, css styling, images, etc - the rendering will complete somewhat later than all the dom ellements are present on the page. To check if everything is there, does not mean the rendering is complete. I have been looking for an answer to this by myself, as now I use the setTimeout function.
Such callback does not exists because .html() always works synchronously
If you are waiting for images loading, there's one approach https://github.com/desandro/imagesloaded
I am trying to load Skyscanner API dynamically but it doesn't seem to work. I tried every possible way I could think of and all it happens the content disappears.
I tried console.log which gives no results; I tried elements from chrome's developers tools and while all the content's css remains the same, still the content disappears (I thought it could be adding display:none on the html/body sort of). I tried all Google's asynch tricks, yet again blank page. I tried all js plugins for async loading with still the same results.
Skyscanner's API documentation is poor and while they offer a callback it doesn't work the way google's API's callback do.
Example: http://jsfiddle.net/7TWYC/
Example with loading API in head section: http://jsfiddle.net/s2HkR/
So how can I load the api on button click or async? Without the file being in the HEAD section. If there is a way to prevent the document.write to make the page blank or any other way. I wouldn't mind using plain js, jQuery or PHP.
EDIT:
I've set a bounty to 250 ontop of the 50 I had previously.
Orlando Leite answered a really close idea on how to make this asynch api load although some features doesn't work such as selecting dates and I am not able to set styling.
I am looking for an answer of which I will be able to use all the features so that it works as it would work if it was loading on load.
Here is the updated fiddle by Orlando: http://jsfiddle.net/cxysA/12/
-
EDIT 2 ON Gijs ANSWER:
Gijs mentioned two links onto overwriting document.write. That sounds an awesome idea but I think it is not possible to accomplish what I am trying.
I used John's Resig way to prevent document.write of which can be found here: http://ejohn.org/blog/xhtml-documentwrite-and-adsense/
When I used this method, I load the API successfuly but the snippets.js file is not loading at all.
Fiddle: http://jsfiddle.net/9HX7N/
I belive what you want is it:
function loadSkyscanner()
{
function loaded()
{
t.skyscanner.load('snippets', '1', {'nocss' : true});
var snippet = new t.skyscanner.snippets.SearchPanelControl();
snippet.setCurrency('GBP');
snippet.setDeparture('uk');
snippet.draw(document.getElementById('snippet_searchpanel'));
}
var t = document.getElementById('sky_loader').contentWindow;
var head = t.document.getElementsByTagName('head')[0];
var script = document.createElement('script');
script.type = 'text/javascript';
script.onreadystatechange= function() {
if(this.readyState == 'complete') loaded();
}
script.onload= loaded;
script.src= 'http://api.skyscanner.net/api.ashx?key=PUT_HERE_YOUR_SKYSCANNER_API_KEY';
head.appendChild(script);
}
$("button").click(function(e)
{
loadSkyscanner();
});
It's load skyscanner in iframe#sky_loader, after call loaded function to create the SearchPanelControl. But in the end, snippet draws in the main document. It's really a bizarre workaround, but it works.
The only restriction is, you need a iframe. But you can hide it using display:none.
A working example
EDIT
Sorry guy, I didn't see it. Now we can see how awful is skyscanner API. It puts two divs to make the autocomplete, but not relative to the element you call to draw, but the document.
When a script is loaded in a iframe, document is the iframe document.
There is a solution, but I don't recommend, is really a workaround:
function loadSkyscanner()
{
var t;
this.skyscanner;
var iframe = $("<iframe id=\"sky_loader\" src=\"http://fiddle.jshell.net/orlleite/2TqDu/6/show/\"></iframe>");
function realWorkaround()
{
var tbody = t.document.getElementsByTagName("body")[0];
var body = document.getElementsByTagName("body")[0];
while( tbody.children.length != 0 )
{
var temp = tbody.children[0];
tbody.removeChild( temp );
body.appendChild( temp );
}
}
function snippetLoaded()
{
skyscanner = t.skyscanner;
var snippet = new skyscanner.snippets.SearchPanelControl();
snippet.setCurrency('GBP');
snippet.setDeparture('uk');
snippet.draw(document.getElementById('snippet_searchpanel'));
setTimeout( realWorkaround, 2000 );
}
var loaded = function()
{
console.log( "loaded" );
t = document.getElementById('sky_loader').contentWindow;
t.onLoadSnippets( snippetLoaded );
}
$("body").append(iframe);
iframe.load(loaded);
}
$("button").click(function(e)
{
loadSkyscanner();
});
Load a iframe with another html who loads and callback when the snippet is loaded. After loaded create the snippet where you want and after set a timeout because we can't know when the SearchPanelControl is loaded. This realWorkaround move the autocomplete divs to the main document.
You can see a work example here
The iframe loaded is this
EDIT
Fixed the bug you found and updated the link.
the for loop has gone and added a while, works better now.
while( tbody.children.length != 0 )
{
var temp = tbody.children[0];
tbody.removeChild( temp );
body.appendChild( temp );
}
For problematic cases like this, you can just overwrite document.write. Hacky as hell, but it works and you get to decide where all the content goes. See eg. this blogpost by John Resig. This ignores IE, but with a bit of work the trick works in IE as well, see eg. this blogpost.
So, I'd suggest overwriting document.write with your own function, batch up the output where necessary, and put it where you like (eg. in a div at the bottom of your <body>'). That should prevent the script from nuking your page's content.
Edit: OK, so I had/took some time to look into this script. For future reference, use something like http://jsbeautifier.org/ to investigate third-party scripts. Much easier to read that way. Fortunately, there is barely any obfuscation/minification at all, and so you have a supplement for their API documentation (which I was unable to find, by the way -- I only found 'code wizards', which I had no interest in).
Here's an almost-working example: http://jsfiddle.net/a8q2s/1/
Here's the steps I took:
override document.write. This needs to happen before you load the initial script. Your replacement function should append their string of code into the DOM. Don't call the old document.write, that'll just get you errors and won't do what you want anyway. In this case you're lucky because all the content is in a single document.write call (check the source of the initial script). If this weren't the case, you'd have to batch everything up until the HTML they'd given you was valid and/or you were sure there was nothing else coming.
load the initial script on the button click with jQuery's $.getScript or equivalent. Pass a callback function (I used a named function reference for clarity, but you can inline it if you prefer).
Tell Skyscanner to load the module.
Edit #2: Hah, they have an API (skyscanner.loadAndWait) for getting a callback once their script has loaded. Using that works:
http://jsfiddle.net/a8q2s/3/
(note: this still seems to use a timeout loop internally)
In the skyrunner.js file they are using document.write to make the page blank on load call back... So here are some consequences in your scenario..
This is making page blank when you click on button.
So, it removes everything from page even 'jQuery.js' that is why call back is not working.. i.e main function is cannot be invoked as this is written using jQuery.
And you have missed a target 'div' tag with id = map(according to the code). Actually this is the target where map loads.
Another thing i have observed is maps is not actually a div in current context, that is maps api to load.
Here you must go with the Old school approach, That is.. You should include your skyrunner.js file at the top of the head content.
So try downloading that file and include in head tag.
Thanks