Add more behavior to existing onclick attribute in javascript - javascript

how can i add more behaviour to existing onclick events e.g.
if the existing object looks like
link
<script>
function sayHello(){
alert('hello');
}
function sayGoodMorning(){
alert('Good Morning');
}
</script>
how can i add more behavior to the onclick that would do also the following
alert("say hello again");
sayGoodMorning()
Best Regards,
Keshav

Here's the dirtiest way :)
<a href=".." onclick='sayHello();alert("say hello again");sayGoodMorning()'>.</a>
Here's a somewhat saner version. Wrap everything into a function:
..
JavaScript:
function sayItAll() {
sayHello();
alert("say hello again");
sayGoodMorning();
}
And here's the proper way to do it. Use the event registration model instead of relying on the onclick attribute or property.
<a id="linkId" href="...">some link</a>
JavaScript:
var link = document.getElementById("linkId");
addEvent(link, "click", sayHello);
addEvent(link, "click", function() {
alert("say hello again");
});
addEvent(link, "click", sayGoodMorning);
A cross-browser implementation of the addEvent function is given below (from scottandrew.com):
function addEvent(obj, evType, fn) {
if (obj.addEventListener) {
obj.addEventListener(evType, fn, false);
return true;
} else if (obj.attachEvent) {
var r = obj.attachEvent("on" + evType, fn);
return r;
} else {
alert("Handler could not be attached");
}
}
Note that if all 3 actions must be run sequentially, then you should still go ahead and wrap them in a single function. But this approach still tops the second approach, although it seems a little verbose.
var link = document.getElementById("linkId");
addEvent(link, "click", function() {
sayHello();
alert("say hello again");
sayGoodMorning();
});

Another way not mentioned is to capture the function currently assigned to the element.onclick attribute, then assign a new function that wraps the old one. A simple implementation to demonstrate would be something like
function addEvent(element, type, fn) {
var old = element['on' + type] || function() {};
element['on' + type] = function () { old(); fn(); };
}
var a = document.getElementById('a');
function sayHello(){
alert('hello');
}
function sayGoodMorning(){
alert('Good Morning');
}
addEvent(a, 'click', sayHello);
addEvent(a, 'click', sayGoodMorning);
Working Demo here

One way would be to write a third function:
link
<script>
function sayHello(){
alert('hello');
}
function sayGoodMorning(){
alert('Good Morning');
}
function foo() {
alert("say hello again");
sayGoodMorning();
}
</script>

link
would also work

Assuming a slight change to your code:
link
In plain ol' JavaScript, you'd do something like this.
var a = document.getElementById('a1');
a.onclick = function () { alert('say hello again'); a.onclick(); }
It's worth noting that jQuery makes this a bit easier. See the documentation on the click, bind, and one, for example, and in general the section on event handler attachment.

Related

How do I execute a function once per page refreshing?

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.

How can I read ".on()" method arguments in jQuery?

I have no idea how to bite this problem. Below two examples are working great but I want to avoid the DRY problem.
parentElement.on('focusout', '.foo-class', function () {
// console.log('hello foo')
});
and:
parentElement.on('focusout', '.bar-class', function () {
// console.log('hello bar')
});
I would like to make it more universal. I have to deal with two classes while the parent stays the same.
Assuming that this is the first step:
parentElement.on('focusout', classValue, function () {
// How to display this class so I can call different stuff depending on the class value?
// console.log('hello ' + classValue)
});
May be something along these line, refined from guardio's solution.
Fiddle: https://jsfiddle.net/pvorhknv/2/
What it doing here is to get the element been called for the handler and accessing the attributes. You can use this element "this" for any such use.
$(document).on('focusout', 'input', callme);
function callme(){
console.log('hello ' + $(this).attr('class').split('-')[0])
}
UPDATE:
One other thing you can use it to mark data attribute for the elements.
Fiddle: https://jsfiddle.net/pvorhknv/3/
<input type='text' class='foo-class' data-classname="foo">
<input type='text' class='bar-class' data-classname="bar">
And hence you can access them,
function callme(){
console.log('hello ' + $(this).data('classname'));
}
To look if the (1) element has a particular class, and to (2) get all classes of $(this), see following:
parentElement.on('focusout', classValue, function () {
// (1). find out if element has class 'foo-class'
if $(this).hasClass('foo-class'){
// ...
}
// (2). for each class of element do something
$($(this).attr('class').split(' ')).each(function() {
if (this !== '') {
// ...
}
});
)};
You can use data attribute for specify event which you want to run. My solution is below (simple nothing more nothing less):
html
<div class="event" data-color-event="blue">click me = blue</div>
js
// one listener
$('body').on('click', '.event', function() {
var ev = $(this).data('color-event');
$('body')[ev]();
});
// event functions on demand
$.fn.blue = function() {
alert('blue');
}
$.fn.red = function() {
alert('red');
}
JSFIDDLE DEMO
Separate your classes with commas, and then check the class in the callback.
https://jsfiddle.net/guanzo/dmpgxxt0/
$('.container').on('click','.test1,.test2',function(){
console.log($(this).attr('class'))
})
Did you try
parentElement.on('focusout', '.foo-class, .bar-class', function () {
// console.log('hello foo')
});
And more:
parentElement
.on('focusout', '.foo-class, .bar-class', function () {
// console.log('hello foo')
})
.on('click', '.baz-class', function() { alert('xx'); })
;

