Javascript each() function in newly added doms - javascript

i use ajax to load some data into one of my divs , i have a each function that do not work on newly added doms , how can i bind it with something like "live" or "on" to take effects on newly added DOMs by ajax ?
$('ul.bigs > li').each(function(){
console.log(this)
})
i mean "on" to something like :
$(document).on('click', '.header a', function() {
//do something
})

Wrap it in a function and call it after you've appended the data to the DOM.
function update() {
$('ul.bigs > li').each(function(){
console.log(this)
})
}
// Below is pseudo-code
$.ajax(..., function (data) {
// Add the data to DOM
update() // Call the update function at the end.
})

What do you mean by "newly added Doms"?
Because if you use something like element.innerHtml = <div id='tst' >/div> It won't work.
Since It does not update the DOM because you're just modifying a String.

Related

Function not working creating a variable and using jquery?

I have a function which changes the width of some images. This happens when I hover over a different div in a different function. For some reason the the called function only performs some lines of code and then it stops.
function hey()
{
alert(0);
var $imgContent = ('.imgContent');
$imgContent.css("width","10%");
alert(2);
}
var $content = $('.content');
$content.mouseenter(function() {
$content.removeClass('full').addClass('partial');
$(this).addClass('full').removeClass('partial');
$(this).find('.img1').css('display','none');
$(this).find('.img2').css('display','');
if($(this).hasClass('cont1')){
alert(1);
hey();
}
if($(this).hasClass('cont2')){
}
if($(this).hasClass('cont3')){
}
if($(this).hasClass('cont4')){
}
}).mouseleave(function(){
$(this).find('.img1').css('display','');
$(this).find('.img2').css('display','none');
$(this).removeClass('full').addClass('partial');
});
In the mouseenter() function when I check if $(this).hasClass('cont1') then I perform an alert, which works. After that I call on function hey(). This is where my problem arises. After calling function hey() i perform another alert(0) , which also works. But the lines of code after that do not get executed and the last alert(2) doesn't work either.
There is an error in your code.
Replace:
var $imgContent = ('.imgContent');
With
var $imgContent = $('.imgContent');
You have a mistake in your jquery object definition.
Per jQuery():
jQuery() — which can also be written as $() — searches through the DOM for any elements that match the provided selector and creates a new jQuery object that references these elements
so in your case you should have:
var $imgContent = $('.imgContent');
$imgContent.css("width","10%");
Also, it's important to note that in your .mouseenter() function you refer to:
$content.removeClass('full').addClass('partial');
$(this).addClass('full').removeClass('partial');
$content and $(this) both refer to the same object, so in essence these lines are pointless.

how to use $.ajax inside .load in jquery

