I have not a good Javascript knowledge, but I'm kinda good with jQuery though. I want to change some jQuery code to pure Javascript, but I have no idea how to do it.
$(document).ready(function()
{
$('#block').one('click', function()
{
$(this).val('{L_SEND_CONFIRM}').removeClass('button1');
$('#replacement').val('{L_BLOCK_CODE}');
});
});
Anyone willing to help me out please?
P.S: Sorry for asking such a dumb question, I really need to learn Javascript myself ASAP.
This is a rough equivalent (there are subtleties that if you want to address start getting annoying, thus the need for frameworks in the first place):
window.onload = function() {
document.getElementById('block').onclick = function() {
this.onclick = '';
this.value = '{L_SEND_CONFIRM}';
this.className = this.className.replace('button1','');
document.getElementById('replacement').value = '{L_BLOCK_CODE}';
}
}
onready and onload are two different beasts.
onready fires when the DOM is ready, but graphics may not have been loaded yet.
onload fires when everything needed, including graphics, have finished.
I like this library here to handle the onready stuff. It uses DOM methods for browsers that support it and uses a weird IE hack when it must:
https://github.com/ded/domready
Related
How to use hammer JS events without JQuery selectors just using plain Javascript methods?
Bind hammer to a container element:
var hammer = new Hammer(document.getElementById("container"));
Now, on every gesture that is performed on the container element,
you'll receive a callback object with information on the gesture.
Some example functions:
hammer.ondragstart = function(ev) { };
hammer.ondrag = function(ev) { };
hammer.ondragend = function(ev) { };
hammer.onswipe = function(ev) { };
hammer.js is available as completely standalone version, so you don't need to import jquery resources. See: http://eightmedia.github.com/hammer.js/
Full documentation: https://github.com/eightmedia/hammer.js#documentation
Just a quick look over the GitHub documentation:
var hammer = new Hammer(document.getElementById("container"));
creates a 'hammer' without jQuery. After that you can set callback functions, you don't need any jQuery for that too. But beware! HammerJS might need jQuery internally, so it is possible you can't leave out the <script src="path/to/jquery.js"></script>
The short answer is: just use the plain old DOM API. You're not obliged, or forced to use nothing but jQuery once you've included it.
var someElements = document.querySelectorAll('.someClass');//not jQuery, perfectly valid
var byId = document.getElementById('someId');
var sameScript = $('#anotherId');//nothing stops me from doing this... using jQ for some things
If you find the DOM API a bit clunky (which it is), you might as well do something like this:
var pureDOMRef = $('someID')[0];//returns "normal" Element object, removes jQ wrapper
var multiple = Array.prototype.slice.apply($('.classSelector'),[0]);//returns Array
Just play around, switch back and forth if you want to, nothing wrong with that
The new version of hammer.js provides a JQuery plugin which has to be understand first that it's not a plugin from JQuery - it is FOR JQuery. So if you use JQuery for your site for other purposes then it's convenient that you can basically 'apply' a plugin from hammer at a JQuery selector like this:
$(element).hammer(options).bind("pan", myPanHandler);
Since hammer.js has a modern OOP pattern it can use instances for multiple data handling at once, hence every JQuery element that is bound to hammer is an instance. (IMHO) JQuery slows down by some ms, if you don't mind use this plugin or stay with Vanilla.
http://hammerjs.github.io/jquery-plugin/
I currently am working on a bookmarklet that opens an iframe, and sets up a communication of postMessage back and forth. That all works fine.
However, seemingly because the bookmarklet is being loaded as an anonymous function, the listeners are multiplying if I run the bookmarklet more than once on a page.
Is there some sort of way to keep track of these addEventListeners so that they don't double-up?
Do I need to define the rp_receive_message outside of the anonymous function?
Here's an example of the code:
var rp_receive_message = function (e) {
var response = e.data;
console.log("got message with "+ response);
};
if (window.addEventListener) {
window.addEventListener('message', rp_receive_message, false);
} else {
window.attachEvent('onmessage', rp_receive_message);
}
var s1 = window.document.createElement('iframe');
s1.setAttribute('src', 'http://mydomain.com/iframe.html');
s1.setAttribute('id', 'testiframe');
s1.setAttribute('width', '700');
s1.setAttribute('height', '550');
s1.setAttribute('frameBorder', '0');
s1.setAttribute('onload', 'this.contentWindow.postMessage(window.location.href, "http://mydomain.com/iframe.html");');
document.getElementById('container').appendChild(s1);
Probably this will solve the problem:
window.onmessage = rp_receive_message;
As you suggest, the code below might be enough by itself. I don't know if addEventListener and attachEvent will add the same function multiple times, but I wouldn't at all be surprised if they will. I suggest just testing it.
window.rp_receive_message = function(){...}
If you dislike either solution, you've got to set up a global variable, which hardly seems any different or greatly superior to above. The global can be a simple boolean to check if the event has been attached, or it can be a list of attached events that you update yourself. AFAIK, and I'm pretty sure, there is no native JS solution to get a list of event listeners have been attached to a particular event. Libraries such as jQuery maintain lists and let you read them; and possibly have other techniques that are elegant solutions to your general problem.
I am having trouble with some JavaScript running before the page is completely rendered in IE 6 (maybe other versions too but just testing IE6 for now. Firefox seems to be OK). I can get around this by calling the js on window.onload like this:
window.onload = function(){doIt();}
However, my concern is the fact that I will overwrite anything else that may already be in window.onload. The code will be used as part of a library so I can not guarantee that window.onload will not be set somewhere else by someone else. I would rather append my function to the onload event like this:
window.onload += function(){doIt1();}
window.onload += function(){doIt2();}
But when I do so, only doit2() is called. Is there a way to register an event handler for when the page is fully rendered? My second thought would be to just put my code in a loop checking to make sure all my objects exist before running. But I am scared that this could potentially lockup the browser.
Just for some background info, my code is hiding/showing iFrames. I know that I can use the iFrame's onload attribute but I need all of the iFrames to be fully loaded before calling the code.
Any thoughts from the community? Thanks in advance for you input.
Use this generic addLoadEvent function...
function addLoadEvent(func) {
if(typeof window.onload != 'function')
window.onload = func;
else {
var oldLoad = window.onload;
window.onload = function() {
if(oldLoad) oldLoad();
func();
}
}
}
This essentially queues up functions to be executed. It never overwrites a previously assigned handler. Sample usage below...
addLoadEvent(function() { alert("One!"); });
addLoadEvent(two);
function two() {
alert("Two!");
}
I want to mention that libraries like jQuery take care of known issues like this for you.
I load everything on my page.
At the end, I have this script.
<script type="text/javascript">loadNewVideo('u1zgFlCw8Aw',0)</script>
It doesn't work.
But if I substitute it with this, it works.:
<input type="submit" onclick="loadNewVideo('u1zgFlCw8Aw',0);" >
In the .JS file, this is the function:
function loadNewVideo(id, startSeconds) {
alert('In-the-function');
if (ytplayer) {
alert('Found-ytplayer');
ytplayer.loadVideoById(id, parseInt(startSeconds));
}
}
Apparently, "ytplayer" is false in the first one!??
I don't know what ytplayer is, but I imagine this problem has something to do with the DOM not being fully loaded. Have you tried this?
<script type="text/javascript">
$(document).ready(function() {
loadNewVideo('u1zgFlCw8Aw', 0);
});
</script>
edit: If this doesn't work, you will have to give us more information. As Tim and Peter asked you in comments to your question, can you tell us where ytplayer is defined and what it is? I'm assuming it stands for YouTube Player, maybe it's being loaded/defined after you were calling loadNewVideo?
For example, if the code snippet above is above the part where ytplayer is defined in your document, this would still be called before ytplayer is loaded, depending on how you're loading it. As I said, please supply some more information.
I don't have an answer, but perhaps this will help you figure out when the ytplayer component is ready for use:
var startTimer = new Date().getTime();
function ytplayerReadyCheck() {
var ready = !!ytplayer;
if (!ready) {
window.setTimeout(ytplayerReadyCheck,50);
}
else {
var endTimer = new Date().getTime();
alert('ytplayer is now ready!\n\nWe waited '+(endTimer-startTimer)+' milliseconds for it');
loadNewVideo('u1zgFlCw8Aw', 0);
}
}
ytplayerReadyCheck();
Of course, this is scarcely replacement for figuring out where ytplayer is defined in the first place! Perhaps it's defined in a .js file that's dynamically loaded after the document has loaded?
I'd highly recommend getting hold of Firebug so you can more easily debug this kind of thing.
I would say this is because the DOM hasn't totally loaded at that stage. You want to hook the body onLoad event, or use jQuery to get the $(document).ready() hook.
In my ASP.NET User Control I'm adding some JavaScript to the window.onload event:
if (!Page.ClientScript.IsStartupScriptRegistered(this.GetType(), onloadScriptName))
Page.ClientScript.RegisterStartupScript(this.GetType(), onloadScriptName,
"window.onload = function() {myFunction();};", true);
My problem is, if there is already something in the onload event, than this overwrites it. How would I go about allowing two user controls to each execute JavaScript in the onload event?
Edit: Thanks for the info on third party libraries. I'll keep them in mind.
Most of the "solutions" suggested are Microsoft-specific, or require bloated libraries. Here's one good way. This works with W3C-compliant browsers and with Microsoft IE.
if (window.addEventListener) // W3C standard
{
window.addEventListener('load', myFunction, false); // NB **not** 'onload'
}
else if (window.attachEvent) // Microsoft
{
window.attachEvent('onload', myFunction);
}
There still is an ugly solution (which is far inferior to using a framework or addEventListener/attachEvent) that is to save the current onload event:
function addOnLoad(fn)
{
var old = window.onload;
window.onload = function()
{
old();
fn();
};
}
addOnLoad(function()
{
// your code here
});
addOnLoad(function()
{
// your code here
});
addOnLoad(function()
{
// your code here
});
Note that frameworks like jQuery will provide a way to execute code when the DOM is ready and not when the page loads.
DOM being ready means that your HTML has loaded but not external components like images or stylesheets, allowing you to be called long before the load event fires.
I had a similar problem today so I solved it having an index.js with the following:
window.onloadFuncs = [];
window.onload = function()
{
for(var i in this.onloadFuncs)
{
this.onloadFuncs[i]();
}
}
and in additional js files that i want to attach the onload event I just have to do this:
window.onloadFuncs.push(function(){
// code here
});
I normally use jQuery though, but this time I was restricted to pure js wich forced to use my mind for a while!
Mootools is another great JavaScript framework which is fairly easy to use, and like RedWolves said with jQuery you can can just keep chucking as many handlers as you want.
For every *.js file I include I just wrap the code in a function.
window.addEvent('domready', function(){
alert('Just put all your code here');
});
And there are also advantages of using domready instead of onload
Try this:
window.attachEvent("onload", myOtherFunctionToCall);
function myOtherFunctionToCall() {
// do something
}
edit: hey, I was just getting ready to log in with Firefox and reformat this myself! Still doesn't seem to format code for me with IE7.
I don't know a lot about ASP.NET, but why not write a custom function for the onload event that in turn calls both functions for you? If you've got two functions, call them both from a third script which you register for the event.
Actually, according to this MSDN page, it looks like you can call this function multiple times to register multiple scripts. You just need to use different keys (the second argument).
Page.ClientScript.RegisterStartupScript(
this.GetType(), key1, function1, true);
Page.ClientScript.RegisterStartupScript(
this.GetType(), key2, function2, true);
I believe that should work.
You can do this with jquery
$(window).load(function () {
// jQuery functions to initialize after the page has loaded.
});