So I just started with jQuery and the functions are confusing me. I want to be able to just name a jQuery function and then call it, without saying when it should be called in the function. I've looked and I can't seem to understand any of the answers. My code is below:
<script type="text/javascript">
$(function() {
$('a').click(function() {
$('#box').slideUp();
});
});
</script>
I want it to do something more like this however:
$(function slideBox() {
$('#box').slideUp();
});
</script>
And then call it through a OnClick event or something on a button.
jQuery is just a library on top of Javascript, you can still have regular functions with jQuery code inside of them. The reason most examples are of the $(function() { ... }); variety is because Javascript in general is heavily event-based and the most common time for you do to things with jQuery is on page load, which $(function() { }); is a shortcut for.
One of the nice things about jQuery is that it lets you write unobstrusive Javascript, you really shouldn't be putting any code in the onclick of any HTML elements as it is a very poor practice and a maintenance nightmare. The more standard approach is:
HTML
<input type="button" id="slideMeUp" value="Up, up, and away!">
jQuery
$(function() {
$('#slideMeUp').click(function() {
$('#box').slideUp();
});
});
However, you could easily have something like:
function slideMeUp() {
$('#box').slideUp();
}
$(function() {
// still need this outer function to indicate
// to only bind the handler when the DOM is ready
$('#slideMeUp').click(slideMeUp);
});
You are getting mixed up between jQuery, which is a Javascript library and Javascript as a whole.
To write the function slideBox() in Javascript you just do:
function slideBox() {
$("#box").slideUp();
}
You usually need
$(function() {
..
});
That's a shortcut of $(document).ready(function() {}) which runs when the page is loaded.
You can do this:
<script>
function slideBox(speed) {
$("#box").slideUp(speed);
}
$(function() {
slideBox(300);
});
</script>
Or you can create your own plugins like this:
(function($) {
$.fn.FunctionName = function() {
return this.each(function() {
$(this).slideUp();
});
};
})(jQuery);
you can save that in a separate file and then do something like this:
<script>
$(function() {
$("#box").FunctionName();
});
</script>
Have a look at this:
http://docs.jquery.com/Plugins/Authoring
There isn't any difference between a JavaScript function and a jQuery function; it's the same technology.
If you want to define a function that slides the box up, just write one, and then hook it up to the onclick event. Here's how I would do that:
<script type="text/javascript">
function slideBox() {
$('#box').slideUp();
}
$(function() {
$('a').click(function() {
slideBox();
});
// or, as Paolo shows:
$('a').click(slideBox);
});
</script>
The $(function() { }); syntax is short for:
$(document).ready(function() {
// do things when the DOM is ready
});
Whatever you put inside it will be delayed until the DOM is finished loading. If the latter makes more sense to you, use that instead.
You can define a function and pass it to the click handler:
<script type="text/javascript">
function onClick() {
$('#box').slideUp();
}
$("#MyButton").click(onClick);
</script>
Use your original function ie
<script type="text/javascript">
$(function() {
$('.uniqueclass').click(function() {
$('#box').slideUp();
});
});
</script>
I have changed the 'a' to 'uniqueclass'
then
create a button with the class of .uniqueclass - on clicking it, the function will fire
You don't want your function to be declared in the global scope (as a general rule), so you would declare it inside of jQuery's document ready and access your function through an event:
<script type="text/javascript">
// jQuery document's ready
$(function() {
// your function
var slideBox = function() {
$('#box').slideUp();
};
// event
$('a').click(function() {
// call to your function
slideBox();
});
});
</script>
Related
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
)};
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/
In my application I have a script:
<script type="text/javascript">
function pageLoad(sender, args){
$('#nursing').click(function () {
document.getElementById("ddlPositionType").selectedIndex = 1;
$("#btnSearch").click();
a.href = "#";
return false;
});
}
</script>
Then below it I am attempting to call it when the page is loaded like this:
<script type="text/javascript">
$(document).ready(function () {
$('#nursing').click();
});
</script>
This does not fire when the page load as it should and it causes no errors in my console. What is most confusing is that if I took from document to return false from the first code block and placed it where I am trying to call the $('nursing').click(); the code will run like it is supposed to.
As reference #nursing is simply a link used on my slider to control content.
<a id="nursing" class="oslide">Nursing Positions</a>
The code you've written in pageLoad is an instruction to set up a click handler. That setup will not be executed unless the pageLoad function is called prior to your call to click the button in document.ready. The easy fix may be to simply modify your code so that it calls pageLoad, and then clicks the anchor.
<script type="text/javascript">
$(document).ready(function () {
pageLoad();
$('#nursing').click();
});
</script>
But this seems a lot of overkill to call a function by performing a click. Why not just make a function out of the click handler and call that code in document.ready instead? If you still need the click handler, call the function in the click handler.
function onNursingClick() {
document.getElementById("ddlPositionType").selectedIndex = 1;
//... and so on....
}
function pageLoad() {
$("#nursing").click(onNursingClick);
}
$(function() { //shorthand for $(document).ready(...);
onNursingClick();
pageLoad();
})
It's not working because in your document.ready script you're not calling the function pageLoad() that you created earlier. You are firing a click event. So try this:
<script type="text/javascript">
$(function(){ //Jquery shorthand for document.ready
pageLoad(sender, args); //pass in what you need
});
</script>
I need to run a function after the HTML on my page has been rendered (because I need to get the height of a particular dynamic div). I have tried several methods, but I cannot get window.load to fire (I am using Chrome).
I've placed all of the following code below in the constructor of my TypeScript ViewModel.
This doesn't work:
$(window).on('load', function () {
...code...
});
And neither does this:
$(window).load(function(){
...code...
});
Or this:
window.addEventListener('load', function () {
...code...
});
Any ideas why none of these work? If there's another method to go about doing this, I'm open to suggestions.
Try putting it inside the following:
$(document).ready(function() {
jQuery.event.add(window, "load", myFunction);
myFunction() {
...code...
}
});
This worked for me when I had to manipulate a <div> based on its height after rendering.
I have the following example: http://jsfiddle.net/gespinha/yTjUL/13/
The variable should be triggered on click, making the link change class from on to off and change colour from red to green. But instead it starts already green, thus making the function useless.
Why does it not work?
HTML
<a id="link" href="javascript:void(0)" class="on">CLICK HERE</a>
JQUERY
$(document).ready(function () {
var $myVar = $(document).find('.on').addClass('off').removeClass('on');
$('link').click(function () {
$myVar
});
});
You seem to be under the impression that the variable will store a chain of actions to perform later, when the variable is 'called,' but that's not (clearly) what happens: the first line, within the ready() handler, in the var assignment, finds the .on element and performs the actions you specify, storing the .on element(s) in the variable (as jQuery methods almost all return the this object).
Instead:
$(document).ready(function () {
// use the `#link` notation, since 'link' is the id of the element:
$('#link').click(function () {
// assign a function to the click-event handler:
$('.on').addClass('off').removeClass('on');
});
});
Or, more simply (if you want to toggle between 'states') use toggleClass() and $(this) (rather than selecting from the whole of the document each time the user clicks the given element):
$(document).ready(function () {
$('#link').click(function () {
$(this).toggleClass('on off');
});
});
Also, rather than using javascript:void(0) in the href, simply use jQuery to prevent the default action, with:
$(document).ready(function () {
$('#link').click(function (e) {
e.preventDefault();
$(this).toggleClass('on off');
});
});
JS Fiddle demo.
References:
click().
event.preventDefault().
toggleClass().
It doesn't work that way, the variable will just contain the result of whatever methods you called, and for jQuery that means the element will be returned, so the variable $myVar only equals $(document) inside the event handler, it does not call the chained methods again.
You have to do:
$(document).ready(function () {
$('#link').on('click', function () {
$('.on').toggleClass('on off');
});
});
$(document).ready(function () {
$('#link').click(function () {
$(".on").addClass("off").removeClass("on");
});
});
As Guilherme Sehn noted, the $myVar variable is not needed. Just put your code in the click event. In addition, the link selector needs to be "#link", not "link".
By doing this, you'll be executing these actions and storing the return value (which will be the jQuery elements) inside $myVar. You can just put your code inside the click trigger function.
$('#link').click(function () {
$('.on').addClass('off').removeClass('on');
});
Also, you forgot the # before your ID. Without that your code will select link tags, not the element with the id link. And you do not need to explicity use $(document).find('.on') as all DOM elements are inside it.
I guess you meant $("#link")... and not $("link")
And if I understand right - the full script should be:
$(document).ready(function(){
$("#link").click(function(){
$(".on").addClass("off").removeClass("off");
});
});
You don't invoke the function and your selector is wrong.
$(document).ready(function () {
$('#link').click(function () {
$(document).find('.on').addClass('off').removeClass('on');
});
});