$("#").on("click",function () {
$("#").load('', function () {
$(".").on("click",function(event) {
event.preventDefault();
var data = $(this);
$.ajax({
.........etc
Can we use $.ajax function inside .load in jquery or is there any better way to handle this ?
I'm guessing you are trying to do that because you can't bind the click function on an element that hasn't been created yet. What you should probably be using is event delegation:
$("#id").on("click",function () {
$("#id2").load('');
});
$('#id2').on('click','.class', function() {
//do stuff
});
This will find any click that happens inside of #id2, which already exists, and if it originated from .class, which may or may not exist at the time of binding, will execute the "do stuff" code.

I cant return anything in callback function of jQuery bind

Can Anybody explain why this happen?
This is my code in a plugin called something:
(function($){
$.fn.extend({
something: function(options) {
// Here I define defaults
$(this).bind('change', function () {
return $(this).each(function() {
// a function body
});
});
}
});
})(jQuery);
and I call this plugin in another js like this:
var myarray=new Array();
myarray[0] = $('#selector').something({
regex:/^([\u0600-\u06FF]|\s)*$/,
// another options
});
$('#selector').change(function (){
alert (myarray[0]);
});
in every change in my selector it returns me undefined.
It completely make me insane. Thanks if anyone can help me.
Edit:
You Can Read My complete code here.
In your plugin you are just attaching a change event handler on the element which just runs a loop on all the matched set of elements and returns a jQuery object.
If you want to return something from something plugin then the return statement should be outside the event handler.
$.fn.extend({
something: function(options) {
return $(this).each(function() {
//Do processing here
});
}
});
Now you can use this
var myarray = $('#selector').something({
regex:/^([\u0600-\u06FF]|\s)*$/,
// another options
});
$('#selector').change(function (){
alert (myarray[0]);
});
Note that myarray will be an array because jQuery each returns a jQuery object which itself is an array of DOM elements.
It is all because your 'something' function does not return anything.
One huge problem... "something" is spelled different in plugin than the jQuery method chain when you call it with your selector

Calling jQuery document.ready functions by hand

If I make an AJAX request and want to call all functions that were set up by $(document).ready(). How can I do it? Thank you
$(document).ready();
If that doesn't work, try this:
function startup() {
// All your functions in here.
}
$(document).ready(startup);
And after your AJAX request is finished:
startup();
The easiest way is to use a shared function:
$(document).ready(function() {
setup();
});
$.post('/', {}, function() {
setup();
}, 'json');
But if you're using it to re-assign listeners, you would probably be able to get away with assigning them before they're created, like this:
$(document).ready(function() {
$(document).delegate('.my-button', 'click', function() { });
});
Using this code, all .my-button clicks will be handled by your custom function, regardless of whether the button existed in your DOM upon DOMReady.
Note that:
$(document).ready(function() { ... }); can be minimized to $(function() { ... });
If you're using jQuery 1.7+, prefer .on over .delegate: $(document).on('click', .my-button', function() { });
Prefer narrower context over broader, i.e. $('#close-parent').delegate over $(document).delegate
Instead of triggering document.ready by hand (which would be bad practice IMHO), make a function that's called setup which sets up all listeners etc. and invoke this function when you need to re-apply things etc.

How can I create functions in jQuery and call it on event and pass variable to it?

$(".addcart").click(function(){
$("input[name='items']:checked").each(function() {
//doing something
});
});
I'm trying to create a common class onclick of which I'm doing something. Is there a way I can make "items" a variable, I mean Can I pass checkbox name to this event.
Try this and see if it works out:
$("input[name='items']:checked").each(function() {
alert(this.attr("name"));
});
I think I've used like this somewhere.
[EDIT]
The thing with this is that jQuery passes the current item to the foreach as the context of the variable.
Use bind instead of click
$(".addcart").bind("click", {name: "items"}, function(event){
$("input[name='" + event.data.name + "']:checked").each(function() {
//doing something
});
});
edit:
"How can I create functions in jQuery
and call it on event and pass variable
to it"
That will still be the same procedure. Use bind to attach an event handler, pass it an object with the needed stuff for your function. In your event handler call your function and pass it the object from event.data
$(".addcart").bind("click", {foo: "hello world"}, function(event) {
DoSomethingOnClick(event.data);
});
function DoSomethingOnClick(obj) {
obj = obj || {};
if (obj.hasOwnProperty('foo'))
alert(obj["foo"]);
else
alert("no foo here");
}
You know that all checked items will have a name of items, so that's not very interesting, but maybe you want to retrieve the value of each of the items:
$(".addcart").click(function(){
$("input[name='items']:checked").each(function() {
// To access an attribute of this item use the form $(this).attr(...)
alert( this.value );
});
});
The above uses this to access the element being iterated over. Take a look at the properties of a DOM element to see what properties of this you can access.
You can create a jQuery object out of this using the form $(this) then you can use .attr() to access the attributes of this. For example to get the class/es of this you can use either this.className or $(this).attr("class").
It is faster to directly access the DOM element's properties. But for some more complex manipulations it is good to know that $(this) is also available.

Categories

Resources