Javascript, Jquery append functions to an event - javascript

I have a function that is associated with an event, say onfocus() and in some cases, I want to be able to execute the default function as well as one or more additional functions.
So I don't want to replace the original function, but I want to append another so that both functions will fire.
<div id="mydiv" onfocus="alert('hello');">
if(something == somethingelse) $('#mydiv').onFocus += "alert('world');"
So in this example, sometimes just Hello will Fire and sometimes Hello and then World will both fire.
I'm just using onfocus() and alert() as an example, these would actually be functions that I have defined.
How do I go about doing this ?

Use jQuery to add a focus event handler
<script>
$('#mydiv').on('focus', function(){
//do soemthing
})
</script>

If you work with jQuery don't use inline event bindings, use the following instead:
$("#mydiv").on("focus", function() {
alert("hello");
});
// add one more action for the same event
$("#mydiv").on("focus", function() {
alert("world");
});

You should do
$('#myDiv').on('focus', function(){alert('world')});

$('#mydiv').focus( function(){
})//This is for the elements which load while the page is loading
or
$('#mydiv').on('focus', function(){
}) //This is for the elements which will load dynamically after the page load completed.

If you don't want to use jQuery try this, its an pure javascript equivalent:
document.getElementById("mydiv").addEventListener("focus", function() { alert('world'); });
and if you want it to be compatible with IE8 and older you should try
var el = document.getElementById("mydiv");
if(el.addEventListener)
el.addEventListener("focus", function() { alert('world'); });
else
el.attachEvent("focus", function() { alert('world'); });

