Passing a function to the jquery On event handler - javascript

This works:
$(".logo").click(doSomething)
This does not:
$('.popular').on '.logo', 'click', doSomething
I need the latter because some .logo elements are loaded using AJAX after the page is done loading.
What can I do to fix it?

You can write
$('.popular').on('click','.logo', function() {
// do something
topServiceClicked();});

Related

jQuery trigger on page load

How can I make jQuery run when my webpage has finished loading?
This is not what I want. All that this does is wait for the page to finish loading before any Javascript CAN be run.
$(document).ready(function(){
//Code here
});
What I want is for this to run when the page loads. I don't want it to wait for 'click' or 'change'. Can I add a 'load' or something to this?
$(document).on("change", "#input", function(e) {
$("#output").val($(this).val());
});
A workaround I have been using is to use jQuery to "change" the selected option on a select box, thereby triggering the code I actually want to run.
I have seen a bunch of questions like this, but every time the answer just says to use $(document).ready(function(){//Code}); which is not what I'm looking for.
Any ideas?
EDIT: Here is a better example of what I'm looking for.
This code below will run when the element with the id of 'input' is clicked. That is the only time it will run. I would like for it to run as soon as it is ready - as soon as $(document).ready(function(){}); can run it.
$(document).ready(function(){
$(document).on("change", "#input", function(e) {
$("#output").val($(this).val());
});
});
I think that this would work, but I was hoping for a nicer solution and one that doesn't require me to rewrite everything as functions.
$(document).ready(function(){
function runWhenReady(){
$("#output").val($(#input).val());
}
$(document).on("change", "#input", function(e) {
runWhenReady();
});
runWhenReady();
});
I think that this will run runWhenReady() when #input is clicked, and when the page finishes loading. My question is, is there a simpler way to do this?
I think the only way to do what I want is to name the function and call it two different ways.
$(document).ready(function(){
function xyzzy(){
$("#output").val($(#input).val());
}
//Call the function when #input is clicked
$(document).on("change", "#input", function(e) {
xyzzy();
});
//Call the function when the page loads
xyzzy();
});
This will call the function when the page has finished loading, as well whenever #input is clicked.
I think you're looking for $(window).load()
$(window).load(function(e){
// code here
});
Answer to your question in the comments:
$(document).on('click', '#input', function(e){
$('#output').val($(this).val());
});
Can I add a 'load' or something to this?
yes you can which will like $(window).on( "load", handler )
Also there is not much difference between the above code and
$( window).load(function() {
// Handler for .load() called.
});
The first method is just short cut of the second one
$(document).ready happens when all the elements are present in the DOM, but not necessarily all content.
$(document).ready(function() {
alert("document is ready");
});
window.onload vs document.onload
window.onload or $(window).load()
happens after all the content resources (images, etc) have been loaded.
$(window).load(function() {
alert("window is loaded");
});
From your Example:
$(document).ready(function(){
function runWhenReady(){
$("#output").val($(#input).val());
}
$(document).on("change", "#input", function(e) {
runWhenReady();
});
runWhenReady();
});
You could write:
$("#input").on("change", function() {...});
which defines a handler for your input. Everytime you change the value in the input it will call the function passed as argument. That make the whole $(document)... unneccessary.
If you want to run the function just once, as soon as possible wrap it in a IIFE like:
(function(){...});
Here is a pretty good blog post about IIFE:
http://benalman.com/news/2010/11/immediately-invoked-function-expression/

How to run one javascript function on two different events?

I have one javascript function and I want run it on two diferent events - document.ready and window.scroll. How to do it?
Guessing you're using jQuery (document.ready and all).
Attaching the event handler to the window after document.ready, and then triggering the event immediately fires the handler on document.ready and on every scroll event.
$(document).ready(function() {
$(window).on('scroll', function() {
// do stuff
}).trigger('scroll');
});
or to reference a function
$(document).ready(function() {
$(window).on('scroll', myJavascriptFunction).trigger('scroll');
});
function myJavascriptFunction() {
// do stuff
}
call it like
$(document).ready(function(){
$(window).scroll(function(){
//some func
});
//same func
})
also use it like this on onscroll
If u want it on doc.ready too then write 2nd time too(though its not a good idea.)

jQuery override an on() event with another on() event

I have 2 files, file 1 (head.tpl) contains this default function operation
$(document).on("click", "#blackout", function(){
closeSkyBox();
});
That is the default operation I want to run, and it works.
On my second page, I would like to override the operation that is in head.tpl with this:
$(document).on("click", "#blackout", function(){
closeSkyBox(function(){
pev_for_country = '';
});
});
So, now when I test the code, each one runs, so If I were to place an alert (for testing reasons) I get two alert boxes. How can I make it so only the one in the second page runs, and the one in head.tpl is disabled. Then when I don't override it say on a third page, the one in head.tpl runs?
Looks like you're looking for jQuery's .off
$(document)
.off('click', '#blackout')
.on('click', '#blackout', function () {
// ...
});
You can use .off to remove all event handlers, but you should be cautious: what if other libraries add event handlers that you don't want to remove subscribe to this event? Also, if you add an additional event handler at a later date, this would obliterate it.
A better approach, I think, is to create a function that you can override:
function blackoutClick() {
closeSkyBox();
}
And set up your click handler:
$(document).on("click", "#blackout", function(){
blackoutClick();
});
Or, as Paul pointed out in the comments below, you don't even need to wrap that handler in an anonymous function, you can just use the cleaner:
$(document).on("click", "#blackout", blackoutClick );
Then, in your second page, you can just modify that function:
function blackoutClick() {
closeSkyBox(function(){
pev_for_country = '';
});
I believe another way to do it is also to set the event to null...
$(document).on('click', '#blackout', null);
before you re-set it on your second page.

jquery function not getting called inside of an ajax function

So im trying do disable links on some <li> ellements that have been loaded in from another page using an .load() function, but for some reason i'm not able to effect those list items.
var from_post = false;
$(document).ready(function() {
//so this is the function that loads in data from another page
$("#gallery").load('http://localhost/index.php/site/gallerys_avalible/ #gallerys_avalible'), function() {
console.log('hello');
// sense there are no other li elliments on the page i thought this
// would be okay. but this function never gets called, i've moved it
// all over i just recently attached it to the load function thinking
// that maybe if the load was not complete it would not run, but i
// have had no luck.
$('li').click(function (e) {
e.preventDefault();
console.log("I have been clicked!");
return false;
});
};
$('#addNew').click(function () {
console.log('i got called');
$('#new_form').fadeIn(1000);
});
$('form').submit(function() {
if(from_post) {
//submit form
return true;
} else {
//dont submit form.
return false;
}
});
any help would be greatly appreciated, oh and the other thing is that i can run this function through firebug, and it works 100% fine. so im stumped.
You are closing your call to .load() too early. You have:
$("#gallery").load('http://...'), function() {
That just calls load and then declares a function. But, that function is not bound to the success handler and it will never be executed. You need the ) to be on the other side of the function declaration so that the function is included as a parameter to your call to load:
$("#gallery").load('http://...', function() {
...
});
Fix that and your code works: http://jsfiddle.net/gilly3/WdqDY/
Try a future-proof event observer like live or delegate:
$('li').live('click', function(){})
or, this method is preferred if you know the parent:
$('#gallery').delegate('li','click',function(){})
The reason for needing this is your click events are being bound to elements that are on the page at the time of the binding. Any li's added later will not see that binding which is how live or delegate works. They bind to the parent and traverse the child nodes every (click in this case) event to see if the event applies to an existing child.
Use .live('click', ...) or .delegate() instead of .click(...).

Jquery calling function on hashchange

I have 2 questions
I am using the hashchange plugin .... so I want to know would a function as below, be called everytime a hashchange occurs... because I have something like that in my code and the code function apparently doesnt seems to be called
$(document).ready(function()
{
// function here
});
On the other have if I remove the hashchange as in If i make http://abc.com/a.htm#http://abc.com/b.htm as http://abc.com/b.htm
the code works fine
the problem is the structure of my pages is a bit different .... here is the fiddle with the page structure that explains on a higher level what I am trying to achieve jsfiddle.net/vBKWd/9 ... on hash change jus the div c on my page 1 gets replaced by page 2 and vice versa .... and the js function that I have shown below is getting called only once and not after hashchange
Or is therre any way I can bind the function with the div so that whenever the div is replace the function get called?
No, a ready handler is only called on document ready, not on hash change. You should use the hashchange event for that, instead:
$(window).hashchange(function () {
// function here
});
Sample: http://jsfiddle.net/vBKWd/2/
In document ready wirte code below
$(window).bind('hashchange', function () {
//code here
});
use live in this case
$(document).ready(function()
{
$(selector).live(hashchange, function(){
// your code goes here
});
});

Categories

Resources