I'm new to JavaScript, so my problem will probably be very easy to fix for someone with any experience. I'm making a music blog with a few friends, and I am trying to make my own custom music player using jPlayer.
I want a simple JavaScript function that you supply the title of the song and the mp3, and it adds itself to the jPlayer playlist. This is the JavaScript function that I have...
function add_song(title, mp3)
{
myPlaylist.add({
title:"Tempered Song",
mp3:"http://www.jplayer.org/audio/mp3/Miaow-01-Tempered-song.mp3"
});
}
I want to be able to call the function anywhere in my body, using this code...
<script>
add_song("Your Face", "http://www.jplayer.org/audio/mp3/TSP-05-Your_face.mp3");
</script>
This, however, doesn't actually add the song. I'm guessing that this has something to do with having to set up the jPlayerPlaylist in the $(document).ready() function. I'm guessing that my variable "myPlaylist" isn't correctly initialized when I try to call add_song(). Like I said, I'm new to JavaScript so try to make it simple for me.
You can check out the code I have at my website to better guide me in my problem. Thanks!
The problem is indeed that you're setting up your jPlayerPlaylist after you're calling add_song. The browsers blocks and runs the Javascript code in <script> tags as soon as it encounters them, which is before document.onload and jQuery equivalents are fired.
What exactly are you trying to accomplish? Do you really want to load up some hardcoded playlist elements right as the page is loading, or do you actually want to attach these to buttons or links? For the former, move the function calls to the onload function, and for the latter, make new event handler functions and attach them to the appropriate elements.
If you're really just going to supply the function manually in the address bar or something, it should work fine. It simply won't work before the page has loaded.
Related
Sorry if the title is a bit tricky to understand. Allow me to elaborate.
On my Wordpress website, I recently started using the extension Custom Field Suite, in order to be able to create custom fields. It allows me to retrieve those afterwards in html, so that if I ever need to change a text I can do it directly on Wordpress instead of having to pull up the html files and re-upload them every time.
Today I was doing some Javascript and I needed to retrieve a text that comes from one of those custom fields. Basically retrieve something like this :
<h1 class="title"><?= CFS()->get('title'); ?></h1>
So, what I thought of doing was using a QuerySelector and retrieve the class .title into a variable, like so :
let sentence = document.querySelector(".title");
The only problem is that it returns undefined, and I think I know why. When I load the page up and then go into the console and type exactly that, it works, which leads me to believe my Javascript retrieves the title faster than it has time to be returned by the CFS()->get.
My problem now is that I don't know how I could make it so that my title loads in time for the Javascript to proceed it, so I was wondering if anyone out there had an idea.
Thanks in advance
You can use the window.onload function of Javascript:
window.onload = function() {
alert('Page is loaded');
};
Or you can use an event listener:
window.addEventListener("load", function() {
alert('Page is loaded');
});
Be sure to put your js inside the functions. Be aware that this is one of many possibilities, so you can surely research for more options.
Problem: Need onclick event to pause/unpause a Youtube video, but impossible to add the evenlistener. Looks to me that the object is 'unclickable'.
Situation: Got a Youtube player initialized by swfobject, onYouTubePlayerReady is build as suggested in the docs (Google API docs)
For HTML & JS see: http://ListAndPlay.com
What I tried: almost everything, from changing doctypes till forcing ID's while adding the eventlisteners, nothing worked.
I hope that one of you see the flaw I made after hours...
i had the same problem before and -i think- i read somewhere in Jquery wiki that object doesn't fire any event because once you click on it you are inside flash object.
as an alternative solution i used a div with z-index:100 and placed it in front of the object and then you can use on click event when the client clicks on that div
i hope this helps
I have an AJAX web service call that returns a chunk of HTML that I then apply to a DIV element on my page. This works fine for any html element except a flash video which comes up with 'Movie not loaded'.
I've double-checked the html that is being returned and it's all fine, and it works if I don't use AJAX, but when I use AJAX and then add it using JS it doesn't seem to attempt to load the playlist.
Any ideas?
Thanks
Kev
If you use swfobject, you can dynamically insert flash into your html, which might fix your issue.
Perhaps the player SWF is to blame: it might be waiting for some kind of cue that the browser usually provides that you're not giving it with AJAX. Now there's no way to find that out, but try another player SWF, it might fire right up.
If that's not possible to do (a custom player, for instance), try using something like #Jasper suggested above (the added 1kb or so of overhead is negligible), but wrap all of your ajax in a JSON object and pass whether it's flash or not. Then you can do some logic to make it work that way.
I'm sorry to have wasted your time on this everyone, it turns out that there is actually an issue with some of the attributes in the HTML, and the reason I 'thought' it was OK was because it was running OK when I initially tested it and just assumed that the problems were because it was being added dynamically.
The issue was with the location of the SWF file, and the reason it wasn't being populated correctly is because the AJAX call resulted in the loading of the controls independently and certain properties weren't being initialised. It's all working fine now.
I have a system that loads a div with content through the use of AJAX. All is well, I can get the div to load perfectly with details from my database and it works great.
The problem is this:
Inside the returned div, I have a couple of buttons with onClick events. The onClick events cause an error when I attempt to call a user defined function onClick="my_function();" but the onClick events do not cause an error when I call a JS defined function onClick="alert('success');".
Anyone know why this would be? my_function() is defined in the head of my page. Although, I have also tried to define it in the content returned by AJAX, still with no luck.
Any help will be greatly appreciated
if you are using prototype, jquery, etc.. (any JS framework), you need to be sure you have set the param "evalJS" to true. this last example I put works in prototype.
check here for prototype
You could try adding event handlers via JavaScript instead of onclick handlers on the actual elements.
Then you could use anonymous functions.
If you're simply updating the innerHTML of a DIV element with the result of an AJAX request, keep in mind that the browser parses only HTML not scripts.
Probably that's why you're recieving the JavaScript Error.
To parse also the scripts you need to consult the documentation of your library. For instance, if you're using ASP.NET you can call ScriptManager.RegisterClientScriptBlock in order to instruct the AJAX client componenet to parse the scripts in the result.
On the other hand, if you're doing it by hand (one thing I did awhile back), you need to detect and parse the scripts yourself.
OK, here is the simple answer.. I had the button element name and id as the same as the function which it was trying to call.. stupid mistake I know.. anyhow, it is now working.. however, I do have another problem.. my ajax only fires once.. it works great the first time, but after that the function doesn't work
here is my code:
function delete_account(account_id) {
create_request();
var url = "accounts_ajax.php?action=delete_account&account_id=" + account_id;
show_div('action_window');
document.getElementById('action_window').innerHTML = '<div class="please_wait"><img src="images/working.gif"><br>Loading...</div>';
xmlHttp.open("GET", url, true);
xmlHttp.onreadystatechange = function(){if(xmlHttp.readyState!=4)return;if(xmlHttp.status==200){reload_div('action_window', xmlHttp.responseText);}};
xmlHttp.send(null);
}
it just causes an error second time around.
I have a javascript function that manipulates the DOM when it is called (adds CSS classes, etc). This is invoked when the user changes some values in a form. When the document is first loading, I want to invoke this function to prepare the initial state (which is simpler in this case than setting up the DOM from the server side to the correct initial state).
Is it better to use window.onload to do this functionality or have a script block after the DOM elements I need to modify? For either case, why is it better?
For example:
function updateDOM(id) {
// updates the id element based on form state
}
should I invoke it via:
window.onload = function() { updateDOM("myElement"); };
or:
<div id="myElement">...</div>
<script language="javascript">
updateDOM("myElement");
</script>
The former seems to be the standard way to do it, but the latter seems to be just as good, perhaps better since it will update the element as soon as the script is hit, and as long as it is placed after the element, I don't see a problem with it.
Any thoughts? Is one version really better than the other?
The onload event is considered the proper way to do it, but if you don't mind using a javascript library, jQuery's $(document).ready() is even better.
$(document).ready(function(){
// manipulate the DOM all you want here
});
The advantages are:
Call $(document).ready() as many times as you want to register additional code to run - you can only set window.onload once.
$(document).ready() actions happen as soon as the DOM is complete - window.onload has to wait for images and such.
I hope I'm not becoming The Guy Who Suggests jQuery On Every JavaScript Question, but it really is great.
I've written lots of Javascript and window.onload is a terrible way to do it. It is brittle and waits until every asset of the page has loaded. So if one image takes forever or a resource doesn't timeout until 30 seconds, your code will not run before the user can see/manipulate the page.
Also, if another piece of Javascript decides to use window.onload = function() {}, your code will be blown away.
The proper way to run your code when the page is ready is wait for the element you need to change is ready/available. Many JS libraries have this as built-in functionality.
Check out:
http://docs.jquery.com/Events/ready#fn
http://developer.yahoo.com/yui/event/#onavailable
Definitely use onload. Keep your scripts separate from your page, or you'll go mad trying to disentangle them later.
Some JavaScript frameworks, such as mootools, give you access to a special event named "domready":
Contains the window Event 'domready', which will execute when the DOM has loaded. To ensure that DOM elements exist when the code attempting to access them is executed, they should be placed within the 'domready' event.
window.addEvent('domready', function() {
alert("The DOM is ready.");
});
window.onload on IE waits for the binary information to load also. It isn't a strict definition of "when the DOM is loaded". So there can be significant lag between when the page is perceived to be loaded and when your script gets fired. Because of this I would recommend looking into one of the plentiful JS frameworks (prototype/jQuery) to handle the heavy lifting for you.
#The Geek
I'm pretty sure that window.onload will be called again when a user hits the back button in IE, but doesn't get called again in Firefox. (Unless they changed it recently).
In Firefox, onload is called when the DOM has finished loading regardless of how you navigated to a page.
While I agree with the others about using window.onload if possible for clean code, I'm pretty sure that window.onload will be called again when a user hits the back button in IE, but doesn't get called again in Firefox. (Unless they changed it recently).
Edit: I could have that backwards.
In some cases, it's necessary to use inline script when you want your script to be evaluated when the user hits the back button from another page, back to your page.
Any corrections or additions to this answer are welcome... I'm not a javascript expert.
My take is the former becauase you can only have 1 window.onload function, while inline script blocks you have an n number.
onLoad because it is far easier to tell what code runs when the page loads up than having to read down through scads of html looking for script tags that might execute.