calling a function before onclick script - javascript

click me
Hello, I need to called a function before calling the onclick script when the is clicked.
I tried:
var script = $("a").attr("onclick");
$("a").attr("onclick", "");
$("a").click(function(event) {
// call bar() first, then foo();
bar();
// script is a string on Chrome
// foo() may use this, so can not globalEval.
});
how to call the script? Can I get the onclick as jQuery function? so that:
onclickFunction.call(this);
Thanks.

If you must follow this way try this:
JS:
(function() {
var a = document.getElementsByTagName('a')[0];
var foo = a.onclick;
function bar() { console.log('bar'); }
a.onclick = function() {
bar();
foo();
};
})();
jsfiddle

can't you wrap them inside another function like this? :
click me
var handler = function() {
foo(); // 1. calling foo first
bar(); // 2. calling bar second
};

You can add "mouse up" or "mouse down" event to the element, this event will call before the "click" event call. Here is the demo.
void function(){
$("div").mousedown(function(){
console.log("mouse down event")
})
$("div").mouseup(function(){
console.log("mouse up event")
})
$("div").click(function(){
console.log("click event")
})
}();
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>click me</div>

Related

how to call a jquery click function using javascript?

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

Having issue with click events/memory leak

I have following JavaScript code.
var Foo = function () {
$('body').on('click', '.btn', this.update.bind(this));
};
Foo.prototype = (function () {
var update = function (e) {
console.log('update');
e.preventDefault();
};
return {
update: update
}
})();
new Foo();
new Foo();
new Foo();
I am creating 3 instances of Foo constructor. Inside constructor, I am attaching a click event to dom element. However, with this approach the click event is attached 3 times because I am creating 3 instance using new operator. How can I make this work so that after creating 3 instance it only attach one click event to that dom element?
JSFIDDLE
var Foo = function () {
$('body').off('click', '.btn');
$('body').on('click', '.btn', this.update.bind(this));
};
This removes the click event listener, then rebinds it. That way it is limited to one listener.
This is not a memory leak. This is how jQuery works if you bind events multiple times. If you do something like that:
$('body').on('click', '.btn', function(e){/*logic here*/});
$('body').on('click', '.btn', function(e){/*logic here*/});
$('body').on('click', '.btn', function(e){/*logic here*/});
It will attach the event 3 times. Why do you think that if you put this thing into a class and instantiate the class 3 times it will not attach the event.
A way to prevent this behaviour is to do something like that:
var Foo = function () {
if(!Foo.instantiatedOnce) {
$('body').on('click', '.btn', this.update.bind(this));
}
Foo.instantiatedOnce = true;
};
Foo.prototype = (function () {
var update = function (e) {
console.log('update');
e.preventDefault();
};
return {
update: update
}
})();
Foo.instantiatedOnce = false;
new Foo();
new Foo();
new Foo();
Doing something like that it is like simulating a static variable that is shared between instances.
This should work:
var binded = false;
var Foo = function () {
if (!binded) {
$('body').one('click', '.btn', this.update.bind(this));
binded = true;
}
};

Jquery Click-handler doesn't work with named function?

I feel like this is one of those problems you only run into after too little sleep or too many coffees...
I have an element
<a id="blah" href="#">somethinghere.com</a>
I define a function
function test(){
alert('hi');
};
I try to attach the function as a click-handler(https://jsfiddle.net/8r1rcfuw/30/):
$('#blah').on('click', test());
and load the page, and the handler executes immediately - without any clicks.
However when I just use an anonymous function as a handler(https://jsfiddle.net/8r1rcfuw/36/) :
$('#blah').on('click', function(){
alert('hi');
});
it works fine
Doing both (https://jsfiddle.net/8r1rcfuw/39/):
$('#blah').on('click', function(){
test();
});
function test(){
alert('hi');
}
seems to work fine - but seems a little redundant.
This feels like something I've done 1000 times before - what gives?
The event handler has to be a function, and you are passing the result of a function to it:
$('#blah').on('click', test());
is the same as:
$('#blah').on('click', undefined); //As your funcion doesn't return anything
Think of it as a function is a value, you can do:
var myFunction = function() {
alert("Hi");
}
or
function myFunction() {
alert("hi");
}
And then:
$('#blah').on('click', myFunction); //Without invocation!
or using an anonymous function:
$('#blah').on('click', function() {
alert("Hi");
});
You can also use object of function :
var temp=function test() {
alert('hi');
}
$('#blah').on('click', temp);
Try :
$('#blah').on('click', test); // your function name only
Updated Fiddle

On click myFunction and wait until it is finished

I thought this is something easy to do but I dont find anything helping me out of this.
I have a function
(function($){
myFunction = function(e){
e.preventDefault();
// do stuff
// load ajax content
// animate and show
}
$('.button').on( 'click', myFunction);
})(jQuery);
now this works but I need to know, wait untill everything is done if someone presses many .buttons in a short time cause there are a few elements with class button
I've tried with promise()
$('.button').on( 'click', function(){
$.when( myFunction() ).done(function() {
alert('finished')
});
});
but that gives me an error e is undefined and
$('.button').on( 'click', myFunction).promise().done(function() {
alert('finisehd');
});
anyone knowing what I'm doing wrong and how I could do it to get it to work?
The most common solution would be to set a variable inside the click handler when myFunction is called and check its state with every call of the click handler.
This could be done somewhere along the lines of this:
(function($){
var wait = false;
myFunction = function(e){
e.preventDefault();
if (wait) {
return;
}
wait = true;
// ...
wait = false;
}
$('.button').on( 'click', myFunction);
})(jQuery);
Your function myFunction expects one argument, when you call myFunction() the argument is missing.
Not tested but it should works:
$('.button').on( 'click', function(e){
$.when( myFunction(e) ).done(function() {
alert('finished')
});
});
In addition to not passing in the e variable. You're using $.when incorrectly.
If you want to have the done function called after myFunction finishes its ajax call. You'll need to return a promise from myFunction.
function myFunction(e) {
return $.Deferred(function(deferred) {
doAjax(function(content) { // callback
deferred.resolve(content);
});
});
}
Now when you do
// inside event handler
$.when(myFunction(e)).done(function(content) {
// whoo!
});

Document.ready function

I have some code in the - $(document).ready(function(){ - that shuffles stuff around, the code is fired when the page is loaded but what I want to do is add a button so this function runs every time I press the button, how could I achieve this, thanks??
function shuffleStuffAround() {
// truffle shuffle
}
$(function($) { // DOM ready
shuffleStuffAround();
$("#some-button").click(function() {
shuffleStuffAround();
return false; // you probably want this
});
});
You can save you "shuffle stuff around" code as a function and call it from other parts of your codebase.
var foo = function() {
// code that shuffles stuff around
};
$(document).ready(function() {
foo();
// other stuff
});
$('#mybutton').click(foo);
//or
$('#mybutton').click(function() {
foo();
// other stuff.
});
You could simple refactor the code that you run on the ready function into its own function and call that in your button's click event:
$(document).ready(function(){
codeToRun();
$('.button').click(function(){codeToRun()});
});
function codeToRun(){
// do work
}

Categories

Resources