jquery that just waits - javascript

I normally set up my javascript code to have a function. But due to the fact that the application generates most of the HTML and javascript calls from a VB6 application I would like to create a jQuery function that is more like a listener. So for example if I have a td tag that has the class 'gridheader1' I would like the jQuery to wait for it to be clicked.
I'm assuming that I would use the bind... But I'm getting javascript errors with it... If you can offer suggestions on where my code is wrong that would be great.
$('.gridheader1').bind('click', function()
{
alert('hi I got clicked');
});
Again this just has to sit out there on the main .js file. It isn't attached to any functions. Please let me know.
Thanks

you want
$('.gridheader1').bind('click', function(){
alert('hi I got clicked');
});
note the dot at the start of selector - it means class

// static tags
$(function(){ // DOM ready
$('.gridheader1').click(function()
{
alert('gridheader1 clicked');
});
});
// or if the tag is loaded via ajax use 'live'...
$(function(){ // DOM Ready
$('.gridheader1').live('click', function()
{
alert('gridheader1 clicked');
});
});
// or if you already have a function defined that you want to call, you can pass in the function instead of using an anonymous function.
function alertAboutStuff(){
alert('gridheader1 clicked');
}
$(function(){
$('.gridheader1').click(alertAboutStuff);
// $('.gridheader1').live('click', alertAboutStuff); // for tags loaded via ajax
});

Related

jQuery bind event not firing on elements loaded via $().load()

I have a DIV that is in an .html file that is loaded into my document via:
$(document).Ready( function() {
$("#contentDiv").load("some.html")
//some.html contains a button id=saveButton
$("#saveButton").click( function () {
alert("Here I am!");
}
});
The event will not fire. If I cut the content of some.html and put it in the document, uhm, "physically", the event will fire.
So, I am pretty sure this issue is related to the fact that the html is injected via .load().
It's bothersome, because if you look at the page source, all the HTML is in fact there, including the button.
So, the question is, is there ANY way to make this work? I am using .load() to reduce page complexity and increase readability, and, code-folding notwithstanding, I really do not want to have to pull all this HTML into the document.
EDIT: This code was just typed in off the cuff. It's not a cut-n-past of the actual code, and it is just to demonstrate what the problem is. But, thanks for pointing it out.
EDIT2: Grrrrrrr. });
load() is asynchronus so you need to the job in the callback :
$(document).ready(function() {
$("#contentDiv").load("some.html", function(){
//some.html contains a button id=saveButton
$("#saveButton").click( function () {
alert("Here I am!");
});
});
});
Hope it helps :)
one way is by adding to the some.html the script line which will be loaded as the div appears.
You can add this script to some.html(in a script tag):
registerButton();
and then you can define registerButton() in your current document.
other way, if I remember correctly is by using something like the function bind( )
If you want to fire event on element which was not available at the time when DOM was ready then you need to use .on event.
http://api.jquery.com/on/
$("#saveButton").on("click", function() {
alert("Here I am!");
});
jquery load() function is asynchronous. If you want to bind events to the loaded content, you should put the code into the callback function:
$(document).ready(function() {
$("#contentDiv").load("some.html", function() {
//you should put here your event handler
});
});
Your issue is that jquery load() function is asynchronous as #lucas mention. But his code has syntax errors, try this:
$(document).ready(function () {
$("#contentDiv").load("some.html", function () {
$("#saveButton").click(function () {
alert("Here I am!");
});
});
});
Hope it helps now
You need to bind the event handler either after the load OR to the container of the HTML from the load
$(document).ready(function() {
$("#contentDiv").load("some.html", function() {
$("#saveButton").on('click',function() {
alert("Here I am! Bound in callback");
});
});
});
OR use: (not needed that it be in the document ready just that the contentDiv be present)
$("#contentDiv").on('click','#saveButton',function(){
alert("Here I am! bound to container div");
});
EDIT: load on the SAVE button click (per comments) (this makes no sense though)
$(document).ready(function() {
$("#saveButton").on('click',function() {
$("#contentDiv").load("some.html", function() {
alert("Here I am! Bound in callback");
});
});
});

JavaScript Pop up : Invoking in JQuery

In my application I am using a simple JavaScript popup and successfully invoking it this way-
<a href="javascript:popup('Hello World')>Click Me</a>
I was wondering whether it is possible to invoke the same popup on other jQuery events. For instance
$("#some_button_id").click( function() {
javascript:popup('Hello World');
});
The above method doesn't work. Any other solution?
EDIT - You don't need the javascript: part because you are not attaching javascript inline.
But that is not the cause of the error so make sure that you wait until the DOM is ready before attaching an event handler.
$(function(){
var popup = function(msg){
alert(msg);
}
$("#some_button_id").click( function() {
popup('Hello World');
});
});
and of course make sure you define popup() somewhere
If the popup function is defined on your page then you should use
$("#some_button_id").click( function() {
popup('Hello World');
});
The javascript: prefix is only needed when you use javascript code directly inside your html attributes.
$("#some_button_id").click( function() {
popup('Hello World');
});
should work.
EDIT
this will work for sure if the id exit when the event if fired , wether or not it has been created when the the listener was added , it is called delegation :
$(document.body).click( function(e) {
if(e.target.getAttribute("id")=="some_button_id"){
popup('Hello World');
}
});

