how to use delicate function without including any event - javascript

I have some functions which don't need any event for calling, like these
$(document).ready(function(){
var t = new $.TextboxList('#form_tags_input', { });
});
and this
$(function() {
$('.tags').tagsInput({width:'auto'});
});
The problem is that I have to call them in a dynamically created post with jQuery. If there is any even then yes, I can use the delicate function for this purpose. But here no event is included.
How should I make this function to work for a component which is created dynamically by jQuery?
I am new in JavaScript and jquery so please edit my code to provide me an answer.

Use this function it will see for the node first and then will open the menu attached with that element.
$('body').on('DOMNodeInserted', ".tags", function(){
$(this).tagsInput({width:'auto'});
});
Hope it helps.
Cheers!

Related

jQuery .<Something that can automatically run a callback function>(). What would it be?

I need something like .load() but that can only work for images and iframes. I would want to do this in order to automatically attach a selector element in "this" variable.
$('document').ready(function({
$('a').<Something to automatically run the stuff below when page is loaded>(function(){
// Placeholder is to store the href somewhere so the link does not go to a webpage atm.
$(this).attr('placeholder',$(this).attr('href'));
$(this).attr('href','javascript:');
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
My Link
I am not sure if you want to achieve this simple thing ? :
$('document').ready(function({
$('a').each(function(){
$(this).attr('placeholder',$(this).attr('href'));
$(this).attr('href','javascript:');
});
});
$('element').each allows to loop over all elements, and you can use $(this) inside closure to modify the element itself.
jQuery supports chaining so the simplest and most likely the most performant answer is:
$('document').ready(function({
$('a').each(function() {
var a$ = $(this);
a$.attr('placeholder',$a.attr('href'))
.attr('href','javascript:void(0)');
});
});
Everytime you call $(this) it has to create a new jQuery wrapper around this which you might as well cache via a variable.

What is the jQuery or javaScript syntax to make functions work only on the active/focused input/button/text area?

I am a beginner & self interested web coder.
I have been testing, asking, retesting, trying, reading up on different functionality solutions in javaScript to an online form which will consist of a multitude of <textarea>'s once I am done.
I am fairly ok, with the current state of functions, which are based upon several js events. Example code would be (written funny so it is easier to read in the forum, actual code is one line obviously):
<textarea
data-id="0"
class="classOne classTwo"
id="dataInput_0"
name="xInput_row_1"
onFocus="functionOne();"
onBlur="functionTwo();"
onKeyUp="functionThree();">
</textarea>
I built and tested all the functions to work specifically on the id="dataInput_0" using getElementById. Example:
var d = document.getElementById("dataInput_0");
So my question is how to I make the functions trigger for other "dataInput" id's?
In other words:
var d = document.getElementById('whichever dataInput that is active/focused');
Thanks!
The simplest way to work with your current code would be to do this:
onFocus="functionOne(this);"
...and then define your function:
function functionOne(el) {
// el is the element in question, used e.g.:
alert(el.name);
}
Within the onFocus=... the browser sets this to the element in question, so you can then pass it as a parameter to your function. Your function then just uses it directly rather than having to go via getElementById().
But since you mentioned jQuery, you could remove the inline onFocus and other onXYZ handlers from your html and just do it all in your JS as follows:
$("textarea").focus(function() {
// here this is the element in question, e.g.:
alert(this.value);
});
That defines a focus handler for all textareas on the page - to narrow it down to just textareas with class "classOne" do $("textarea.classOne"). Within the function this refers to the focused element. You could use the .blur() and keyup() methods to assign handlers for the other events shown in your code.
My suggestion is to use attribute selector $('input[id^="dataInput_"]') for this and use the jQuery's .on() handler this way:
$('input[id^="dataInput_"]').on({
focus: function{
functionOne($(this));
},
blur: function(){
functionTwo($(this));
},
keyup: function(){
functionThree($(this));
}
});
and the functions:
functionOne(obj){
console.log(obj.val());
}
functionTwo(obj){
console.log(obj.val());
}
functionThree(obj){
console.log(obj.val());
}

Jquery bind()/live() within a function

I wrote a little pager which removes and rewrites content. I have a function called after loading the page, it shall be executed after changing the page as well. Because I do not wat to implement the function twice (on initialisation and after changing the page) I tried bind()/live() and a simple function.
The function looks like this:
jQuery('.blogentry').each(function (){
jQuery(this).click(function(){
//Clicking on the element opens a layer, definitely works - I tested it
});
});
It is executed after initialisation, for executing it after page changes as well I tried the following:
jQuery('.nextPage, .prevPage').click(function changePage(){
// Changing page and rewriting content
showEntry();
});
//...
showEntry();
//...
function showEntry(){
jQuery('.blogentry').each(function (){
jQuery(this).click(function(){
//Clicking on the element opens a layer, definitely works - I tested it
});
});
}
But the function is not executed if put inside a function (lol) and called via showEntry();
Afterwards I tried to bind the function...
jQuery('.nextPage, .prevPage').click(function changePage(){
// Changing page and rewriting content
jQuery('.blogentry').bind("click", showEntry);
});
//...
jQuery(this).click(function showEntry(){
//Clicking on the element opens a layer, definitely works - I tested it
});
Did not work either. Code after the bind()-line would not execute as well.
I thought maybe it's a problem to bind to an event function, if an event is already given via the parameter so i also tried this:
jQuery('.nextPage, .prevPage').click(function changePage(){
// Changing page and rewriting content
jQuery('.blogentry').bind("click", showEntry);
});
//...
function showEntry(){
//Clicking on the element opens a layer, definitely works - I tested it
});
}
No success at all. Maybe I cannot call the function from inside the function regarding to the bind()? Maybe I just do not understand the bind()-function at all? I also tried the live() function since it seemed to fit better, as I am rewriting the content all the time. But it had the same effect: none...
The simplest way to implement this should be
jQuery('.blogentry').live('click', function() { /* onclick handler */ });
This should bind the function to every blogentry on the page at the moment of the call and all the blogentries that are added to the page later on.
Additional notes:
In $(foo).each(function() { $(this).click(fun); }); the each is unnecessary - $(foo).click(fun); is enough.
$(foo).bind('click', fun); is functionally equivalent to $(foo).click(fun) - it does not matter which one you use.
You can use delegate or bind. don't call the function like that, just create a delegate with .blogentry and it should update even after you load a new page via ajax. It will automatically do this.
$("#blogcontainer").delegate(".blogentry", "click", function(){ //open layer });
This should work for you
$(body).delegate(".blogentry", "click", function(){
showEntry();
});
alternaltivly you can use event delegation
$(document).ready(function () {
$('#blogcontainer').click( function(e) {
if ( $(e.target).is('.blogentry') ) {
// do your stuff
}
});
});
hence, no need to bind each blogentry at creation or reload, and it's (slightly) faster.

not work class .numeric after add new input. what do i do?

why after add new input, class .numeric (normal number formatting) in js code not worked?
This way for normal number formatting is right?
What is your suggestion?
i not want use of plugin.
DEMO
$("input:text.numeric").keyup(function () {
$val = $(this).val().match(/[0-9]/g).reverse().join("").match(/[0-9]{1,3}/g).join(",").match(/./g).reverse().join("");
$(this).val($val)
})
With respect
If you add something to the page after it is done loading you will need to use the live() function on your scripts to make them work on the new data.
If you do something like:
$('#container').append('<div class="clickme">The text goes here</div>');
or
$('#container').load('script.php');
...they are both considered adding to the page.
Using live(), your code would become:
$("input:text.numeric").live('keyup', function () {
$val = $(this).val().match(/[0-9]/g).reverse().join("").match(/[0-9]{1,3}/g).join(",").match(/./g).reverse().join("");
$(this).val($val)
});
Read more here: http://api.jquery.com/live/
You need a future-proof event observer. Since the keyup bind is assigned to existing nodes, any nodes you create afterwards will not be bound to that event. You need to use live or delegate
Change
$("input:text.numeric").keyup(function () {
to
$("input:text.numeric").live('keyup',function () {
or
$('.find_input').delegate('input:text.numeric','keyup',function () {
delegate() is much more resource-friendly than live() but you need to know the parent ahead of time. In your example, I'd recommend it.
Working demo: http://jsfiddle.net/AlienWebguy/zgWr3/4/
Use the delegate()[docs] method to bind the handler to the .column container.
Example: http://jsfiddle.net/zgWr3/3/
$('.column').delegate("input.numeric:text",'keyup',function () {
$val = $(this).val().match(/[0-9]/g).reverse().join("").match(/[0-9]{1,3}/g).join(",").match(/./g).reverse().join("");
$(this).val($val)
});
This way, any "input.numeric:text" elements inside of .column will invoke the handler irrespective of when they're added to the DOM.
I also changed the selector around a little. Seems more understandable to me.

Observing events on dynamically inserted objects in the DOM

On load, I add a desired behavior on all textareas on a page.
Event.observe(window, 'load', function() {
$$('textarea').each(function(x) {
x.observe('keydown', dosomethinghere)
});
});
This works because the textareas are already in the DOM, but how should I treat textareas that are dynamically added after the page loads (ex: if I have a button that says "Add More"). I would like these newly created textareas to have the same behavior.
The way I do it is by just observing the new textarea when I add it, like this:
function doSomethingWithTextAreas(){
//do something.
}
document.observe("dom:loaded", function() {
$$('textarea').each(function(s){
s.observe('keydown', doSomethingWithTextareas);
});
$('add_more').observe('click', function(){
textarea = new Element('textarea');
textarea.observe('keydown', doSomethingWithTextareas); //Observes the new textarea.
Element.insert($('textarea_container'), {bottom:textarea});
});
});
Consider using jQuery Live.
$.live() would work as STAii mentions, but there is discussion of implementing a similar function in prototype as well. That would probably be of more benefit so you don't have to add another library.
Well, the answer is a bit tricky. The only way to do this is to maintain a cache of events listeners for your textareas. When adding a new textarea to your page, you would need to call Event.stopObserving on all your cached events. You would then call your $$('textarea').each(...) code again to bind to all the elements.
Thankfully, someone has done this for you already in a very handy lightweight prototype extension called lowpro: http://www.danwebb.net/2006/9/3/low-pro-unobtrusive-scripting-for-prototype
You can do what you wish as simply as:
Event.addBehavior({
'textarea:keydown': function(e) {
dosomethinghere(); // e.g. this.hide();
}
});
Then whenever you add a new textarea dynamically, you simply call Event.addBehavior.reload();
I should point out that "e" is the Event object, and "this" is the element inside the context of the function(e) {} definition.
A nice way of doing this is to have the javascript function which adds the text areas fire an event which any other function can observe and act on. So:
function add_textarea() {
// Code creates a new <textarea> and adds it to the page
var textarea = new Element("textarea");
$("some-form").insert(textarea);
textarea.fire("textarea:add")
}
document.observe("textarea:add", function(event) {
event.target.observe('keydown', dosomethinghere);
});
This allows your 2 functions--one that adds a new textarea and one which attaches observers--to be loosely coupled and not know anything about each other. One simply needs to fire a custom event which the other can observe.

Categories