From the documentation I've found this example:
We can animate any element, such as a simple image:
<div id="clickme">
Click here
</div>
<img id="book" src="book.png" alt="" width="100" height="123" />
With the element initially shown, we can hide it slowly:
$('#clickme').click(function() {
$('#book').fadeOut('slow', function() {
// Animation complete.
});
});
I remember from 5 years ago, that you should NEVER ever refer to any element until it was defined. Does this rule still apply? So I would have to put all that code in the footer of my web page? Or can I put it in a separate file and import it in the footer? What's best practice?
The recommended way of doing this is putting all initialization code into $(document).ready, like so:
$(document).ready(function() {
$('#foobar').click(function(event) { alert("You Clicked Me!"); });
});
You are correct; you cannot interact with a DOM element before it exists.
You have two options:
Put the code below the HTML, as you suggested.
Put the code anywhere, but wrap it in $(function() { ... }).
This construct will execute the function in the page load event, after the DOM exists.
The best practice is to place all SCRIPT elements at the bottom of the HTML document (right before the </body> tag. The reasons are:
loading of external JS files blocks loading of other resources (like images)
since JS code is executed immediately, it is better to parse the HTML code of the page first, and then execute the JS code afterwards
You can see an HTML5 template that demonstrates this practice here: http://vidasp.net/HTML5-template.html
Many people put it in the bottom of the page so other code can execute first. That becomes a bit of a moot point with the document ready syntax that waits until other content loads to the dom. So, using that logic, in theory it could go anywhere.
Scripts go best in the foot of the page, to provide for the speediest rendering of the DOM. The following idiom executes only once the DOM is ready:
$(function() { /* ... your code goes here ... */ }
If you have a lot of code, or code that is shared between multiple pages, you should link it in a separate file which can then be minified, should you need to optimize your download speed.
I asked this question, albeit in a different way a little while back. You might want to look at the answers I got too - they're quite ... philosophical:
JQuery - Best way of wiring GUI objects to events?
Related
I'm sure this sounds a little odd, but here's the background...
We utilize a company that loads their chat program, so we can support our customers, into our page. This is done via javascript and jquery, and creates a structure like this:
<div id="myid" style="...; right: 0px;..."><div><iframe></iframe></div></div>
There's a WHOLE lot more to that, but those are the important parts. Now the tool allows us to put custom scripting, which will be placed in the iframe. My goal is to just remove the "right: 0px", which I have done via the below code, but I don't want to put that code on every page that this tool integrates with. I would like to load it into the tool, and have it run when the iframe and divs are created.
working code on parent:
$(document).ready(function() {
function checkPos() {
$('#myId').each(function() {
var oldstyle = $('#myId').attr('style');
var newstyle = oldstyle.replace(' right: 0px;','');
$('#myId').attr('style', newstyle);
});
setTimeout(checkPos, 100);
};
$(document).ready(function() {
setTimeout(checkPos, 100);
});
});
Once placed in the code include method they provide, I have trouble having it wait until the div tag actually has the "right: 0px;" in its style tag. the only thing I need to run is the three lines in the $('#myId').each(function()
Basically, I need help with having the script in the iframe target the div that the iframe is nested in.
Assuming that whatever tool your using actually lets you pass in a custom script to the content rendered in the iframe (seems fishy to me), a better way of modifying the style in jquery is to use the css function:
$('#myId').css('right', '0px');
Notice I removed the $.each function as well. You are targeting an element with an id, so there isn't any need to iterate.
Edit:
Anyways, back to the problem of delaying execution to when the target, #myId, actually exists. If they are really injecting your javascript into their page (again, seems fishy), then attaching the above code to the $(document).ready() event should do the trick, as long as this listener is attached to their document.
If all else fails, try to use the waitUntilExists plugin, here:
Source:
https://gist.github.com/buu700/4200601
Relevant question:
How to wait until an element exists?
I'm using an external javascript file (eg:myjs.js) with function setval() to set the innerText property of a HTML lable.
I have PHP page with <lable id="abc"></lable> and I have included myjs.js in <head> section. myjs.js is included in <head> section of one more PHP file and I'm calling setval() from this file, so when it runs it must set the innerText of lable in the first PHP file.
Is it possible to achieve? Any suggestions are greatly appreciated.
I hope I made question clear.
Thanks
Ideally, move your include of myjs.js to the bottom of the page (just before or after the closing </body> tag). Then it's just:
document.getElementById("abc").innerText = /* ...the text */;
Live example | source
If you can't move the include for some reason, you can put the above code in a function, e.g.:
function updateTheLabel() {
document.getElementById("abc").innerText = /* ...the text */;
}
...and then put this script just after the label:
<label id="abc"></label>
<script>
updateTheLabel();
</script>
Live example | source
If you don't want to do that (and it's a bit ugly, mixing script tags into your markup like that), you could wait for some kind of event that occurs when the page is ready. Search for "javascript dom ready event" and you'll see a lot of discussion of this, and lots of solutions. If you're using a library jQuery, Prototype, or any of several others, odds are high (but not 100%) that the library will have something for you. You probably don't want to wait for the window load event, because that fires very late in the page load process (after all external resources — images and such — are loaded).
(Can't do a live example of the above without knowing what library, if any, you're using; but again, there are dozens of "dom ready" solutions out there.)
Or I suppose worst case, you could poll, using this in myjs.js:
function updateTheLabel() {
var elm = document.getElementById("abc");
if (elm) {
elm.innerText = /* ...the text */;
}
else {
setTimeout(updateTheLabel, 50);
}
}
setTimeout(updateTheLabel, 0);
Live example | source
I'm trying to do some simple jQuery stuff 'dynamically' from within a MediaWiki content page. Its really just to 'beauty up' some different features.
I've done the following:
http://www.mediawiki.org/wiki/JQuery
http://www.mediawiki.org/wiki/Manual:$wgRawHtml (mainly for Paypal buttons initially)
The below code does not work. This is put in a blank content page.
<html>
<script>
$j(document).ready(function(){
$j('#test').hover(
function(){
$j('#test').attr('background-color','red');
},
function(){
$j('#test').removeAttr('background-color');
}
);
});
</script>
<div id="test">Howdy</div>
</html>
Nothing happens...
Any ideas?
Update:
I have attempted this simple solution with no result.
example.com/wiki/index.php?title=MediaWiki:Common.js
$j('#jTest-Howdy').hover(
function(){
$j('#jTest-Howdy').addClass('jTest-red');
},
function(){
$j('#jTest-Howdy').removeClass('jTest-red');
}
);
example.com/wiki/index.php?title=MediaWiki:Common.css
.jTest-red { background-color: red; }
example.com/wiki/index.php?title=jQueryTest
<html>
<div id="jTest-Howdy">Howdy</div>
</html>
as you can see here, this code should work IF jQuery was being loaded properly...
http://jsfiddle.net/5qFhv/
but it is not working for me... any help?
If you're using the jQuery that's loaded by MediaWiki 1.17, be aware that most JavaScript is loaded after page content. An inline <script> element is executed immediately when it's reached, so $j would not be defined at this time -- you'll probably see some errors in your JavaScript error console to this effect.
(Offhand I'm not sure about the jQuery that's included with 1.16; versions of MediaWiki prior to that as far as I know did not include jQuery.)
Generally what you want to do here is to either put JavaScript code modules into the 'MediaWiki:Common.js' page and let that hook up to your HTML markup, or create a MediaWiki extension -- which you can then invoke from your pages, and which will let you create any fun HTML and JavaScript output you like.
http://www.mediawiki.org/wiki/Manual:Interface/JavaScript
http://www.mediawiki.org/wiki/Manual:Developing_extensions
Code you put in your 'MediaWiki:Common.js' page will be loaded after other UI initialization, ensuring that code and variables are present so you can call into jQuery etc.
I don't know much about MediaWiki, but to me it looks like some simple javascript mistakes.
In the first sample you are trying to set an attribute on the element,
when you need to set the css or style attribute.
$j('#test').css('background-color', 'red');
In both samples you are binding an event to an element that doesn't exist yet in the DOM, so it will fail. You could use the live method, which will work for existing and future elements introduced in the DOM.
$j.('#test').live('mouseover', function(){
$j(this).addClass('hover-class');
}).live('mouseout', function(){
$j(this).removeClass('hover-class');
});
Hope that helps.
Try putting all your custom jQuery code in its own file, then load it as a module with ResourceLoader, after jQuery.
http://www.mediawiki.org/wiki/ResourceLoader/Migration_guide_for_extension_developers
Also, as a debugging method: completely load your site in Firefox, then enter your custom jQuery code in the console. If it works, your problem is a race condition. If it doesn't, jQuery isn't loading for some reason.
I have a couple of, what may end up being for this forum, overly-novice questions regarding unobtrusive event handling.
As I understand it, a properly set-up document would look something like this:
<html>
<head>
<title>Title</title>
<script src="jsfile.js" type="text/javascript></script>
</head>
<body>
//Body content, like some form elements in my case
</body>
</html>
Jsfile.js would look something like this:
function a() {
//code;
}
function b()...
window.addEventListener('load', a, false);
document.getElementById("id").addEventListener('click', b, false);
document.myForm.typeSel.addEventListener('change', c, false);
//or to use better browser-compatible code...
function addEvent(obj,evt,fn) {
if (obj.addEventListener)
obj.addEventListener(evt,fn,false);
else if (obj.attachEvent)
obj.attachEvent('on'+evt,fn);
}
addEvent(window, 'load', a);
addEvent(document.getElementById('id'), 'click', b);
addEvent(document.myForm.typeSel, 'change', c);
As I understand it, while in the head the browser will load this JavaScript code, adding each of those event handlers to their respective elements. HOWEVER... While the window handler is added properly, none of the others are. But if placed within a function, the (for instance) getElementById method of accessing an element works just fine, and the event handler is added. So I could conceivably make a loadEvents() function which is called via window onload, which contains all of the addEvent() functions for the other document elements for which I need event handlers. But as I understand the whole thing, I shouldn't have to do this.
In addition, if I were to stick the addEvent code within the body along with the element it addresses, such as:
<input type="checkbox" id="test" />
<script type="text/javascript>
document.getElementById("test").onclick = func;
</script>
...then it works fine. But of course it also violates the whole reason for removing inline event handlers!
So question being: In order to use *element*.addEventListener('click',func,false), addEvent(*element*,'click',func), or even *element*.onclick = func - how can I successfully reference an element at the end of a script file in the head, without having to stick it in another function? Why does getElementById and other such methods not work outside of a function in the head?
Or, is there some flaw in my underlying understanding?
Putting <script> in the <head> used to be the wisdom. But nowadays, with heavy ajax pages, <script> is more and more often but in the body, as far down below as possible. The idea is that the loading and parsing of the <script> keeps the rest of the page from loading, so the user will be looking at a blank page. By making sure the body is loaded as fast as possible, you give the user something to look at. See YAHOO best practices for a great explanation on that issue: http://developer.yahoo.com/performance/rules.html
Now, regardless of that issue, the code as you set it up now, can't work - at least, not when the elements you attempt to attach the handlers to aren't created yet. For example, in this line:
document.getElementById("id").addEventListener('click', b, false);
you will get a runtime error if the element with id="id" is inside the body. Now, if you put the <script> in the body, way below, after the content (including the lement with id="id", it will just work, since the script is executed after the html code for those elements is parsed and added to the DOM.
If you do want to have the script in the head, then you can do so, but you'll need to synchronize the adding of the event handlers with the rendering of the page content. You could do this by adding them all inside the document or window load handler. So, if you'd write:
//cross browser add event handler
function addEventHandler(obj,evt,fn) {
if (obj.addEventListener) {
obj.addEventListener(evt,fn,false);
} else if (obj.attachEvent) {
obj.attachEvent('on'+evt,fn);
}
}
addEventHandler(document, 'load', function(){
//set up all handlers after loading the document
addEventHandler(document.getElementById('id'), 'click', b);
addEventHandler(document.myForm.typeSel, 'change', c);
});
it does work.
The reason why window.addEventListener works while document.getEle...().addEventListener does not is simple: window object exists when you're executing that code while element with id="abc" is still not loaded.
When your browser downloads page's sources the source code is parsed and executed as soon as possible. So if you place script in head element - on the very beginning of the source - it's executed before some <div id="abc">...</div> is even downloaded.
So I think now you know why
<div id="test">Blah</div>
<script type="text/javascript">document.getElementById("test").style.color = "red";</script>
works, while this:
<script type="text/javascript">document.getElementById("test").style.color = "red";</script>
<div id="test">Blah</div>
doesn't.
You can handle that problem in many ways. The most popular are:
putting scripts at the end of document (right before </body>)
using events to delay execution of scripts
The first way should be clear right now, but personally I prefer last one (even if it's a little bit worse).
So how to deal with events? When browser finally download and parse whole source the DOMContentLoaded event is executed. This event means that the source is ready, and you can manipulate DOM using JavaScript.
window.addEventListener("DOMContentLoaded", function() {
//here you can safely use document.getElementById("...") etc.
}, false);
Unfortunately not every browser support DOMContentLoaded event, but as always... Google is the anwser. But it's not the end of bad news. As you noticed addEventListener isn't well supported by IE. Well... this browser really makes life difficult and you'll have to hack one more thing... Yes... once again - Google. But it's IE so it's not all. Normal browsers (like Opera or Firefox) supports W3C Event Model while IE supports its own - so once again - Google for cross-browser solution.
addEventListener might seems now the worst way to attach events but in fact it's the best one. It let you easly add or remove many listeners for single event on single element.
PS. I noticed that you consider of using Load event to execute your scripts. Don't do that. Load event is execute too late. You have to wait till every image or file is loaded. You should use DOMContentLoaded event. ;)
EDIT:
I've forgotten... dealing with cross-browser event model is much easier when you're using some framework like very popular jQuery. But it's good to know how the browsers work.
are you familiar with jQuery?
its a javascript library featuring some really awesome tools.
for instance if you want to have some js action done just after your page if fully loaded and all DOM elements are created (to avoid those annoying exceptions) you can simply use the ready() method.
also i see you want to attach click \ change events jQuery takes care of this too :) and you don't have to worry about all those cross-browser issues.
take a look at jQuery selectors to make your life easier when attempting to fetch an element.
well thats it, just give it a shot, its has a very intuitive API and a good documentation.
I have hunted around for answer to this one, and though have found related quesions, I couldn't quite find an exact match for this.
I have a fairly large app which is supposed to load pages into divs in another page using the jQuery.load() method. The problem I have is that when loading the same page over and over again into the same div, I see the memory of the browser increase substantially (memory leak). If I call $("*").unbind, I of course do not see a leak, but then everything has been reset, so this isn't reallya fix. The following code example reproduces this problem:
Test1.htm
<head>
<title></title>
<script type="text/javascript" language="javascript" src="Scripts/jquery-1.3.2.js"></script>
<script type="text/javascript" language="javascript">
<!--
var i = 0;
$(document).ready(function() {
$("#btn").click(
function() {
i++;
$("#Test1").load("Test2.htm", null, function() {
//$(document).trigger("test");
})
$("#count").html(i);
});
});
//-->
</script>
</head>
<body>
<img id="btn" src="someimage.png" />
<h3>We are loading Test2.htm into below div</h3>
<div>
Count loads =<span id="count">0</span>
</div>
<div id="Test1" style="border-style:solid">EMPTY</div>
</body>
Test2.htm = any old html page..
If you load Test1.htm and click the button mutliple times, you'll notice the browser memory steadily increasing. I believe the problem is that the loaded js and DOM elements are never set for garbage collection. In my real world system I have tried removing (elem.remove() or .empty()) the loaded elements, but this doens't really fix the problem. I also have many js files loaded using "src", which I replaced with $.getScript, this seems to have had made a small improvement. These are all workarounds thought, and I wanted to find a real solution for this problem. Any ideas?
Edit: update due to more info provided about test2.htm (the page being loaded)
Original answer (for historical purposes): I don't actually see any leaks in the code/markup you have provided - is it possible the leak is in Test2.htm (which you haven't provided the code/markup for)?
New answer:
I would suggest that it it probably due to either multiple loads of jQuery, or other scripts you have in test2.htm.
Assuming jQuery does not leak by simply instantiating and then nullifying jQuery and $, loading multiple times will keep at least 2 copies of jQuery in memory. When loaded, jQuery keeps a backup of any previous versions of $ and jQuery in _$ and _jQuery - so you are going to have at least 2 copies of jQuery loaded when you use load() multiple times.
The above assumption is most likely not correct however - there is every chance that jQuery has leaks even if you "unload" it by setting $,jQuery,_$ and _jQuery to null - it's not really intended to be loaded multiple times like that (however I'm sure that they allow it intentionally, so you can use noConflict() to load and use two different versions of jQuery if necessary).
You can add a "selector" to a load URL. For example:
$("#Test1").load("Test2.htm body", null, function() {
//callback does nothing
});
//or
$("#Test1").load("Test2.htm div#the_Div_I_Want", null, function() {
//callback does nothing
});
I would suggest doing this if you are not interested in any scripts in the ajax result, or alternatively if you do want scripts, you'd need to choose a selector to disable only certain elements/scripts, e.g.
/* load with selector "all elements except scripts whose
src attribute ends in 'jquery.js'" */
$("#Test1").load("Test2.htm :not(script[src$='jquery.js'])", null, function() {
//callback does nothing
});
Also of note is that if you leave out the "data" argument (you have it as null), and provide a function as the second argument, jQuery will correctly determine that the second argument is the callback, so
$("#Test1").load("Test2.htm :not(script[src$='jquery.js'])", function() {
//callback does nothing
});
is acceptible
Hmm perhaps it's just something really basic, but if i set $.ajaxSetup({ cache: false }); before the load calls, I don't seem to get the problem. Now, of course my "real" code has this call, so why might I see a problem? I believe the Tabs UI extension is causing caching to be switched on (I don't actually believe this, but invoking the false cache call before each load seems to fix it!!)
Ok so I finally found the problem and it's not a leak at all (which I suspected), it's simply the result of attaching multiple very complex handlers to the same trigger/event. I raised this question relating to that:
JQuery event model and preventing duplicate handlers