Code impact inside click event? - javascript

element.onclick = function() {
myFunction();
};
function myFunction() {
// 100, 500 or 1000 lines of code
}
Does and if yes, how does code inside the click event impacts the weight of click event?
PS! Im interested in code impact in event listener overall, not just a function like in my example. What if there was 500 lines of code instead of function?
Does it matter how big is myFunction() code?
Does it get processed before click event is triggered?
I do not mean the impact on the moment it's pressed but before this: if event is attached to element.
Im asking this because I need to attach the same click event to many elements and the code inside is pretty big. Event delegation is not an option in my situation. An example:
for(i = 0; i < 500; i++) {
//Just for the sake of this example
var element = document.createElement('div');
element.onclick = function() {
myFunction();
};
}
function myFunction() {
// 100, 500 or 1000 lines of code
}
Based on this example, should I be thinking about or worried about the size of myFunction()?

You function will be processed by the JavaScript runtime when it reads in the file. It will be invoked when you call it in the callback. The time for the callback to invoke the function will be no different if the function is 10 lines or 1000 lines.
Edit:
You may notice the execution time of the function change, as the amount of code increases, but invocation shouldn't change. Things that change invocation speed are looking up nested functions in objects: obj1.obj2.obj3.obj4.obj5.func() would be slower than a top-level func() definition (shouldn't be drastically different if it is not nested deep in large objects).

First, Javascript is a single threaded ecosystem.
There is a big eventloop which executes one event after another.
In case your onclick takes ages, you might see the prominent "A script is not responding"
The processing happens when you click it.
The "big event loop" reads the click event and calls all your event handlers for it. So the clicking triggers all the click event handlers being processed. (for the elements that are under your click area)
In case your problem is a not responding script, you could try WebWorkers. I never played with those, as it´s rather new.
https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/Using_web_workers
Regarding your 500 elements with the same click handler... You can only click one item at a time, no?
Maybe try
event.stopPropagation();

Related

is there a way to run the jquery.live function without any event

The live function of jQuery is triggered with an event
The api documentation is here
http://api.jquery.com/live/
$(".xyz").live('event', function(){
});
I want the above function to run without an event , i.e as soon as the class xyz is dynamically created.
I have tried this without the event parameter
$(".xyz").live( function(){
});
but it doesn't work !!
adding
I don't know exactly what you want to do, but I'll make assumptions.
Scenario 1
In order to execute a function inside jQuery, you need to tell jQuery when to execute the function, otherwise it cannot know. One way to do this is:
$(document).ready(function () {
$('.xyz').css('color', 'red');
// more code, anything, functions, calculations, etc.
});
The code inside that function will be executed as soon as your DOM is ready (is safe to manipulate).
You can put $('.xyz').css('color', 'red'); also outside the ready() event and it will also be executed. The "event" this time is when the executions of the page reaches that line of code. For example, if you put this line before your HTML, you don't have guarantee it will work.
Scenario 2 - onClassChange event
If you are looking for an event called something like onClassChange, it does not exits on jQuery. An approach to that problem could be this:
Create a timer which runs infinitely
On each run, check if that object has your class ( $(obj).hasClass('xyz') )
If yes, do whatever you want to do inside the if ()
Also, since you said the class xyz is created dynamically, you can try to run your function immediately after you create your class in your code.
For more about onClassChange event, there are long discussions you can check on this site.

$(document).click from two locations

I call an external js file. This js file already has a (document).click function. I want to have an (document).click within the main js.
external js:
$(document).click(function() {
//do stuff
});
I do not use global variables. What's the best way to have $(document).click function in the external file and also to add an $(document).click function within the main js?
You can have both. As long as nobody stops propagation, both event handlers will run.
Do post the code if you still have any trouble.
Expanding the answer a bit:
There is in fact a way (the wrong way) to do click event handlers that supports only one at a time. If you do:
element.onclick = function () {alert('a')};
And then
element.onclick = function () {alert('b')};
You will get only one alert (saying 'b'). Which is why you should never use that. This is a remnant of a time when nobody knew what they were doing. It's 2015, the less we talk about it the better.
Now, when you use the proper way of registering event handlers:
element.addEventListener('click', function () {alert('a')});
element.addEventListener('click', function () {alert('b')});
You'll get both alerts.
To clear up any confusion, it's worth mentioning that jQuery uses the same old addEventListener internally when you do $(element).click(f) or $(element).on('click', f) or however it works today.
You can add 'click' event on both the file,but the problem is, when
you click on that particular element both the handlers will fire on
the same time If i am not wrong, both handler will work differently
and should not fire at same time.
Best way use Event trigger with different name spaces of events.
$(document).on('click.func1',function(){
func1();
});
$(document).bind('click.func2',function(){
doStuff2();
});
Then when you need to trigger you can choose order.
$(document).trigger('click.func1').trigger('click.func2');
Or you can trigger both event on same time:
$(document).trigger('click');

Javascript function gets called multiple times by event listener