if you're using jQuery, you want to use on() to bind event handlers to elements as opposed to specifying them inline
$('#mydiv').on('focus', function () {
alert('hello');
});
$('#mydiv').on('focus', function () {
if (something === somethingelse) {
alert('world');
}
});
or combining into one handler function seems reasonable in this case
$('#mydiv').on('focus', function () {
alert('hello');
if (something === somethingelse) {
alert('world');
}
});
When specifying them inline as you have done, only one event handler can be bound to the event so if you want to bind multiple event handlers, you either need to bend the one event handler limitation to handle this or use another approach, such as DOM Level 2 events or an abstraction on top of it (such as jQuery's on() function).
Event handlers need to be bound when the element to which you are binding the handlers exists in the DOM. To do this, you can use jQuery's ready() function
// bind an event handler to the "ready" event on the document
$(document).ready(function () {
// ..... here
});
or shorthand
$(function () {
// ..... here
});

Related

How to prevent jQuery duplicate function being called

I have a jQuery on('click') function like this:
function enabled_click() {
$('.btn_enabled').on('click', function() {
alert('CLICKED');
});
}
and then I have another post function like this
$(document).on('click', '.btn_add_link', function(e) {
var url = 'www.xxx.my-function';
post_data(url, function(data) {
if (data.status == 'success') {
$('#my_wrapper').append(data.response);
enabled_click();
} else {
alert('error');
}
});
return false;
});
The post function will append another .btn_enabled button. If i did not call the enabled_click() function on the success post, then the newly added .btn_enabled would not be able to trigger the onclick function.
But if I call the enabled_click() function like i did above, the already existing .btn_enable will then call the onclick function twice and alert CLICKED twice. Is there any way to make it so it only alerts once?
Event delegation by binding to a common parent, as answered by #qs1210, is a possible solution, and a very efficient one (because there's only one common handler instead of one per element). But depending on the code, it may require more changes.
As a compatible "drop-in replacment" just unbind the event handler before binding again. To achieve this in an easy and stable way, you can use jQuery's "namespace" feature for event names (see .on(), "Event names and namespaces"):
function enabled_click(){
$( '.btn_enabled' )
.off('click.some_namespace')
.on('click.some_namespace'), function() {
alert('CLICKED');
});
}
Note: if you extract the event handler into its own function and use that as second parameter to .off(), you could omit the namespace:
function click_handler(){
alert('CLICKED');
}
function enabled_click(){
$( '.btn_enabled' )
.off('click', click_handler)
.on('click', click_handler);
}
But this only works it the click_handler variable is "stable": depending where and when the click handler is defined, the variable (click_handler in this example) could be re-assigned and .off() couldn't detach the previous handler anymore.
Follow-up: in your example, you only apply the event handler to newly appended elements ($('#my_wrapper').append(data.response)). You could alter enabled_click to explicitly take the new element(s) as an argument:
function enabled_click($element){
$element.find('.btn_enabled' ).on('click', function() {
alert('CLICKED');
});
}
and call it like this:
var $newElement = $(data.response);
$('#my_wrapper').append($newElement);
enabled_click($newElement);
Now the event handler gets attached to new elements only, and not to already existing which have the event handler already attached.
(I'm using $ as prefix for all my variables holding jQuery collections, in order to distinguish them from pure DOM nodes)
Your can write like this
document.on('click', '.btn_enabled', function() {
alert('CLICKED');
})`
delegate event to dom, it makes everything harmony.

How do I bind this event handler in a jQuery plugin?

I am learning JavaScript and jQuery, so I apologize in advance if this is a stupid question.
(function ($) {
$.fn.addDiv = function () {
this.append('<div></div>');
return this;
};
}(jQuery));
$('div').click(function () {
$('body').addDiv();
});
In the code above, I have written a simple jQuery plugin which appends a <div> element to the current value of this.
Now, after I click on an element and add some <div> elements, I realize that the click handler in not associated with the newly appended elements. This seems perfectly acceptable since naturally when the handler function was bound, it was to only the ones that existed and hence were present in the $('div') object.
Now, I know that binding the handler to all <div> elements within the plugin is as simple as follows.
(function ($) {
$.fn.addDiv = function () {
this.append('<div></div>');
$('div').click(function () {
$('body').addDiv();
}); // added this statement
return this;
};
}(jQuery));
But I'm sure that there is a better way to handle such event binding. This clearly duplicates code. So what is the best practice with regards to such event binding to elements that the plugin itself adds?
This is meant to be an educational example, please do not consider it to be any kind of use case and give me alternative solutions.
http://jsbin.com/jokururiyaca/1/edit
Edit: I know that some people recommend the use of .selector but it is deprecated in jQuery 2. Also, using it doesn't change the fact that the event handling code is still duplicated within the plugin.
This is one way you could solve your problem of re-binding the click handler to all elements.
You can create the DOM element using $('<div></div>'), add the click handler to only that element, using $('<div></div>').click(...), and then append it to the body with $('<div></div>').click(...).appendTo("body").
Example:
(function ($) {
$.fn.addDiv = function () {
$('<div></div>').click(function () {
$('body').addDiv();
}).appendTo("body");
return this;
};
}(jQuery));
Usually Event Delegation would be used to handle events on future elements.
Example:
(function ($) {
$.fn.addDiv = function () {
this.append('<div></div>');
return this;
};
}(jQuery));
$(document).on("click", "div", function(){
$('body').addDiv();
});

How to run one javascript function on two different events?

I have one javascript function and I want run it on two diferent events - document.ready and window.scroll. How to do it?
Guessing you're using jQuery (document.ready and all).
Attaching the event handler to the window after document.ready, and then triggering the event immediately fires the handler on document.ready and on every scroll event.
$(document).ready(function() {
$(window).on('scroll', function() {
// do stuff
}).trigger('scroll');
});
or to reference a function
$(document).ready(function() {
$(window).on('scroll', myJavascriptFunction).trigger('scroll');
});
function myJavascriptFunction() {
// do stuff
}
call it like
$(document).ready(function(){
$(window).scroll(function(){
//some func
});
//same func
})
also use it like this on onscroll
If u want it on doc.ready too then write 2nd time too(though its not a good idea.)

jQuery override an on() event with another on() event

I have 2 files, file 1 (head.tpl) contains this default function operation
$(document).on("click", "#blackout", function(){
closeSkyBox();
});
That is the default operation I want to run, and it works.
On my second page, I would like to override the operation that is in head.tpl with this:
$(document).on("click", "#blackout", function(){
closeSkyBox(function(){
pev_for_country = '';
});
});
So, now when I test the code, each one runs, so If I were to place an alert (for testing reasons) I get two alert boxes. How can I make it so only the one in the second page runs, and the one in head.tpl is disabled. Then when I don't override it say on a third page, the one in head.tpl runs?
Looks like you're looking for jQuery's .off
$(document)
.off('click', '#blackout')
.on('click', '#blackout', function () {
// ...
});
You can use .off to remove all event handlers, but you should be cautious: what if other libraries add event handlers that you don't want to remove subscribe to this event? Also, if you add an additional event handler at a later date, this would obliterate it.
A better approach, I think, is to create a function that you can override:
function blackoutClick() {
closeSkyBox();
}
And set up your click handler:
$(document).on("click", "#blackout", function(){
blackoutClick();
});
Or, as Paul pointed out in the comments below, you don't even need to wrap that handler in an anonymous function, you can just use the cleaner:
$(document).on("click", "#blackout", blackoutClick );
Then, in your second page, you can just modify that function:
function blackoutClick() {
closeSkyBox(function(){
pev_for_country = '';
});
I believe another way to do it is also to set the event to null...
$(document).on('click', '#blackout', null);
before you re-set it on your second page.

Adding a function to onclick event by Javascript!

Is it possible to add a onclick event to any button by jquery or something like we add class?
function onload()
{
//add a something() function to button by id
}
Calling your function something binding the click event on the element with a ID
$('#id').click(function(e) {
something();
});
$('#id').click(something);
$('#id').bind("click", function(e) { something(); });
Live has a slightly difference, it will bind the event for any elements added, but since you are using the ID it probably wont happen, unless you remove the element from the DOM and add back later on (with the same ID).
$('#id').live("click", function(e) { something(); });
Not sure if this one works in any case, it adds the attribute onclick on your element: (I never use it)
$('#id').attr("onclick", "something()");
Documentation
Click
Bind
Live
Attr
Yes. You could write it like this:
$(document).ready(function() {
$(".button").click(function(){
// do something when clicked
});
});
$('#id').click(function() {
// do stuff
});
Yes. Something like the following should work.
$('#button_id').click(function() {
// do stuff
});

Categories

Resources