how to combine jquery code into a javascript function - javascript

I need to add a jquery script into a javascript function and then call that function when #sortby is added to the url. Is this possible?
the jQuery
$("#myselect option[value='availability']").attr("selected","selected");
the Javascript
function sortBy(){
performanceQuery(perfpage);
tourQuery(tourpage);
return false;
}

$(window).on('hashchange', function() {
if (document.location.hash == '#sortby') sortBy();
});
function sortBy(){
$("#myselect option[value='availability']").prop("selected", true);
performanceQuery(perfpage);
tourQuery(tourpage);
return false;
}

jQuery is just a Javascipt library that provides some new functions (yes, this $ is just a funky name of a variable containing function). You can use it wherever you want.

Related

javascript autoexecuted function syntax

I've found this function and I'm not sure about what's doing
(function($) {
$(document).ready(function() {
/
$('.auto-scroll').off('click').on('click', function(event) {
event.preventDefault();
....
....
});
$("#btnBuscar").on("click", function() {
...
...
});
});
})(jQuery);
What is the meaning of pass JQuery as a parameter?
What is the meaning of pass JQuery as a parameter?
It's passing jQuery as an argument, and receiving it as the $ parameter. That way, within the anonymous function, it can use $ when using jQuery, rather than having to use jQuery. This is useful when you can't be sure that the global $ is already equal to jQuery (which it may not be, if a page has used noConflict to release it).

how to write jquery in body when using aspnetmvcturbolinks

I use aspnetmvcturbolinks in own project but, the jquery api that written in body is undefined. I move js files to head of layout .
$(document).on('keyup', 'input[name=keyword]', function () {
alert(this.attr("name"));
return false;
});
in this above code attr api is undefind!! what is solution?
thanks.
It's because you have to pass this to jQuery to use jQuery methods...
$(this).attr("name")
... else it looks into the object and returns undefined

jQuery plugin with multiple methods

I am going to wrap some of my functions in a nice manner and for this I want to go with jQuery approach. Like jQuery having a lots of methods
$.parseJson()
$.ajax()
$("div").text("hey my testing");
and both methods are present in a same jQuery file. But while reading about how to make a jquery plugin, its specified that you don't need to create multiple functions inside a same plugin. Instead pass an argument which contains the method name as string.
So, Is that the below snippet is correct or do i need to make some corrections in it.
<script type="text/javascript">
(function ($) {
$.fn.testMethod1 = function () {
return $(this).each(function () { });
};
$.fn.testMethod2 = function () {
return $(this).each(function () { });
};
$.test = function () {
return "testresult"
};
})(jQuery);
$("div1").testMethod1();
$("div2").testMethod2();
$.test();
//Is that needed to be replace in a different way like
$("div1").myPlugin("testMethod1");
$("div1").myPlugin("testMethod2");
$("div1").myPlugin("test");
</script>
The second way is preferred because it conserves namespace in the jQuery object.
Read the official jQuery doc for this: Plugins/Authoring
Have you try using jquery boilerplate. It is a good point to start study jQuery plugin development. It's provide a safe and(seem to be) a good solution to create a plugin. They use your second way to call a method.

How to create a jQuery function (a new jQuery method or plugin)?