How to call the same function in two different ways?

I am trying to combine a function which will display alert (ofcourse I have a lot of code In this function but for this case It will be alert) after:
Click on element with class .number
Change select[name=receive]
I have this code but it doesn't work:
$(document).on(("click",".number"),("change","select[name=receive]"),function(){
alert('test');
})
Try this
function doMyWork() {
console.lot( 'TEST' );
}
$('.number').on('click', doMyWork);
$('select[name=receive]').on('change', doMyWork);
Or, if your elements are inserted after DOM ready:
You do not have to use this form if the target elements exist at DOM ready
function doMyWork() {
console.lot( 'TEST' );
}
$(document).on('click', '.number', doMyWork)
.on('change', 'select[name=receive]', doMyWork);
Try this
$(document).on("click change","select[name=receive], .number", function(){
alert('test');
});
Or
var fn = function () {
alert('test');
}
$(document).on("click", ".number", fn);
$(document).on("change", "select[name=receive]", fn);
You cannot separate events and selectors in a single .on() call. You have two options here. You can use them together....
$(document).on("click change", ".number, select[name=receive]"),function(){
alert('test');
});
...however this means that .number will listen to both click and change, possible resulting in the function running 2 times.
You need to move the function outside and reuse it for every handler
var al = function(){
alert('test');
};
$('.number').on('click', al);
$('select[name=receive]').on('change', al);
$(document).on("click change",".number, select[name=receive]", function(){
alert('test');
})
I am not sure where you learned that syntax, but that is not how on() works.
Use a named function and share it.
(function(){
var shared = function(){
console.log(this);
}
$(document)
.on("click",".number", shared)
.on("change","select[name=receive]", shared);
}());

how to pass parameter in jquery using .on?

Good Day, this maybe a silly question :) how can I pass a parameter to an external javascript function using .on ?
view:
<script>
var attachedPo = 0;
$this.ready(function(){
$('.chckboxPo').on('ifChecked', addPoToBill(attachedPo));
$('.chckboxPo').on('ifUnchecked', removePoToBill(attachedPo ));
});
</script>
external script:
function addPoToBill(attachedPo){
attachedPo++;
}
function removePoToBill(attachedPo){
attachedPo--;
}
but Im getting an error! thanks for guiding :)
You need to wrap your handlers in anonymous functions:
$('.chckboxPo')
.on('ifChecked', function() {
addPoToBill(attachedPo);
})
.on('ifUnchecked', function() {
removePoToBill(attachedPo);
});
You can also chain the calls to on as they are being attached to the same element.
If your intention is to count how many boxes are checked, via passing variable indirectly to functions try using an object instead like this:
JSFiddle: http://jsfiddle.net/TrueBlueAussie/pBkhX/
var attachedPo = {
count: 0
};
$(function () {
$('.chckboxPo')
.on('change', function () {
if ($(this).is(':checked')) {
addPoToBill(attachedPo);
} else {
removePoToBill(attachedPo);
}
$("#output").prepend("" + attachedPo.count + "<br/>");
});
});
function addPoToBill(attachedPo) {
attachedPo.count++;
}
function removePoToBill(attachedPo) {
attachedPo.count--;
}
If it is not doing anything else you can simplify the whole thing to count checked checkboxes:
$(function () {
var attachedPo = 0;
$('.chckboxPo')
.on('change', function () {
attachedPo = $(".chckboxPo:checked").length;
});
});
"DOM Ready" events:
you also needed to wrap it in a ready handler like this instead of what you have now:
$(function(){
...
});
*Note: $(function(){YOUR CODE HERE}); is just a shortcut for $(document).ready(function(){YOUR CODE HERE});
You can also do the "safer version" (that ensures a locally scoped $) like this:
jQuery(function($){
...
});
This works because jQuery passes a reference to itself through as the first parameter when your "on load" anonymous function is called.
There are other variations to avoid conflicts with other libraries (not very common as most modern libs know to leave $ to jQuery nowadays). Just look up jQuery.noConflict to find out more.

