Do jQuery functions after elements created - javascript

I'm sorry for my bad english..
I did a jQuery function that when the user calls the function, it's creating an element on the page. To that elemet I did a jQuery click event and its working fine,
But if the user calls the function 3 times like this:
$.someFunction();
$.someFunction();
$.someFunction();
If the user clicks the first element, it will do 3 times whats in the click's event callback function, and if the user clicks the second element, it will do 2 times whats in the click's event callback function and if the user do it on the last one, it will do it once.
I want that when the user click every element then the callback function will happen just one time.
How can I fix that problem?

Bind the event to the created element rather than all existing elements.
$.somefunction = function() {
$("<div />").text("click me!").bind("click",function(){
alert("Hello World!");
}).appendTo("body");
}

Try doing something like:
$(".element").unbind("click").bind("click", function(){
alert('a');
});

Even easier: use jquery.on
$('.some-selector').on('click', function()
{
// do your work here
});
With jquery on ("live" in old versions) it will bind to any element matching that selector, regardless of when it is added to the DOM.

Related

How to apply Jquery function to a div that yet existed before ajax call

Say I want to hide a div with id="foobar", but foobar does not exist yet, only after user clicks a button and make an ajax call, the div gets populated into the DOM.
How do I write a function that runs once the div comes into existence? The function cannot be brought by the ajax call. It must exist before the call.
I learned that something like this might help:
$(document).ready(function () {
$(document).on('click', '#futurebutton', function() {
alert("You clicked the future button");
});
but this seems to work only new button is clicked, what I need is having the function run once the div comes into existence.
so something similar to $(document).on( "COMES INTO EXISTENCE" , '#newdiv', function() ...
Thanks!
If you're trying to hide the div with a button after it has been populated, you can add a listener to a parent element that already exists.
$('.parent').on('click','#foobar',removeFoobarFunction);
If you need to remove the div immediately, when it is populated, then you should use the ajax success callback like mcbex mentioned.
Read up on event delegation if you haven't:
https://learn.jquery.com/events/event-delegation/
You should create function then when creating the element add the function name into the element's onclick attribute.
//<div id="futureButton" onclick="onClickFunc"></div>
function onClickFunc(e){ alert("You clicked the future button"); }

Apply JS to dynamically created divs?

I have multiple div's on my page, that can be added to the page dynamically, and can also be removed.
On page load, the dynamically created div's are loaded from localStorage with uniqiue id's and a common class depending on the div, and I call a function along with that, content().
The function content() looks like this:
function content(){
alert("test");
$(".two button").click(function(){
var id = $(this).parent().attr("id");
alert(id);
});
}
Pretty simple, all it does is alert "test" when the function is called, and if you click .two <button>, it will alert .two <textarea> .val().
This works fine once the div's have been loaded, but I run into the problem when I clone the div's
When I clone the div's, it gives them a unique id and a common class like above. At the end of cloneDiv(), I call content(), so that clicking on the elements inside will produce the same results as above.
The problem is, the function will get called as many times as there are div's on the screen, but also means that clicking on the <button> in div .two will alert .two <textarea> .val() three times.
TLDR; Clicking on the button in .two get's called as many times as there are div's on the screen, as the function is called once the dynamic div is created, but should only be called once.
There's a lot of code to do all this, but I think I explained what happens pretty clearly. I will however whip up a demo if that would help more.
You want to use the .on function:
$('body').on('click', '.two button', function(){
var id = $(this).parent().attr("id");
alert(id);
});
I would change the 'body' part of that to the real container of these buttons. So say the buttons are always inside a content div with id my-div, you'd do:
$('#my-div').on('click', '.two button', function(){
var id = $(this).parent().attr("id");
alert(id);
});
You also only need this code to run once, so no need to put it in a function that gets called multiple times. Just put it in your $(document).ready(....).
A fiddle: http://jsfiddle.net/gromer/dxbqz/
This is what "event delegation" is for. You set up a handler on the document and it will handle events from its descendants, even if they are created after the handler is attached:
$(document).on("click", ".two button", function(){
// put a click hander on the document to process clicks
// from buttons that are descendants of elements with class=two
The problem is this: "At the end of cloneDiv(), I call content(), so that clicking on the elements inside will produce the same results as above." What happens is that you are compounding the events on to the existing elements so that is why you get so many callbacks. You should instead use the .on function, and use it only once. If you call .on multiple times it will produce the same results because multiple events will be registered.
$(".two button").on("click",function(){
var id = $(this).parent().attr("id");
alert(id);
});
Do this once, every button matching (".two button") will respond to it, even if appended later.
Another approach would be to pass in the element to the content() call and then mark it up from there if you are always calling this function when creating the elements anyway.
function content(element){
$(element).click(function(){
var id = $(this).parent().attr("id");
alert(id);
});
}
As a side note, using alerts to debug can be problematic as they interrupt program execution. I would highly recommend using console.log(id) instead and then looking in the console for your testing variables. console.trace() is also a good one to keep in mind if you are using a third party script and need to see what went wrong where.

Prevent click jump on jQuery one() function

I'm using the one() function in jQuery to prevent multiple clicks. However, when they click the element a second time, it does the annoying click jump and sends you back to the top of the page.
Is there a way to prevent this from happening? Unbinding the click and re-binding it when the function is done has the same result (and I'm assuming that one() just unbinds the event anyways).
A quick example of this happening: http://jsfiddle.net/iwasrobbed/FtbZa/
I'm not sure if this is better or not, but you could bind a simple function that maintains the return false.
jQuery provides a shortcut for this with .bind('click',false).
$('.someLink').one('click', function() {
$(this).bind('click',false);
return false;
});
or if you have several of these links, a very efficient alternative would be to use the delegate()[docs] method to bind a handler to a common ancestor that takes care of the return false; for you.
Here I just used the body, but you could use a nearer ancestor.
$('.someLink').one('click', function() {
});
$('body').delegate('.someLink','click',function(){return false;});
Try changing the href so the '#' isn't being used: http://jsfiddle.net/FtbZa/1/
$('.someLink').one('click', function() {
alert('test');
return false;
}).attr('href', 'javascript:void(0);');
You could use the standard .click() function and a little logic:
1. $('.someLink').click(function(event) {
2. event.preventDefault();
3. if (!$(this).hasClass("clicked"))
4. alert('This will be displayed only once.');
5. $(this).addClass("clicked");
});
Listen to anything with the class someLink for a .click()
Stop the browser doing what it would normally do.
Check if the object has the class clicked (Note this could be any name you wanted)
It hasn't so do something.
Add the class clicked so next time its clicked, it will ignore your code.
See the demo here
The problem is that after the listener has been unbound there is nothing stopping the browser from honoring the link (Which it is treating as an anchor tag) and trying to go to it. (Which in this case will simply lead to the top of the page.

call js script on every change state

i have big table with many html items such as select, textbox, radio-button, checkbox. also i have some function. i want to call this function on every change in item. for example select was changed, or some text type in textbox, or click radiobutton. how can i simply subscribes and call my js function? i can insert in any item
onchange='function()'
but may be jquery allow more simly way? any sample?
jQuery's .change() event will work for all types of input elements.
But for efficiency, if you've got a lot of elements, you might want to look into .delegate():
$('body').delegate('input', 'change', function() {
// in here, $(this) is the input that has changed
});
Delegating is more efficient since it creates only a single handler and makes use of event bubbling.
In JQuery, you could use a .click() event on the items you want to change. For example:
$("#the-element").click(function(){
//Enter your function here
});
Hope that helps!
You can use a jQuery selector to wrap all the items you want the event attached to. Then, use bind method on that wrapper to attach events.
An example:
$('input').bind({
click: function() {
// do something on click
},
mouseenter: function() {
// do something on mouseenter
}
});

Intercept javascript event

Here's what I'm trying to do :
I have a page with some links. Most links have a function attached to them on the onclick event.
Now, I want to set a css class to some links and then whenever one of the links is clicked I want to execute a certain function - after it returns , I want the link to execute the onclick functions that were attached to it.
Is there a way to do what I want ? I'm using jQuery if it makes a difference.
Here's an attempt at an example :
$("#link").click(function1);
$("#link").click(function2);
$("#link").click(function(){
firstFunctionToBeCalled(function (){
// ok, now execute function1 and function2
});
}); // somehow this needs to be the first one that is called
function firstFunctionToBeCalled(callback){
// here some user input is expected so function1 and function2 must not get called
callback();
}
All this is because I'm asked to put some confirmation boxes (using boxy) for a lot of buttons and I really don't want to be going through every button.
If I understand you correctly, is this wat you wanted to do..
var originalEvent = page.onclick; //your actual onclick method
page.onclick = handleinLocal; //overrides this with your locaMethod
function handleinLocal()
{ ...your code...
originalEvent ();
// invoke original handler
}
I would use jQuery's unbind to remove any existing events, then bind a function that will orchestrate the events I want in the order I want them.
Both bind and unbind are in the jQuery docs on jquery.com and work like this...
$(".myClass").unbind("click"); // removes all clicks - you can also pass a specific function to unbind
$(".myClass").click(function() {
myFunctionA();
myFunctionB($(this).html()); // example of obtaining something related to the referrer
});
An ugly hack will be to use the mousedown or mouseup events. These will be called before the click event.
If you can add your event handler before the rest of handlers, you could try to use jQuery's stopImmediatePropagation

Categories