I have a weird problem that I am not able to debug.
I have a script with the following relevant functions:
a function events() that has a jQuery.on('click', callback(event)) event binder inside it. That function gets called every time I add or remove anchors with AJAX, but that's irrelevant for this problem.
a function get_passwords() which gets jQuery.attr("href") from anchor $("a.active") and makes a $.post to the server with a callback that inserts values into a table upon receiving the data
The function get_passwords() is called synchronously in the callback(event) function like this:
event.preventDefault(); //prevents a browser navigation
$("a.active").removeClass("active"); //removes active class from all other anchors
$(this).addClass("active"); //adds a class "active" to the anchor that was clicked
get_passwords(); <---- the function in question <--BREAKPOINT #1
The function get_passwords() contains the following relevant lines:
$.post("url", postData, function(data) { //put received data into table }); <--BREAKPOINT #2
Now, the weird bug is that the get_passwords() function is called multiple times by the same event listener, and only stops calling that function after an arbitrary, but constant amount of times, every time the click is made on an anchor with the event listener.
I've set the breakpoint in FireBug on the above indicated line, and as I execute the script step by step, all it does is jump between the two breakpoints set above (the part where it calls get_passwords() and where it executes $.post, 4 times (always the same amount), up until the 4th time when it actually proceeds with the callback in the $.post function.
Realizing that there is no way I can ask anyone to read through all the code that I've written, does anyone have any suggestions as to where this bug could be coming from?
Thank you in advance.
EDIT: http://jsfiddle.net/nt3A4/
Are you looking for event.stopImmediatePropagation()?
#epascarello, #nbrooks,
You were both right. I was attaching multiple event listeners, somehow, to the same anchor. Probably got lost due to my poor coding planning (I was making up website features as I went along).
Anyway, I fixed it by pre-pending $("a").off() in the events() function, as to remove any other event listeners that may have been set before. Should of done that from the beginning :/
Thank you all for your answers and your time.

jQuery events... how much code should go inside?

If I am attaching change events to a lot of items, say every checkbox on a large form, and then processing rules based on that, should I execute a separate function instead of having that code in an anonymous function inside the event?
$(".magic_checkbox").change(function(event){
//somewhat lengthy code here
});
Is this creating a separate JavaScript function object for every checkbox, or are they all going to use one pointer? If they are all duplicates, will that even matter in the grand scheme of things?
There is only one anonymous function, but you may want to consider delegated event approach. Create a single event handler on a parent object of the .magic_checkbox elements. Then do the following:
$("#parentObjectId").on("change", ".magic_checkbox", function(event){
// your somewhat lengthy code here
});
or ...
$("#parentObjectId").on("change", ".magic_checkbox", function(event){
somewhatLengthyMethod();
});
function somewhatLengthyMethod() {
// your somewhat lengthy code here
}
Choosing between the two is just a matter of preference. The key is event delegation which results in far fewer event handlers, hence more efficient.

How do I prevent touchend event from apparently being "remembered" by the browser and firing subsequently at inappropriate times?

EDIT
Based on the number of views and the complete lack of responses I have to assume that I did a poor job of communicating my issue. I'm going to try to rectify that now.
I extended the HTMLElement prototype with a new tap method like so:
HTMLElement.prototype.tap = function (func) {
this.addEventListener("touchend", func, false);
};
I also created a custom tap event in jQuery:
$(document).delegate("*", "touchend", function (e) {
$(this).trigger("tap");
});
I also created a jQuery plugin called tap:
$.fn.tap = function (func) {
this.bind("tap", func);
};
If I try to use any of these with a callback function that includes an alert statement the callback executes twice. I tap the element to pop up the alert. I tap the "OK" button in the alert to close it. The next time I tap the screen no matter how long I wait the alert pops up again. This time tapping the "OK" button doesn't seem to set up another repeat.
However if the callback function doesn't include an alert statement (e.g. I use a console.log statement instead) the callback only executes the one time.
Does anyone know a way to deal with this? I'm about to try unhooking the event handler from within itself and then rebinding it afterwards, but that's nothing more than a hack if it's even successful.
I'd rather do things the "right" way. :-)
ORIGINAL
I just finished writing a "tap" function that I can use by extending the HTMLElement or Element prototypes as well as a custom "tap" event and "tap" plugin both for jQuery. I thought I had this in the bag until I decided to use a simple alert statement as test code.
When I use these with some element on my test page, they fire properly when I first "tap" the element, but the problem arises after I touch the alert's "OK" button and then, any amount of time later, tap the screen again at which point the event handler fires a second time.
At first I thought it was my custom code, but when I tried it with the following very basic JavaScript I was able to replicate the exact same issue.
document.getElementById("some-element").ontouchend = function (e) {
alert("Howdy doody!");
};
I imagine it must have something to do with the fact that I have to touch the screen again to execute the "OK" on the alert while still technically "inside" the event handler (since the alert is in effect "blocking" the completion of the handler function).
The fact that the behavior isn't replicated with the following slightly different code seems to support my imagination. :-)
document.getElementById("some-element").ontouchend = function (e) {
console.log("Howdy doody!");
};
If I include the above code in a page and touch that element after the callback fires I won't get a repeated firing of that callback function as opposed to the previous block of code where I'll see the alert pop up a second time the next time I tap the screen after hitting "OK" no matter where on the page I tap.
A strange issue indeed, and I haven't been able to find any information about why this might be happening. Does anyone have an idea what is happening?
I believe the visual, full-page alert being triggered on touch end is interfering with the touch event cycle. Try to call the alert after yielding to the DOM. eg.
setTimeout(function() {
alert('btn clicked');
}, 0);

Categories

Resources