Do something AFTER the page has loaded completely

I'm using some embed codes that insert HTML to the page dynamically and since I have to modify that dynamically inserted HTML, I want a jquery function to wait until the page has loaded, I tried delay but it doesnt seem to work.
So for example, the dynamically inserted HTMl has an element div#abc
and I have this jquery:
if ( $('#abc')[0] ) {
alert("yes");
}
the alert doesn't show up.
I'd appreciate any help
Thanks
$(window).load(function () {
....
});
If you have to wait for an iframe (and don't care about the assets, just the DOM) - try this:
$(document).ready(function() {
$('iframe').load(function() {
// do something
});
});
That is the purpose of jQuery's .ready() event:
$(document).ready(function() {
if ( $('#abc').length ) //If checking if the element exists, use .length
alert("yes");
});
Description: Specify a function to execute when the DOM is fully
loaded.
Using the jQuery.ready should be enough. Try this
$(document).ready(function(){
//your code here
});
or
$(function(){
});
which is a shortcut of the first.
The load() method was deprecated in jQuery version 1.8 and removed in version 3.0.
So you have to use -
$(window).on('load', function() {
// code here
});
Try this:
$(document).ready(function () {
if ( $('#abc')[0] ) {
alert("yes");
}
});
$(window).load(function () { ... }
can be enough but otherwise your embeded code (what ever that can be) might provide some callback functionality that you can make use of.
delay() should only be used to delay animations.
Generally, to handle my JQuery before or after page loads, will use:
jQuery(function($){
// use jQuery code here with $ formatting
// executes BEFORE page finishes loading
});
jQuery(document).ready(function($){
// use jQuery code here with $ formatting
// executes AFTER page finishes loading
});
Make sue you bind the event with dom load so it's there when trigger called.
This is how you do it. Hope this helps someone someday
$(window).bind("load", function() {
//enter code here
$("#dropdow-id").trigger('change');
});`

Can I call $(document).ready() to re-activate all on load event handlers?

Does anyone happen to know IF and HOW I could re-call all on-load event handlers? I'm referencing some .js files that I DON'T have control over, and these .js libraries do their initialization in $(document).ready(), and unfortunately don't provide any easy function to re-initialize.
I'm currently trying to replace a large div block with content from an ajax call, and so I have to re-initialize the external libraries. So, it would be nice just to call $(document).ready() in order to re-initialize EVERYTHING.
So far, I've tried this on the ajax call:
success: function(data) {
alert('1'); // Displays '1'
$('#content').html(data);
alert('2'); // Displays '2'
$(document).ready();
alert('3'); // Does not display
}
Calling $(document).ready(); fails quietly too. JavaScript console shows no errors. Does anyone know if this is possible (without modifying javascript library files)?
Since you asked how to do it without modifying the external JS files, I'll answer that way. I've traced through the .ready() function in jQuery in the debugger and it appears that the root function that gets called when the page is ready is this:
jQuery.ready();
But, it appears you cannot just call it again to accomplish what you want because it appears that when it fires the first time, it unbinds from the functions that were previously registered (e.g. forgetting them). As such, calling jQuery.ready() manually a second time does not retrigger the same function calls again and I verified that in the debugger (breakpoint was only hit once, not second time).
So, it appears that you cannot solve this problem without either changing the jQuery implementation so it doesn't unbind (to allow multiple firings) or changing each piece of ready handler code to use your own events that you can fire as many times as you want.
I did something like:
// When document is ready...
$(function(){
onPageLoad();
});
function onPageLoad(){
// All commands here
}
Now I can call this function anytime I need.
A simple way to achieve this is just to invent your own event like this:
$(document).bind('_page_ready', function() { /* do your stuff here */});
Then add this:
$(function() { $(document).fire('_page_ready'); }); // shorthand for document.ready
And last, whenever you need to run it again you simply call this:
$(document).fire('_page_ready');
[Edit]
If you really can't edit the external script-files I've made a jsFiddle that makes what you want to do possible, you can take a look at the code here: http://jsfiddle.net/5dRxh/
However, if you wan't to use this, it's important that you add this script RIGHT AFTER you include jQuery, like this:
<script src="jquery.js" type="text/javascript"></script>
<script>
//script from jsFiddle (only the plugin part at the top).
</script>
<!-- All the other script-files you want to include. -->
You can trigger document.ready second time if you change entire body content:
$('body').html($('body').html())
I don't think that this can be done since jquery unbinds the ready event after it is executed. From the source:
// Trigger any bound ready events
if ( jQuery.fn.trigger ) {
jQuery( document ).trigger( "ready" ).unbind( "ready" );
}
You can do this simple.
Make a function:
function REinit() {
/// PLACE HERE ALL YOUR DOC.READY SCRIPTS
}
Place just the Reinit() function inside doc.ready:
$(document).ready(function(){
REinit();
});
then after an ajax action just call
REinit();
I think it is straight forward to just change the ready event to pjax success
Change it from:
$(document).ready(function() {
// page load stuff
});
To:
$(document).on('ready pjax:success', function() {
// will fire on initial page load, and subsequent PJAX page loads
});
This will be what you want, just hold the ready event until you are really ready.
https://api.jquery.com/jquery.holdready/
Or, try this:
jQuery.extend ({
document_ready: function (value) {
$(document).ready (value);
$(document).ajaxComplete (value);
}/* document_ready */
});
And instead of defining a function by saying:
$(document).ready (function () { blah blah blah });
say:
jQuery.document_ready (function () { blah blah blah });
Explanation:
Any function loaded to "document_ready" will be automatically loaded into both "$(document).ready ()" and "$(document).ajaxComplete ()" and will fire under both circumstances.
I just had the problem that my ajax code only worked if it gets called by the $(document).ready(function(){}); and not in a regular function, so I couldn't wrap it.
The code was about loading a part of my page and because of some loading errors I wanted it to be called again after a timeout.
I found out that the code doesn't have to be in the $(document).ready(function(){}); but can be run by it and can also be called by itself.
So after I read many solutions from different pages now I've got this code mixed together:
$(document).ready(loadStuff);
function loadStuff(){
$.ajax({
type: "POST",
url: "path/to/ajax.php",
data: { some: data, action: "setContent"},
timeout: 1000, //only one second, for a short loading time
error: function(){
console.log("An error occured. The div will reload.");
loadStuff();
},
success: function(){
$("#divid").load("path/to/template.php"); //div gets filled with template
}
});
}

Jquery bind()/live() within a function

I wrote a little pager which removes and rewrites content. I have a function called after loading the page, it shall be executed after changing the page as well. Because I do not wat to implement the function twice (on initialisation and after changing the page) I tried bind()/live() and a simple function.
The function looks like this:
jQuery('.blogentry').each(function (){
jQuery(this).click(function(){
//Clicking on the element opens a layer, definitely works - I tested it
});
});
It is executed after initialisation, for executing it after page changes as well I tried the following:
jQuery('.nextPage, .prevPage').click(function changePage(){
// Changing page and rewriting content
showEntry();
});
//...
showEntry();
//...
function showEntry(){
jQuery('.blogentry').each(function (){
jQuery(this).click(function(){
//Clicking on the element opens a layer, definitely works - I tested it
});
});
}
But the function is not executed if put inside a function (lol) and called via showEntry();
Afterwards I tried to bind the function...
jQuery('.nextPage, .prevPage').click(function changePage(){
// Changing page and rewriting content
jQuery('.blogentry').bind("click", showEntry);
});
//...
jQuery(this).click(function showEntry(){
//Clicking on the element opens a layer, definitely works - I tested it
});
Did not work either. Code after the bind()-line would not execute as well.
I thought maybe it's a problem to bind to an event function, if an event is already given via the parameter so i also tried this:
jQuery('.nextPage, .prevPage').click(function changePage(){
// Changing page and rewriting content
jQuery('.blogentry').bind("click", showEntry);
});
//...
function showEntry(){
//Clicking on the element opens a layer, definitely works - I tested it
});
}
No success at all. Maybe I cannot call the function from inside the function regarding to the bind()? Maybe I just do not understand the bind()-function at all? I also tried the live() function since it seemed to fit better, as I am rewriting the content all the time. But it had the same effect: none...
The simplest way to implement this should be
jQuery('.blogentry').live('click', function() { /* onclick handler */ });
This should bind the function to every blogentry on the page at the moment of the call and all the blogentries that are added to the page later on.
Additional notes:
In $(foo).each(function() { $(this).click(fun); }); the each is unnecessary - $(foo).click(fun); is enough.
$(foo).bind('click', fun); is functionally equivalent to $(foo).click(fun) - it does not matter which one you use.
You can use delegate or bind. don't call the function like that, just create a delegate with .blogentry and it should update even after you load a new page via ajax. It will automatically do this.
$("#blogcontainer").delegate(".blogentry", "click", function(){ //open layer });
This should work for you
$(body).delegate(".blogentry", "click", function(){
showEntry();
});
alternaltivly you can use event delegation
$(document).ready(function () {
$('#blogcontainer').click( function(e) {
if ( $(e.target).is('.blogentry') ) {
// do your stuff
}
});
});
hence, no need to bind each blogentry at creation or reload, and it's (slightly) faster.

Categories