How to make function work after append - javascript

For example i'm using append, and for example i'm appendig button in to a div, and i have function $('button_id').click(... etc to work affter i append the div, how can i do that.I mean i get no errors, but the function is not starting, it's because i append and then i want to use the function but how to do that, i tryed with delegate, but same thing.I tryed with function in the button tag , onmouseover and then the function thing, but nothing it gives me function not found.What is the solution ?
I have two events, one event is click event that appends button, the other event is click event that does something if the button that was appended is clicked, but that second event is not working ?

Try using :
$(elem).live(...)
It will bind event for now and in the future.

Firstly, it always helps if you show us the exact source code. $('button_id') is the incorrect selector to start with, try something more along the lines of $('#button_id') as your selector. Also, are you appending dynamic content? Anyways, I've always used the delegate() function quite successfully, but have you tried using the live() function? Also, one more thing to make sure of is that you have the newest version of jQuery as your source.
As was stated as well, you can not have duplicate ids, if you want to have a pointer, use class, instead of id="some_id" use class="appended". To select those using jQuery, use the selector like this $('.appended').

Try something like this it will work as per your expectations.
$("#button_id").click(function(){
//On click code goes here
}).appendTo($("#div_id"));

It's difficult to determine the problem you're having without seeing your code, but delegate (or live) should be perfect for what you're trying to do:
$("body").delegate("#b", "click", function() {
alert("ok");
});
$("#example").append('<input type="button" id="b" value="Click" />');
The click handler above will fire when an element with id="b" is clicked, whether or not that element happens to be in the DOM right now or not.
However, as others have noted, it's important to remember that IDs need to be unique within a document, so by the sounds of it you may be better of using classes instead.
You can see an example of the above code running here.

Related

how to toggle a div on click at different div?

I am trying to toggle a div by clicking on a different div. The only relation that two divs share is that they are inside the same div. I have a DIV class comment which holds DIV class button that is supposed to toggle DIV class box when clicked. The box DIV is also inside the comment DIV. I am trying to use jQuery(this).find(".box").toggle();, but it is not working. I am triggering it with $( ".button" ).click(function(). The script is currently at the bottom of my body.
Could anyone please tell me what am I doing wrong here? I've been playing around with the function for a while now, but with no luck at all. Thank you in advance for your replies.
JSFIDDLE here
HTML
<div class="comment">
<div class="button">
show/hide .box with text1
</div>
<div class="box">
text 1
</div>
</div>
<div class="comment">
<div class="button">
show/hide .box with text2
</div>
<div class="box">
text 2
</div>
<div>
jQuery
$( ".button" ).click(function() {
jQuery(this).find(".box").toggle();
});
You can use the jQuery selector .siblings() to re-write your function like this:
$( ".button" ).click(function() {
$(this).siblings().toggle();
});
Here's a working fiddle to demonstrate.
All you really need to do is this:
$(this).parent().find(".box").toggle();
In short, change:
jQuery(this).find(".box").toggle();
To ONE of the following lines:
$(this).parent('.comment').find(".box").toggle();
$(this).closest('.comment').find(".box").toggle();
$(this).siblings(".box").toggle();
Full Explanation:
The reason it's not working is due to the call. Let's break down your call and see what exactly it's doing.
First we see a simple jQuery selector. This tells jQuery to look for a div containing the class button. Keep in mind, jQuery makes use of any CSS selector. So selecting an item in jQuery is as simple as using it's CSS selector!
$( ".button" )
Next you are assigning an event. In this case, that event is click, meaning you're telling a div having the class button to do something every time it is clicked. Keep in mind, however, not including a callback function is an easy way to trigger this event as well.
$( ".button" ).click(function() {
Now this next line is where your mistake takes place.
jQuery(this).find(".box").toggle();
The first mistake is the use of jQuery. after you're already making use of it's short sign, $. You only need use the elongated name if you are using jQuery's noconflict because another JS library you include might use $. In other words, if $('.button') works and is a jQuery object when used, then you don't need to use jQuery.. See more about this here.
Now, that aside, we can look at jQuery(this) as $(this). Whenever you use $(this) in an Event's callback method, you're referring to the element that the event was tied too. That means that $(this) in your function refers to $('.button'). The problem here is that you then want it to find an inner element containing the class box. Well according to your HTML, that can't happen since .box is a sibling, it is not within the inner HTML of .button. Thus you need to make a different call before you can find .box.
There are actually several solutions here. No solution is more "correct" than another, just simply different and possibly causes a different amount of "time" to run. Now I went with what I saw as being the most simple in that it gives you control over the parent element which contains ALL relevant elements to this function. I'll talk about possible alternatives in a minute.
$(this).closest('.comment')
The above line simply tells .button:clicked to look for the first parent element that contains the class .comment. In other words, this won't find any children or siblings, it will only go up from the current element. This allows us to grab the block that contains all relevant elements and information and thus make maneuvers as needed. So, in the future, you might even use this as a variable in the function, such as:
$('.button').click(function(e) {
var container = $(this).closest('.comment');
Now you can find anything within this element block. In this case you want to find box and toggle it. Thus:
$(this).closest('.comment').find(".box").toggle();
// Or with our variable I showed you
container.find(".box").toggle();
Now, there are plenty of alternatives based on your HTML layout. This example I've given would be good even if .box was buried inside more elements inside .comment, however, given your exact HTML, we see that .button and .box are siblings. This means that you could make this call different entirely and get the same result using something like:
$(this).siblings(".box").toggle();
This will allow our currently clicked and selected button element to look for ANY and ALL siblings having class box. This is a great solution and simple if your HTML is that simple.
However, many times, for "comment" type setups, our HTML is not so simple, nor is it static. It's usually something loaded after the page load. This means our general assignment of .click will not work. Given your exact HTML and not knowing a static Parent ID, I would probably write your code as:
$(document).on('click', '.button', function(e) {
$(this).siblings('.box').toggle();
});
What this does is allow for this click event to be assigned to ANY element containing .button for a class, whether loaded with page or even ten minutes after the page is up. However, the caveat often seen here is the assignment is placed on document. Should we assign a lot of events to document it could become quite convoluted and possibly slow down the client's browser. Not to mention the arguments held over all the other headaches this could cause. So here's my recommendation, make a static (loads with page, is a part of page's main HTML) loading area and do our dynamic assignment to that. For instance:
<div id"Comments"><!-- load comments --></div>
Then you can do the assignment as such:
$('#Comments').on('click', '.button', function(e) {
$(this).siblings('.box').toggle();
});
If you have any more questions, just comment!
Side Note .on is for jQuery versions 1.7+. If using older jQuery, use .live or .bind

Fire ajax call on onclick and div

I am attempting to fire off an AJAX call based on the onclick event for a google map integration. The info_window_content function seen here: http://jsfiddle.net/6xw2y/ is the call to create the divs that reside within the map itself.
The "v" variable does in fact contain a store_id. So in the opening line of that function, it has the following:
var info_window_string = "<div class='maps_popup' id="+v.id+">";
Now I have an onclick event that I have duplicated and modified. The first onclick event works just fine and refreshes the panel as it should. The second onclick event doesn't work and the code for that is below:
$("#div").click(function(){
var store_id = $(this).find("div").attr("id");
var pathname = "ajax=1&store_id="+store_id+"&action=get_nearby_stores&distance="+distance+"&lat="+lat+"&lng="+lng+"&products="+$('#edit-products').val();
$("#pocp_content").load("file1.php?" + pathname);
});
That doesn't seem to work. I've also tried changing the div tag to be like this:
$("div").click(function(){
Which still doesn't work. As an added side hint. At one point I was able to get it to refresh but it was passing map-container as the store_id, instead of the id itself.
What am I missing here?
I agree with Joke_Sense10,
but I think you're probably not binding the event to the right DOM element.
Try to open up the developer console in your browser (while being on the side you develop this code for), and enter $("#div") to see if the element it returns is the one you expect. You can also use console.log($("#div")) in the code for that.
answer in comments
For a larger number of elements, always use .on() method as the latter will bind an single event listener on one of the topmost nodes in the DOM tree.
$(document).on("click","#"+v.id, function(){

Fire Function if Button or Other Button Is Clicked

This is probably really obvious, but because it's hard to clearly describe, I can't find anything through searching.
I want to do something where if a user clicks on any of several buttons, one event gets triggered. Is this possible? This is what I've tried, but it doesn't appear to work:
$("#button1" || "#button2").click(function() {alert("example")});
Try this:
$("#button1, #button2").click(function() {alert("example")});
http://api.jquery.com/multiple-selector/
Just apply the handler to all the buttons.
$("#button1,#button2").click(...
Using the , creates a multiple selector, and because of jQuery's "implicit iteration", it will add the click() handler to all matched elements.
That said, if there are many buttons, usually it's nicer to give all the buttons a common class.
$(".my_buttons").click(...

javascript: function of a div in another div having another function

I have a nested div.
The child div is inside the parent div.
How can I distinguish the correct onClick function?
In this case, only the function of parent div is called no matter clicking where I click on the nested div.
<div class="portfo" onclick="showValue()">
<div id="cross" onclick="deleteValue()">
<img src='cross.png' height='15px' width='15px' alt='some'>
</div>
</div>
However, showValue is always called whenever I click on the children div.
delete is a reserved word. Try renaming that function to something else. Then both events should fire when click on the image. First the delete event and then the showval one
I think a library like jQuery can help you out here. Take a look at the .on() method.
I think your problem has to do with Event Propogation. This should help you solve it: Prevent event propogation
Also, delete() is a predefined function in JavaScript, you should rename it to something else, unless you're trying to use the built-in function, in that case, please look at the proper usage: delete

jQuery, <div> loading itself using generated links that are clickable more than once

I got following problem: I generate a div with "jQuery-Load" links. Theese links inside the div should reload the same div with different parameters. I found a working solution, which generates theese links, which are clickable and... ...trigger the chosen event once. So clicking the same link inside the generated div, after it has been regenerated, doesnt work anymore. Tried a lot of things...
It looks like that now:
click
<div id="aaa0"> I'm the div - level1! </div>
div gets filled - beautyful.
It now contains this: (actually its generated what is why wrote [time] wich is time(); generated in php. as a changing parameter
[...] Link inside Updated Div [...]
when i click the link inside the div it works. when i click it again, it wont...
I want to generate a nice 'click deeper inside the data'-thing, which would be amazing getting this thing work and is the reason why everything must be as best as possible inside the "onclick" event :|
Sorry btw. for the a bit confusing post-style, its a confusing topic, and im not native speaking :)
Thanks for any help or hint in advance,
Harry
Maybe you're missing the concepts between bind and live. In bind, jQuery scans the document and attach a function direct to the element. In live, jQuery attach the function to the document, along with the event and the element as parameters. Once a event bubbles, jQuery check the event and the element, and if it match, then a function executes.
After the first run, the dom has changed, and its gonna work using live.
something like that should work:
click
<div id="aaa0"> I'm the div - level1! </div>
<script>
$('a').live('click', function (e) {
e.preventDefault();
var id = this.id;
$(this).next('div').load('getdetails.php?fNumber=36&env=fun&id=' + id);
});
</script>
basically, what is done is a generic rule, which gives all tags the same behavior. (load next div content). ".live()" is used so that loaded tags work (check the jquery documentation for .live(), or event delegation in general).
I'm not certain about the preventDefault stuff. You might want to use somehting else than tag for the link.
click
made the day :) I don't know exactly why, but maybe its possible preventDefault made the bind and live thing for me. Its working fine, so ...
thanks for the hints! :D

Categories

Resources