I thinkg I doing something wrong, but the events only works if the selector is document. Otherwise, not happens.
HTML
<html>
<head>
<!-- the libraries references here -->
</head>
<body>
<div id="canvas"></div>
</body>
</html>
Javascript
/* Click on canvas */
canvasClickEvent = function(e){
if(e.shiftKey){
selectedElement = $(this).attr("id");
}
}
/* Events */
$(document).ready(documentLoadEvent);
$(document).click(canvasClickEvent); //this works, but is wrong
//$("#canvas").click(canvasClickEvent); --this is what I want, but not works
$(document).dblclick(canvasDblClickEvent);
If I replace the document by the div name like $('#canvas').click(canvasClickEvent);, the click event is not called. It's only works if the selector is document, but the element passed to the function always has the attibs like undefined.
What might be happening?
What is happening is that event is attempting to bind the event before the DOM element exists.
If you wrap the events inside of the ready() method you guarantee that the domain exists before your event attempts to bind.
$(document).ready( function () {
$("#canvas").click(canvasClickEvent);
}
The ready() method is dependent on the browsers DOMContentLoaded event which basically means the DOM is completely loaded in the browser, but does not necessarily mean all the media on the page has completely loaded. Once all media is loaded the onLoad browser event fires.
It seems like you put your JavaScript code BEFORE the html code. So, when the JavaScript code runs, the elements to be dealt with is not loaded into the DOM yet. (That's why you got "undefined")
Just put your script AFTER the related HTML code. Or put it inside the pageLoad event:
$(function(){
....
})
Related
Yesterday I had an issue where a .on('click') event handler I was assigning wasn't working right. Turns out it's because I was was trying to apply that .on('click') before that element existed in the DOM, because it was being loaded via AJAX, and therefore didn't exist yet when the document.ready() got to that point.
I solved it with an awkward workaround, but my question is, if I were to put a <script> tag IN the ajax loaded content and another document.ready() within that, would that second document.ready() be parsed ONLY once that ajax content is done being loaded? In other words, does it consider that separately loaded ajax content to be another document, and if so, does having another document.ready() within that ajax-loaded HTML work the way I think it does?
Alternatively; what would be a better way to handle this situation? (needing to attach an event listener to a DOM element that doesn't yet exist on document.ready())
To answer your question: No, document.ready will not fire again once a ajax request is completed. (The content in the ajax is loaded into your document, so there isn't a second document for the ajax content).
To solve your problem just add the event listener to the Element where you load the ajax content into it.
For example:
$( "div.ajaxcontent-container" ).on( "click", "#id-of-the-element-in-the-ajax-content", function() {
console.log($( this ));
});
For #id-of-the-element-in-the-ajax-content you can use any selector you would use in $("selector"). The only difference is, only elements under div.ajaxcontent-container will be selected.
How it works:
As long as div.ajaxcontent-container exists all elements (if they exist now or only in the future) that match the selector #id-of-the-element-in-the-ajax-content will trigger this click-event.
Javascript in the resulting ajax call will not be excecuted (by default) due to safety. Also, you can't directly bind event to non-existing elements.
You can bind an event to some parent that does exist, and tell it to check it's children:
$(document).ready(function(){
$(document).on('eventName', '#nonExistingElement', function(){ alert(1); }
// or:
$('#existingParent').on('eventName', '#nonExistingElement', function(){ alert(1); }
});
Always try to get as close to the triggering element as you can, this will prevent unnessesary bubbling through the DOM
If you have some weird functions going on, you could do something like this:
function bindAllDocReadyThings(){
$('#nonExistingElement').off().on('eventName', function(){ alert(1); }
// Note the .off() this time, it removes all other events to set them again
}
$(document).ready(function(){
bindAllDocReadyThings();
});
$.ajaxComplete(function(){
bindAllDocReadyThings();
});
try this, that is not working because your control is not yet created and you are trying to attach a event, if you use on event it will work fine. let me know if you face any issues.
$(document).ready(function(){
$(document).on('click', '#element', function (evt) {
alert($(this).val());
});
});
The answer here is a delegated event:
JSFiddle
JSFiddle - Truly dynamic
jQuery
$(document).ready(function(){
// Listen for a button within .container to get clicked because .container is not dynamic
$('.container').on('click', 'input[type="button"]', function(){
alert($(this).val());
});
// we bound the click listener to .container child elements so any buttons inside of it get noticed
$('.container').append('<input type="button" class="dynamically_added" value="button2">');
$('.container').append('<input type="button" class="dynamically_added" value="button3">');
$('.container').append('<input type="button" class="dynamically_added" value="button4">');
$('.container').append('<input type="button" class="dynamically_added" value="button5">');
});
HTML
<div class="container">
<input type="button" class="dynamically_added" value="button1">
</div>
I'm working on a code-base with a friend that has a similar requirement. The delegated event handler option is definitely best if all you want is to attach event handlers. An alternative, especially if you need to do other DOM processing in your $(document).ready function, is to put the code you want run into a script element at the end of your code. Basically, instead of:
<script type="text/javascript">
$(document).ready(function() {
// Your code here
});
</script>
<!-- rest of dynamically loaded HTML -->
Try swapping the script and the rest of the HTML around so you have:
<!-- rest of dynamically loaded HTML -->
<script type="text/javascript">
// Your code here
</script>
This forces the browser to only process your code once it has loaded every other DOM element in the dynamically loaded HTML. Of course this means you'll have to make sure the inserted HTML does not have unintended UI consequences by using CSS/HTML instead of JS. Its an old Javascript trick from years gone by. As a bonus, you don't need jQuery for this anymore.
I should mention that in Chromium v34, putting a second $(document).ready call inside a <script> tag in the dynamically loaded HTML seems to wait for dynamically loaded DOM to load and then runs the function as you described. I'm not sure this behaviour is standard though as it has caused me great grief when trying to automate tests with this kind of code in it.
JQuery AJAX .load() has a built-in feature for handling this.
Instead of simply $('div#content').load('such_a_such.url'); you should include a callback function. JQuery .load() provides room for the following:
$('div#content').load('such_a_such.url',
{ data1: "First Data Parameter",
data2: 2,
data3: "etc" },
function(){ $('#span1').text("This function is the equivalent of");
$('#span2').text("the $(document).ready function.");
}
);
However, you do not need to include the data argument.
$( "#result" ).load( "ajax/test.html", function() {
alert( "Load was performed." );
});
http://api.jquery.com/load/
alert() is working fine, but when I tried to make a link bold, it is not working.
I think it is because of page is already loaded. Is there any way to do that?
you can do it using jquery:
$("selector").css('font-weight', 'bold');
Using Jquery:
Use ready() to make a function available after the document is loaded:
The ready event occurs when the DOM (document object model) has been loaded.
Because this event occurs after the document is ready, it is a good place to have all other jQuery events and functions.
The ready() method specifies what happens when a ready event occurs.
$(document).ready(function(){
$('selector').css('font-weight','bold');
});
Using Javascript:
The onload event is a standard event in the DOM, while the ready()
event is specific to jQuery. The purpose of the ready event is that it should occur as early as possible after the document has loaded, so that code that adds functionality to the elements in the page doesn't have to wait for all content to load.
window.onload = function () {
all your code goes here.
}
I have a really strange problem. My example code works [here][1] quite fine, but I have the exactly same code in my aptana studio editor and when I try it in Chrome or the Eclipse browser the events just don't fire. I can't imagine what's the problem, because it's exactly the same code ...
HTML
<!DOCTYPE html>
<html>
<head>
<title>OrderScreen</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script src="js/script.js" type="text/javascript"></script>
</head>
<body>
Test
</body>
</html>
jQuery
$("a").mouseup(function() {
clearTimeout(pressTimer);
// Clear timeout
return false;
}).mousedown(function() {
// Set timeout
pressTimer = window.setTimeout(function() {
alert("hcbdhaf")
}, 1000);
return false;
}).click(function() {
alert("dfsdg");
});
If your code is really as quoted, the problem is that the elements don't exist as of when you try to hook event handlers to them. jsFiddle's default settings hide this problem from you. (Look on the left, and you'll see that your code isn't run until the load event fires — which is very, very late in the page load process.)
To fix it, either:
Move your script tags to the end of your document, just before or after the closing </body> tag. By the time the browser runs your script, the elements will exist. This is the recommendation of the YUI team and Google's web engineers like it too.
Use jQuery's ready event.
In conjunction with either of those, you might also look at using event delegation instead of directly hooking up events on the elements. Your mouseup and mousedown handlers will get attached to each a element individually. That's a lot of hookups. If there's a container that all of those a elements are in (body or better yet, something nearer), you might instead hook the event on that container (since those events bubble) and then check to see if the event originated in an a element. jQuery supports event delegation, doing most of the hard work for you, via delegate (which I like because it's so explicit) and more recently, one of the half-dozen variations of arguments you pass to on.
Suppose I have an element on my page with id "some_id". I want to call a function as soon as I encounter this element. Something like following.
$("#some_id").call_a_function(function () {
// do stuff
});
Not sure what you mean by "encounter this element". If you mean as soon as the element is parsed, you could always inline some script right after it:
<div id="some_id">Hello</div>
<script type="text/javascript">
$("#some_id").call_a_function(function () {
// do stuff
});
</script>
The javascript code will be parsed right after the div. Of course, this wouldn't be much quicker than using $(document).ready() on small pages.
Checkout this jquery plugin as an alternative to $(document).ready()
http://plugins.jquery.com/project/available
Allows you to specify a handler to a DOM element as soon as it becomes available.
My main HTML page does the following:
var popup = window.open(...);
// Wait for popup to load
popup.onload = function() { do_something(); };
popup.location = "new-page.html";
I'd like do_something to be called when new-page.html is finished loading. But what I currently have doesn't work -- do_something is never called.
How can I make this work?
I only care about getting this to work in Firefox 3.5, if that makes things easier.
you could use window.opener.<functionName> and put your notification code within that function on the parent page
Have you tried using the opener object?
http://www.webreference.com/js/tutorial1/opener.html
Or, without messing with the HTML of the child window, from the parent, you can attach a listener on the load event of the iframe. In this solution, i am going to use jQuery for simplicty, but any library or even manual event attachment will do.
In the parent's HTML:
<iframe id="foo"></iframe>
<script type='text/javascript'>
var element = $("#foo");
element.load( function( eventObject ) {
// do something here
} );
// Now that the event listener is attached, we can set the source.
element[0].src = "foo.html";
</script>
Note, I have not tried setting the source first and then attaching the listener, I am not sure if this would be guaranteed to always work. It could happen that the iframe is created/loaded before the load listener is attached, I am not sure. But, by setting the src after the listener is attached, I am sure that the load listener will be called.
Shane
http://www.shanetomlinson.com
http://www.ubernote.com
Try having the doSomething method called in the popup's onload. You can refer back to the parent by using window.opener
In your .html that is loaded you could have a simple one liner at the end that calls a function on the opening window (if it exists)
<script type='text/javascript'>
if (window.opener && window.opener.do_something) window.opener.do_something(window);
</script>