I added a simple function:
$.postAndVerify = function(url)
{
// this.event. ?
}
$('#myButton').click(function() {
$.postAndVerify('/url');
});
inside in it, how do I know the caller object, i.e. #myButton? Of course I know it could be just passed:
$.postAndVerify = function(url, $triggeredBy)
{
}
$('#myButton').click(function() {
$.postAndVerify('/url', $(this));
});
but it then would result tons of boilerplate code.
You could make it a plugin method by assigning the method to $.fn instead of to $
$.fn.postAndVerify = function(url){
console.log(this)// jQuery object
}
$('#myButton').click(function() {
$(this).postAndVerify('/url' );
});
Or you could use Function#bind()
You can try to use call method to pass button element as this
$.postAndVerify = function (url) {
console.log('this:');
console.log(this);
};
$('#myButton').click(function () {
$.postAndVerify.call(this, '/url');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="myButton" type="button">Click me</button>
Related
So by default jQuery uses a HTML Dom Element as the calling object in a event callback
var el = $("#foo");
el.on("click", function()
{
// this will output a div element
console.log(this);
});
Is there a simple way to make it use the jQuery object as the calling function by default instead
so that "this" references the jQuery object and I don't have to wrap "this" in a jQuery constructor.
$("#foo").on("click", function()
{
// this will instead output the jQuery object el declared above
console.log(this);
this.addClass("fee").find(".roo").remove();
});
I want to avoid creating variable names and just use "this" to refer to the jQuery object that added the listener.
You can make your own handler which calls a function bound to the jQuery collection:
const onClick = (selector, callback) => {
const jQueryCollection = $(selector);
jQueryCollection.on('click', callback.bind(jQueryCollection));
};
onClick("#foo", function() {
this.addClass("fee").find(".roo").remove();
});
.fee {
background-color: yellow;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="foo">foo
</div>
Or, extend jQuery:
$.fn.onClickWithThis = function(callback) {
const jQueryCollection = $(this);
jQueryCollection.on('click', callback.bind(jQueryCollection));
};
$("#foo").onClickWithThis(function() {
this.addClass("fee").find(".roo").remove();
});
.fee {
background-color: yellow;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="foo">foo
</div>
I wanted to use a preexisting option if possible, but since there doesn't seem to be one.
I overwrote the on function instead.
Most of the credit to CertainPerformance, but this solution works best since it overwrites the callback and works with the 4 available parameters that on can take.
(function ($)
{
let originalOn = $.fn.on;
$.fn.on = function(...args)
{
for(let key in args)
{
if(typeof(args[key]) == "function")
{
let originalCallback = args[key];
args[key] = function(...args)
{
originalCallback.bind($(this))(...args);
}
}
}
originalOn.bind(this)(...args);
}
})($);
I wand to call a jquery click function using JavaScript
<input type='button' class="button" value='+Add' id='addImage'>
when i click this button the following function will run
$("#addImage").click(function () {
//my code.....
}
but i need to call this function using another JavaScript function like fn_name()
You can use trigger and the name of the event, like so (the example below uses a self-executing function for simplicity):
$("#addImage").click(function() {
alert('Clicked')
});
(function(){
$("#addImage").trigger('click')
})();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type='button' class="button" value='+Add' id='addImage'>
use trigger
$("#addImage").trigger("click")
you have this ugly way too, but not recommended:
https://jsfiddle.net/96oxhwsf/
function fn_name() {
$("#addImage").click(function() {
alert('test')
});
}
fn_name()
beatiful way:
function fn_name(elID) {
let btn = document.getElementById(elID);
btn.addEventListener('click', function() {
alert('Test');
}, false)
}
// still need call the function
fn_name('addImage');
even better:
var addImg = () => {
let btnAdd = document.getElementById('addImage')
btnAdd.addEventListener('click', () => {
alert('test')
}, false)
}
declare function
bind click event
call function
//declare
function test(){
//my code.....
}
function callTest(){
// call function
test();
}
function callAClick(){
//trigger
$("#addImage").trigger('click')
}
// bind click
$("#addImage").click(test);
I have a code like this:
function myfunc () {
alert('executed');
}
$('.classname').on('click' function () {
myfunc();
});
I want to run myfunc once. I mean I don't want to execute it every time when user clicks on .classname element. I guess I need to warp function-calling into a condition. Something like this:
if ( /* that function never executed so far */ ) {
myfunc();
}
How can I do that?
The simplest way with jQuery is to use .one
function myfunc() {
alert('executed');
}
$('.classname').one('click', function() {
myfunc();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button class="classname">click here!</button>
You should remove the event listener in the function you're calling:
function myfunc () {
alert('executed');
$('.classname').off('click', myfunc);
}
$('.classname').on('click', myfunc);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class='classname'>Click Me</div>
Don't set a global variable like the other posts describe - there's no need for that and then you're still doing an unnecessary function call. This ensures the function is never called again and the event isn't being listed for.
$( document ).ready(function() {
var hasBeenExecuted = false;
function myfunc () {
alert('executed');
hasBeenExecuted = true;
}
$('.classname').on('click' function () {
if(!hasBeenExecuted){
myfunc();
}
});
});
var functionWasRun = false;
function myfunc () {
functionWasRun = true;
alert('executed');
}
$(document).ready(function() {
$('.classname').on('click', function () {
if (!functionWasRun) {
myfunc();
}
});
});
I would suggest, as an alternative to a global variable, assigning a property to the function.
function myfunc () {
alert('executed');
myfunc.executed = true;
}
$('.classname').on('click', function () {
if(!myfunc.executed) {
myfunc();
}
});
This has the advantage of working the same way while not polluting the global scope unnecessarily. However, if skyline3000's answer works for you, you should use that instead as it's cleaner and more sensible overall.
I want to call a function with a namespace based on its name.
Perhaps some background: What I want is, dynamically bind pages via $.mobile.loadPage(inStrUrl, { showLoadMsg: false }); and then, based on the current page, invoke a function within a loaded page. For example: each page has a showFilter function, the Event is attached to a main.html - page which should call the matching function in the current page.
I also tried some solutions, with jquery too, but nothing works for me.
This is my function code:
function namespace() { }
namespace.showFilter = function () {
alert("Test");
}
And want to "invoke" or "call" it via its name.
This is what i tried at least.
$(document).ready(function() {
var fn = window["namespace.showFilter"];
fn();
});
I get error TypeError: fn is not a function
Here is a fiddle http://jsfiddle.net/xBCes/1/
You can call it in the following way:
$(document).ready(function() {
window["namespace"]["showFilter"]();
});
or
$(document).ready(function() {
window["namespace"].showFilter();
});
or
$(document).ready(function() {
window.namespace.showFilter();
});
I found that I had to manually set it to window.
window.namespace = function() { }
window.namespace.showFilter = function () {
alert("Test");
};
$(document).ready(function() {
var fn = window["namespace"]["showFilter"];
fn();
});
http://jsfiddle.net/xBCes/4/
Like this:
$(function() {
window.namespace.showFilter();
});
P.S. I shortened the $(document).ready(...)
function namespace() {}
namespace.showFilter = function () {
alert("Test");
}
$(document).ready(function() {
var fn = namespace.showFilter();
fn();
});
http://jsfiddle.net/xBCes/3/
I have the following javascript code found also in this fiddle: http://jsfiddle.net/periklis/k4u4c/
<button id = "element_id" class = "myclass">Click me</button>
<script>
$(document).ready(function() {
this.myfunc = function() {
console.log('Hello world');
}
this.myfunc();
$('#element_id').select('.myclass').bind('click', function() {
this.myfunc(); //Obviously this doesn't work
});
});
</script>
How can I call this.myfunc() when the element is clicked? I don't want to define the myfunc() in the global space.
Thanks as always
Create a local variable that references to the function, that way it is accessible from the anonymous function and you don't end up with myfunc in the global namespace.
<button id = "element_id" class = "myclass">Click me</button>
<script>
$(document).ready(function() {
var myfunc = function() {
console.log('Hello world');
}
myfunc();
$('#element_id').select('.myclass').bind('click', function() {
myfunc(); // works!
});
});
</script>
If you, on the other hand, assign var that = this;, then your method myfunc will be stored on the HTMLDocument object (from $(document)), which is perhaps not what you want. But if that's what you want, then you do this (as others have suggested also, I might add).
<button id = "element_id" class = "myclass">Click me</button>
<script>
$(document).ready(function() {
// storing reference to $(document) in local variable
var that = this;
// adding myfunc on to the document object
that.myfunc = function() {
console.log('Hello world');
}
that.myfunc();
$('#element_id').select('.myclass').bind('click', function() {
that.myfunc(); // works!
});
});
</script>
// Simon A
You could do
$(document).ready(function() {
var that = this;
that.myfunc = function() {
console.log('Hello world');
}
that.myfunc();
$('#element_id').select('.myclass').bind('click', function() {
that.myfunc();
});
});
In this way you cache the this variable with something that you can reuse in your event handlers where this points to the current element
You may be a little confused by what you are doing with the this.myfunc call.
In that context this is referring to document which means you are globally defining that function and it can be referenced at any time by document.myfunc();
If you are just wanting to put a function in a variable temporarily then the following code should help:
$(document).ready(function() {
this.myfunc = function() {
alert('Hello world');
};
var otherfunc = function() {
alert('Hi world');
};
$('.cv1').click(document.myfunc);
$('.cv2').click(otherfunc);
});
JSFiddle: http://jsfiddle.net/LKmuX/
This demonstrates both what you are doing in terms of attaching a function to document and also just putting it in a variable.
An alternative to caching the context, if you need to use the external context inside the binded function, is to use the proxy() method (docs here) to change the scope of the internal function like this :
$('#element_id').select('.myclass').bind('click', $.proxy(function() {
this.myfunc();
}, this));
In this way, I force the actual this (the context when I'm using the bind method) to be the same inside the binded function (that normally has his own context)
http://jsfiddle.net/k4u4c/2/
FYI - the same method can be found in Dojo library (in Dojo it's
largely used), and it's called hitch
Most common way to do this is to cache this in other variable and later on in handler refer to that variable as you would do with this. http://jsfiddle.net/k4u4c/3/
<button id = "element_id" class = "myclass">Click me</button>
<script>
$(document).ready(function() {
this.myfunc = function() {
console.log('Hello world');
}
this.myfunc();
var that = this;
$('#element_id').select('.myclass').bind('click', function() {
that.myfunc(); //Obviously this DOES work :)
});
});
</script>