Pass $(this) to a function

I am trying to build a media playlist that can advance the credits, play the video and change the title on thumb-hover, end of video and on next/prev click. So I need to write some functions that can then be called together. So like this:
function showBox()
{
$(this).parents('.container').find('.box').show();
};
function hideBox()
{
$(this).parents('.container').find('.box').hide();
};
$('a').hover(
function()
{
showBox();
},
function()
{
hideBox();
}
);
The problem is that $(this) does not carry through to the functions from the .hover. How do I do this?
Per #patrickdw's answer, jQuery sets the scope of a callback for an event to the DOM element upon which the event was fired. For example, see the eventObject parameter in the documentation for the click() handler.
My original answer (below) is useful when you want to create a jQuery plug-in so that you may invoke your own custom methods on jQuery objects and have the jQuery object set as this during execution. However, it is not the correct and simple answer to the original question.
// Within a plug-in, `this` is already a jQuery object, not DOM reference
$.fn.showBox = function(){ this.parents('.container').find('.box').show(); };
$.fn.hideBox = function(){ this.parents('.container').find('.box').hide(); };
$('a').hover(
function(){ $(this).showBox() },
function(){ $(this).hideBox() }
);
Edit: Or, if (as suggested) you want to add only one name to the ~global jQuery method namespace:
$.fn.myBox = function(cmd){
this.closest('.container').find('.box')[cmd]();
};
$('a').hover(
function(){ $(this).myBox('show') },
function(){ $(this).myBox('hide') }
);
Or more generally:
$.fn.myBox = function(cmd){
switch(cmd){
case 'foo':
...
break;
case 'bar':
...
break;
}
return this;
};
For more information, see the jQuery Plugin Authoring Guide.
The this will carry through if you just do:
$('a').hover(showBox,hideBox);
EDIT: To address the question in the comment, this will work for any function you assign as an event handler. Doesn't matter if it is an anonymous function or a named one.
This:
$('a').click(function() {
alert( this.tagName );
});
...is the same as:
function alertMe() {
alert( this.tagName );
}
$('a').click( alertMe );
...or this:
function alertMe() {
alert( this.tagName );
}
$('a').bind('click', alertMe );
In Javascript you can use call() or apply() to execute a function and explicitly specify this for it:
$('a').hover(
function()
{
showBox.call(this);
},
function()
{
hideBox.call(this);
}
);
The first parameter given to call() specifies the object that this will refer to in the function. Any further parameters are used as parameters in the function call.
You need to modify your code to something like this:
function showBox(elem)
{
elem.parents('.container').find('.box').show();
};
function hideBox(elem)
{
elem.parents('.container').find('.box').hide();
};
$('a').hover(
function()
{
var $this = $(this);
showBox($this);
},
function()
{
var $this = $(this);
hideBox($this);
}
);
$('a').hover(function() {
$(this).closest('.container').find('.box').show();
}, function() {
$(this).closest('.container').find('.box').hide();
});
Add parameters to showBox and hideBox so that they can accept the element, and then call showBox($(this)) and hideBox($(this)).

Categories

Resources