How to run one javascript function on two different events? - javascript

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.)

Related

Trigger jquery .on() on page load

I am trying to find out if I can trigger some javascript code when page has loaded and not only on keyup
$(document).on('keyup', '.some-class', function (e)
{
// Some code
});
I have tried the following and that didn't work (my research indicate that it shouldn't work either):
$(document).on('keyup load', '.some-class', function (e)
{
// Some code
});
$(window).on('keyup load', '.some-class', function (e)
{
// Some code
});
UPDATE:
My question seems to be unclear in regards to what I want to accomplish. The code works fine when using keyup in an input field.
But I also want the code to run when the page loads.
I could do this but I am looking for a solution that are more elegant.
hello();
function hello() {
// Some code
}
$(window).on('keyup load', '.some-class', function (e)
{
hello();
});
Whilst you CAN trigger the keyup function on page load, I wouldn't recommend it. You're much better off defining the function you want to run elsewhere, then calling it on both load and keyup.
This way if you ever want to add anything to the keyup event that doesn't need to run on load, you can.
Something like, but not necessarily this, would work:
var myFunction = function() {
// Do some function stuff
return;
}
$(document).ready(myFunction);
$('.myElement').on('keyup', myFunction);
Or if you need to pass arguments to the function (which is a little closer to your use-case):
var myFunction = function(args) {
// Do some function stuff
return;
}
$(document).ready(function() {
myFunction(args)
});
$('.myElement').on('keyup', function(e) {
e.preventDefault();
myFunction(args);
// You can add more code here that won't be triggered on load
});
Maybe you are searching for $( document ).ready(). When the document is ready just run the code
$( document ).ready(function() { /* YOUR CODE HERE (maybe the $(document).on('key up'... */})
It sounds to me like you are wanting something like the following:
jQuery(document).ready(function(){
//Code Here
)};
Or window load (which was deprecated in 1.8 thanks to #charlietfl):
jQuery(window).load(function(){
//Code Here
)};

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/

Javascript, Jquery append functions to an event

I have a function that is associated with an event, say onfocus() and in some cases, I want to be able to execute the default function as well as one or more additional functions.
So I don't want to replace the original function, but I want to append another so that both functions will fire.
<div id="mydiv" onfocus="alert('hello');">
if(something == somethingelse) $('#mydiv').onFocus += "alert('world');"
So in this example, sometimes just Hello will Fire and sometimes Hello and then World will both fire.
I'm just using onfocus() and alert() as an example, these would actually be functions that I have defined.
How do I go about doing this ?
Use jQuery to add a focus event handler
<script>
$('#mydiv').on('focus', function(){
//do soemthing
})
</script>
If you work with jQuery don't use inline event bindings, use the following instead:
$("#mydiv").on("focus", function() {
alert("hello");
});
// add one more action for the same event
$("#mydiv").on("focus", function() {
alert("world");
});
You should do
$('#myDiv').on('focus', function(){alert('world')});
$('#mydiv').focus( function(){
})//This is for the elements which load while the page is loading
or
$('#mydiv').on('focus', function(){
}) //This is for the elements which will load dynamically after the page load completed.
If you don't want to use jQuery try this, its an pure javascript equivalent:
document.getElementById("mydiv").addEventListener("focus", function() { alert('world'); });
and if you want it to be compatible with IE8 and older you should try
var el = document.getElementById("mydiv");
if(el.addEventListener)
el.addEventListener("focus", function() { alert('world'); });
else
el.attachEvent("focus", function() { alert('world'); });
if you're using jQuery, you want to use on() to bind event handlers to elements as opposed to specifying them inline
$('#mydiv').on('focus', function () {
alert('hello');
});
$('#mydiv').on('focus', function () {
if (something === somethingelse) {
alert('world');
}
});
or combining into one handler function seems reasonable in this case
$('#mydiv').on('focus', function () {
alert('hello');
if (something === somethingelse) {
alert('world');
}
});
When specifying them inline as you have done, only one event handler can be bound to the event so if you want to bind multiple event handlers, you either need to bend the one event handler limitation to handle this or use another approach, such as DOM Level 2 events or an abstraction on top of it (such as jQuery's on() function).
Event handlers need to be bound when the element to which you are binding the handlers exists in the DOM. To do this, you can use jQuery's ready() function
// bind an event handler to the "ready" event on the document
$(document).ready(function () {
// ..... here
});
or shorthand
$(function () {
// ..... here
});

Onload fires no matter where I place it

Right, I'm getting quite aggitated with this. I'm probably doing something wrong, but here's what I'm doing:
$(document).ready(function () {
$('#somebutton').click(function () {
openPage1();
});
$('#someotherbutton').click(function () {
openPage2();
});
});
var openPage1 = function () {
$('#iframe').attr('src', 'someurl');
$('#iframe').load(function () {
$('#button').click();
});
};
var openPage2 = function () {
$('#iframe').attr('src', 'anotherurl');
$('#iframe').load(function () {
$('#anotherbutton').click();
});
}
Whenever I click somebutton everything goes as expected. However when I click someotherbutton. The .load() from openPage1() is called first and I can't find a way to stop that. The .load() from openPage1() has a button with the same name, however on openPage2() I need to modify the contents before clicking the buttons.
I need to use .load() because I can't click the buttons before the document is ready.
Basically what I need is two seperate .load() instances on the same iframe, that don't fire off on each other.
Besides that, maybe my understanding of jQuery/JS is wrong, but shouldn't the .load() events only be listening after clicking the corresponding button?
Can someone help me out, this has been keeping me busy all afternoon.
Try using on, and once loaded, unbind
$("#iframe").on("load", function(){
$(this).off("load");
$('#button').click();
});
That way you remove the handler you put up before the second button is clicked?
By writing : $('#iframe').load(function (){ $('#button').click(); });, you are adding a listener on the load event, which will stay and be re-executed on each subsequent reload of the iframe.
Here is a jsfiddle to demonstrate this : click on the "reload" button, and see how many times the "loaded" message appears in your console.
in your case, if you click on #somebutton, then on #someotherbutton, after the second click, you will have two handlers bound on the load event, and both will be triggered.
If you click 5 times on #somebutton, you should end up calling 5 times $('#button').click().
If you want to execute it once, you can follow Fred's suggestion, or use jQuery .one() binder :
$('#iframe').one('load', function(){ $('#button').click() });
Here is the updated jsfiddle : 'loaded' should be displayed only once per click.
Maybe try and replace the lines in both functions like this:
$('#iframe').load(function() {
$('#anotherbutton').click();
};
$('#iframe').attr('src', 'anotherurl');
Otherwise it might be firing the event before the new event-handler has been set.
This isn't really an answer to your problem Now it is an answer, but I think utilizing functions as they were intended could be beneficial here, i.e.:
//Utilize a single function that takes arguments
var openPage = function (frame, src, eventEl) {
frame.attr('src', src); // If you pass frame as a jQuery object, you don't
frame.on("load", function(){ // need to do it again
$(this).off("load");
evEl.click(); //Same for your buttons
});
}
//Simplify other code
$(document).ready(function () {
$('#somebutton').click(function () {
openPage($("#iframe"),somehref,$("#buttonelement"));
});
$('#someotherbutton').click(function () {
openPage($("#iframe"),anotherhref,$("#someotherbuttonelement"));
});
});

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