I know that in JavaScript the syntax is as follows:
function myfunction(param){
//some code
}
Is there a way to declare a function in jQuery that can be added to an element? For example:
$('#my_div').myfunction()
From the Docs:
(function( $ ){
$.fn.myfunction = function() {
alert('hello world');
return this;
};
})( jQuery );
Then you do
$('#my_div').myfunction();
In spite of all the answers you already received, it is worth noting that you do not need to write a plugin to use jQuery in a function. Certainly if it's a simple, one-time function, I believe writing a plugin is overkill. It could be done much more easily by just passing the selector to the function as a parameter. Your code would look something like this:
function myFunction($param) {
$param.hide(); // or whatever you want to do
...
}
myFunction($('#my_div'));
Note that the $ in the variable name $param is not required. It is just a habit of mine to make it easy to remember that that variable contains a jQuery selector. You could just use param as well.
While there is a plethora of documentation / tutorials out there, the simple answer for your question is this:
// to create a jQuery function, you basically just extend the jQuery prototype
// (using the fn alias)
$.fn.myfunction = function () {
// blah
};
Inside that function, the this variable corresponds to the jQuery wrapped set you called your function on. So something like:
$.fn.myfunction = function () {
console.log(this.length);
};
$('.foo').myfunction();
... will flush to the console the number of elements with the class foo.
Of course, there is a bit more to semantics than that (as well as best practices, and all that jazz), so make sure you read up on it.
To make a function available on jQuery objects you add it to the jQuery prototype (fn is a shortcut for prototype in jQuery) like this:
jQuery.fn.myFunction = function() {
// Usually iterate over the items and return for chainability
// 'this' is the elements returns by the selector
return this.each(function() {
// do something to each item matching the selector
}
}
This is usually called a jQuery plugin.
Example - http://jsfiddle.net/VwPrm/
Yup — what you’re describing is a jQuery plugin.
To write a jQuery plugin, you create a function in JavaScript, and assign it to a property on the object jQuery.fn.
E.g.
jQuery.fn.myfunction = function(param) {
// Some code
}
Within your plugin function, the this keyword is set to the jQuery object on which your plugin was invoked. So, when you do:
$('#my_div').myfunction()
Then this inside myfunction will be set to the jQuery object returned by $('#my_div').
See http://docs.jquery.com/Plugins/Authoring for the full story.
$(function () {
//declare function
$.fn.myfunction = function () {
return true;
};
});
$(document).ready(function () {
//call function
$("#my_div").myfunction();
});
You can also use extend (the way you create jQuery plugins):
$.fn.extend(
{
myfunction: function ()
{
},
myfunction2: function ()
{
}
});
Usage:
$('#my_div').myfunction();
You can write your own jQuery plugins(function which can be called on selected elements) like below:
(function( $ ){
$.fn.myFunc = function(param1, param2){
//this - jquery object holds your selected elements
}
})( jQuery );
Call it later like:
$('div').myFunc(1, null);
Yes, methods you apply to elements selected using jquery, are called jquery plugins and there is a good amount of info on authoring within the jquery docs.
Its worth noting that jquery is just javascript, so there is nothing special about a "jquery method".
Create a "colorize" method:
$.fn.colorize = function custom_colorize(some_color) {
this.css('color', some_color);
return this;
}
Use it:
$('#my_div').colorize('green');
This simple-ish example combines the best of How to Create a Basic Plugin in the jQuery docs, and answers from #Candide, #Michael.
A named function expression may improve stack traces, etc.
A custom method that returns this may be chained. (Thanks #Potheek.)
You can always do this:
jQuery.fn.extend({
myfunction: function(param){
// code here
},
});
OR
jQuery.extend({
myfunction: function(param){
// code here
},
});
$(element).myfunction(param);
It sounds like you want to extend the jQuery object via it's prototype (aka write a jQuery plugin). This would mean that every new object created through calling the jQuery function ($(selector/DOM element)) would have this method.
Here is a very simple example:
$.fn.myFunction = function () {
alert('it works');
};
Demo
Simplest example to making any function in jQuery is
jQuery.fn.extend({
exists: function() { return this.length }
});
if($(selector).exists()){/*do something here*/}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Define a function in jQuery</title>
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<script>
$(document).ready(function() {
$.fn.myFunction = function() {
alert('You have successfully defined your function!');
}
$(".call-btn").click(function(){
$.fn.myFunction();
});
});
</script>
</head>
<body>
<button type="button" class="call-btn">Click Here</button>
</body>
</html>

I cant return anything in callback function of jQuery bind

Can Anybody explain why this happen?
This is my code in a plugin called something:
(function($){
$.fn.extend({
something: function(options) {
// Here I define defaults
$(this).bind('change', function () {
return $(this).each(function() {
// a function body
});
});
}
});
})(jQuery);
and I call this plugin in another js like this:
var myarray=new Array();
myarray[0] = $('#selector').something({
regex:/^([\u0600-\u06FF]|\s)*$/,
// another options
});
$('#selector').change(function (){
alert (myarray[0]);
});
in every change in my selector it returns me undefined.
It completely make me insane. Thanks if anyone can help me.
Edit:
You Can Read My complete code here.
In your plugin you are just attaching a change event handler on the element which just runs a loop on all the matched set of elements and returns a jQuery object.
If you want to return something from something plugin then the return statement should be outside the event handler.
$.fn.extend({
something: function(options) {
return $(this).each(function() {
//Do processing here
});
}
});
Now you can use this
var myarray = $('#selector').something({
regex:/^([\u0600-\u06FF]|\s)*$/,
// another options
});
$('#selector').change(function (){
alert (myarray[0]);
});
Note that myarray will be an array because jQuery each returns a jQuery object which itself is an array of DOM elements.
It is all because your 'something' function does not return anything.
One huge problem... "something" is spelled different in plugin than the jQuery method chain when you call it with your selector

Categories

Resources