Further to a previous question I posted - using the HTML5 audio element with XForms - I need some suggestions on how best to save and load the current time to Local Storage ?
It is relatively easy to save the current position like this - I'm not sure this is correct approach - I don't know if there is any potential clash between Xforms and custom javascript doing this.
<audio id="audioplayer" src="{media_url}" controls="true" onpause="func()"/>
And this javascript function:
function func() {
var audio = document.getElementById("audioplayer");
localStorage.setItem(audio.src,audio.currentTime);
}
But loading back the value from Local Storage is trickier: since I am setting the src of the audio using Xforms, which is all done declaratively - how to trigger the equivalent javascript function when the underlying instance changes?
Can I intercept the 'onpause' event in Xforms? Can I hook Javascript methods into XForms etc?
I would like to stick as close to using XForms' declarative methods as possible.
Related
I've been trying to write some JavaScript for a Chrome extension that can read elements by class name from a website which I don't own. For example, if I inspect this website there is a body tag with class="x" in it, this sometimes updates to class="y". All I need to do is be able to read this value.
So far I have tried using:
var x = document.getElementsByClassName("x");
if (x.length > 0) window.alert("Alert");
This works when I have this in script tags beneath my own HTML. However I have no idea how to do this for an external website. Ideally I use a solution using vanilla JS but please also let me know if I will have to use libraries to do this.
You need to use "content scripts" to run your code in a context of web page.
Take a look at Google's doc here - https://developer.chrome.com/extensions/content_scripts
Also you mentioned about possibility of changes, if you need to watch if object changes, you can use Mutation Observer API.
Take a look at Mozilla's doc here - https://developer.mozilla.org/en-US/docs/Web/API/MutationObserver
I'm using Processing with the HYPE framework to create some visualizations and want to put it in my iOS app. I've searched around a bit and it looks like the easiest solution would be to export Processing to JS and put that in a UIWebView.
The part I'm unsure about is that I need to be able to send input to the JS to adjust the visualization on a steady timer. My first thought is that I can set up key listeners in the JS, and then programmatically simulate a key press within the app. Is that possible? Are there other solutions?
Not a javascript expert but I know you can run JS in UIWebView. eg:
// Get
NSString *innerHTML = [self.myWebView stringByEvaluatingJavaScriptFromString:#"document.documentElement.innerHTML"];
// Set
[self.myWebView stringByEvaluatingJavaScriptFromString:#"document.documentElement.innerHTML"];
I hope this guides you in the right direction.
Source
I'm currently working through a tutorial on how to make a sound board in HTML5 provided here.
The current piece of code I've been having trouble with is this:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<script type="text/javascript" charset="utf-8">
$(function() {
$("audio").removeAttr("controls").each(function(i, audioElement) {
var audio = $(this);
var that = this; //closure to keep reference to current audio tag
$("#doc").append($('<button>'+audio.attr("title")+'</button>').click(function() {
if(that.play()==true){
play.stop();
}else{
that.play();
}
}));
});
});
</script>
I'm trying to make it so that only one sound can play at once. I also tried to make a plain stop button by calling that.stop() but it doesn't work. I am also trying to figure out how to make separate arrays so I can organize the sounds. I tried changing the audio tag as in the tutorial talks about how it creates the array searching for that. But I must be changing the wrong line of code as the new array never works.
To only allow one sound to play at once, I would listen to the DOM media events.
There are several events that would help you. Such as:
ended
pause
play
playing
If you listen to these, and keep a global flag to tell you if media is playing, you can prevent your other buttons/links from playing a sound, by checking this flag first.
EDITED FOR COMMENT:
Pretty much all of the code you need is JavaScript, not PHP. Have a look at this sample fiddle.
http://jsfiddle.net/B82Nq/11/
It registers a generic media event listener to the 3 <audio> tags, and separate pause, ended and playing event handlers to control playback. When you are sent a stop/start event, a global boolean variable is toggled that tells you whether you should allow another clip to play (I assume you will simply disable the buttons that play them, or something similar).
But I've added all media events to show you them all firing anyway - it will help understanding when and how often they are fired. They are listed at MDC here:
(no apology made for using an AC/DC clip :)
Generally, there are 3 ways (that I am aware of) to execute javascript from an <a/> tag:
1) Use onclick():
hello
2) Directly link:
hello
3) Or attach externally:
// In an onload event or similar
document.getElementById('hello').onclick = window.alert('Hello');
return false;
<a id="hello" href="#">hello</a>
I am actually loading the link via AJAX, so #3 is basically out. So, is it better to do #1 or #2 or something completely different? Also, why? What are the pitfalls that I should be aware of?
Also of note, the anchor really doesn't link anywhere, hence the href="#", I am using a so the styles conform as this is still an object to be clicked and a button is inappropriate in the context.
Thanks
If you are loading the content via ajax and need to hook up event handlers, then you have these choices:
Put a javascript handler in your HTML with your option 1) or 2). In my mind option 1) is a cleaner way of specifying it, but I don't think there's a mountain of difference between 1) or 2) - they both do essentially the same thing. I'm not a fan of this option in general because I think there's value in keeping the markup and the code separate.
After loading the content with ajax, call some local code that will find and hook up all the links. This would be the same kind of code you would have in your page and execute on DOMReady if the HTML had been static HTML in your page. I would use addEventListener (falling back to attachEvent) to hook up this way as it more cleanly allows multiple listeners for a single object.
Call some code after you load the content with ajax that finds all the links and hooks up the clicks to some generic click handler that can then examine meta data in the link and figure out what should be done on that click based on the meta data. For example, this meta data could be attributes on the clicked link.
When you load the content, also load code that can find each link individually and hook up an appropriate event handler for each link much the way one would do it if the content was just being loaded in a regular page. This would meet the desire of separating HTML from JS as the JS would find each appropriate link and hook up an event handler for it with addEventListener or attachEvent.
Much like jQuery .live() works, hook up a generic event handler for unhandled clicks on links at the document level and dispatch each click based on some meta data in the link.
Run some code that uses an actual framework like jQuery's .live() capability rather than building your own capability.
Which I would use would depend a little on the circumstances.
First of all, of your three options for attaching an event handler, I'd use a new option #4. I'd use addEventListener (falling back to attachEvent for old versions of IE) rather than assigning to onclick because this more cleanly allows for multiple listeners on an item. If it were me, I'd be using a framework (jQuery or YUI) that makes the cross browser compatibility invisible. This allows complete separation of HTML and JS (no JS inline with the HTML) which I think is desirable in any project involving more than one person and just seems cleaner to me..
Then, it's just a question for me for which of the options above I'd use to run the code that hooks up these event listeners.
If there were a lot of different snippets of HTML that I was dynamically loading and it would be cleaner if they were all "standalone" and separately maintainable, then I would want to load both HTML and relevant code at the same time so have the newly loaded code handle hooking up to it's appropriate links.
If a generic standalone system wasn't really required because there were only a few snippets to be loaded and the code to handle them could be pre-included in the page, then I'd probably just make a function call after the HTML snippet was loaded via ajax to have the javascript hook up to the links in the snippet that had just been loaded. This would maintain the complete separation between HTML and JS, but be pretty easy to implement. You could put some sort of key object in each snippet that would identify which piece of JS to call or could be used as a parameter to pass to the JS or the JS could just examine the snippet to see which objects were available and hook up to whichever ones were present.
Number 3 is not "out" if you want to load via AJAX.
var link = document.createElement("a");
//Add attributes (href, text, etc...)
link.onclick = function () { //This has to be a function, not a string
//Handle the click
return false; //to prevent following the link
};
parent.appendChild(link); //Add it to the DOM
Modern browsers support a Content Security Policy or CSP. This is the highest level of web security and strongly recommended if you can apply it because it completely blocks all XSS attacks.
The way that CSP does this is disabling all the vectors where a user could inject Javascript into a page - in your question that is both options 1 and 2 (especially 1).
For this reason best practice is always option 3, as any other option will break if CSP is enabled.
I'm a firm believer of separating javascript from markup. There should be a distinct difference, IMHO, between what is for display purposes and what is for execution purposes. With that said, avoid using onclick attribute and embedding javascript:* in a href attribute.
Alternatives?
You can include javascript library files using AJAX.
You can setup javascript to look for changes in the DOM (i.e. if it's a "standard task", make the anchor use a CSS class name that can be used to bind a specific mechanism when it's later added dynamically. (jQuery does a great job at this with .delegate()))
Run your scripts POST-AJAX call. (Bring in the new content, then use javascript to [re]bind the functionality) e.g.:
function ajaxCallback(content){
// add content to dom
// search within newly added content for elements that need binding
}
This might be a simple question for geeks, but not for me, at least. I was developing a simple XUL program from scratch. I used wizard tag to simplify the GUI that appears to the user. On a wizard page I have inserted a progressmeter to show the progress of a function called myFunction() which belongs to the JavaScript which is available in the XUL file. How can I properly update the progressmeter based on the real progress of the function?
Yes, the reverse thread work round does work, but as per the doc (here: https://developer.mozilla.org/en/nsIThread) processNextEvent may wait for a very long time if there are no pending events! Err.. since xulrunner is single thread there appear to be few, resulting in a huge slow down. Waggling the mouse helps though.
On further investigation use processNextEvent(false) works without delay.
Have you tried setting the progression of the progressmeter using its "value" property?
myProgressmeter.value = 50;
You just need to increment this value depending on the progression of your function.
Note that the value should be set between 0 and myProgressmeter.max