This question already has answers here:
Event binding on dynamically created elements?
(23 answers)
Closed 9 years ago.
I am adding dynamic content to a php page using jQuery. I don't have a problem adding the content I just can't seem to find a way to make the new content respond to a click event.
For example (I'm using a div here but could be a button or other type).
$("#oldstuff").after('<div id="newstuff">Some content that should respond to click event</div>');
Edit:
I am currently using jquery 1.9.1, I was using 1.6.2 but I am checking out magnific-popup which required a newer jquery version.
I didn't post my failed attempts (
$("#newstuff").click(function() {...
$("#newstuff").live('click', function() {...
binding the click event, etc.
because I assumed that I am missing something fundamental that a more seasoned jQuery user would spot without the noise of broken code.
You can attach a click event before inserting the element into the DOM:
$('<div id="newstuff">...</div>').click(function(){
//do something
}).insertAfter('#oldstuff');
can't seem to find a way to make the new content respond to a click event.
You have to do event delegation
$("#oldstuff").on("click", '#newstuff',function(){
alert( $(this).text() );
});
What you need is to attach the event to the parent element.
HTML:
<div id="parent">
<div class="thediv">Hello</div>
</div>
JavaScript:
function addDiv() {
var div = document.createElement('div');
div.className = 'thediv';
document.getElementById('parent').appendChild(div);
}
$('#parent').on('click', '.thediv', function() {
// ...
});
See if this technique works.
It is probably you are binding event before attaching DOM and also in latest version of jquery library live method is deprecated so try to bind click even after attaching DOM or you can use following code...
first add DOM.
$("#oldstuff").after('<div id="newstuff">Some content that should respond to click event</div>');
and then bind event.
$('#newstuff').on('click',function(){alert('do your stuff!')});
Or
$('#newstuff').click(function(){alert('do your stuff!')});
Try this
$("#yourElementId").live("click",function(){
alert( $(this).text() );
});
As .click is not working after loading dom or dynamically created element
Related
This question already has answers here:
Event binding on dynamically created elements?
(23 answers)
Closed 2 years ago.
I am injecting some html strings to create buttons, however they jquery events don't fire after they have been created. I was told they needed to be "initialized" but cannot find an example.
$('#parent_div).html(<div class="clickable-button">click me here</div>);
will create:
<div id='parent_div'>
<div class="clickable-button">click me here</div>
</div>
And my usual jquery doesn't fire when clicked.
$('.clickable-button').on('click', function (){
console.log('clicked');
}
I got it to work by using a parent that existed before the injection with on()
$('#parent_div').on('click', '.clickable-button', function(){
console.log('clicked');
}
But it seems like there should be a better way to handle this because I don't always know what the parent is and I don't want to hard code new jquery every time I inject something. How do people usually handle this problem?
You can listen at the document level in that case you dont know whats the parent element
$(document.body).on('click', '.clickable-button', function(){
console.log('clicked');
}
i'm creating an application where a user can make a html layout and attach javascript to it.
Now i'm trying to make it so when they click a button, they go to a preview mode where they can see it in action.. so when they click i add the javascript tag ( with their javascript) in the head of the iframe.. this all works fine!
But the problem is when they leave the preview mode, i remove the javascript tag, however when i have code like this:
$('#button').click(function()
{
alert("ok");
});
it still alerts ok when i click the html button (when not in previewmode!), which shouldn't happen!
It seems that when removing the javascript tag, the listeners aren't removed.. Or am i doing it wrong?
Now my question: is there a way to make it so these added eventlisterens are removed when i remove the script tag?
AND YES: i know you can remove eventhandlers with .off(), but since i already have event handlers attached, these will be removed also, and i don't want this!
So two options i can think off:
- rebuild the whole iframe
- store the eventhandlers that were added by the user and when leaving the preview mode, removing them.
Thanks in advance
Each time you "evaluate" JavaScript, it becomes part of the browser's "image", and whether the source is present on the page no longer matters. You need to manually unbind the event, or replace the html segment to which the event was bound.
To remove events from an html element, you can use:
element.parentNode.innerHTML = element.parentNode.innerHTML
This rebuilds the DOM tree using the same HTML.
you need to unbind event.
You can do it by using jquery unbind() or off()
like this:
$("#button").unbind("click");
or
$("#button").off("click");
Demo: http://jsfiddle.net/a6NJk/664/
jquery Doc: http://api.jquery.com/off/
Another good answer: Best way to remove an event handler in jQuery?
Set the event:
var $button = $('#button');
$button.on("click", function() {
alert("ok");
});
Take off the event:
$button.off("click");
You can take off that specific function too
var $button = $('#button');
var eventFunction = function() {
alert("ok");
});
// Set event up
$button.on("click", eventFunction);
// Take event off
$button.off("click", eventFunction);
If you want to remove all events from an element you can use
$("#yourSelector").off()
Because it's not jQuery in general but also vanilla javascript, it would be too much work to keep track of javascript changes, so rebuilding the iframe would be the best option here.
This question already has answers here:
Event binding on dynamically created elements?
(23 answers)
Closed 9 years ago.
I am making dynamic buttons using jQuery. Now I want to use this buttons as any other buttons. Here is my HTML:
<label class='twobuttons'><div id="submit-button" >GO!</div></label>
<div id='result'></div>
And here is my JavaScript:
$(document).ready(function(){
$('#submit-button').click(function(){
$('#result').append("<label><div id='share' class='longbutton'>Share this route</div></label>");
$('#result').append("<label><div id='goback' class='longbutton'>Create another one !</div></label>");
});
$('#share').on("click",function(){
alert('hi');
});
$('#goback').on("click",function(){
alert('hello');
})
});
I'm specifically having trouble with the $('#share').on( part.
I tried the on() function as suggested here. But it is not working. Here is the fiddle of my code. Please correct me if I am wrong somewhere.
That isn't how .on() works, if you are dynamically creating elements, you can't bind an event handler to it, because at the point the code runs (document.ready), the element doesn't exist. So to "get around" that, you bind the event to a parent element (that exists) and then add the actual element you'll be clicking on as a parameter like this:
$('body').on("click", "#share", function(){
alert('hi');
});
$('body').on("click", "#goback",function(){
alert('hello');
})
DEMO
You should setup event delegation on #result instead, because by the time you're trying to setup the click handlers on #share, the element itself has not been added yet.
$('#result').on('click', '#share', function() {
// your code here
});
Try not to bind the event handler to $(document) by default; the closest element that will not get removed is the prime candidate.
Alternatively, only bind the click handlers after you've added the new elements.
Update
You're appending elements with a fixed identifier at every click of your button; note that identifiers should be unique per document, so you should make sure that the action is performed at most once.
The way the .on() method works changes according to how you use it. In your example the .on() method behaves similar to bind and will only work on elements that already exist.
Try this:
$(document).on("click",'#share',function(){
alert('hi');
});
DEMO
It's not enough to use .on(). You have to use event delegation with an element (such as document) that existed before your dynamically-created elements:
$(document).on('click', '#share', function () {
alert('hi');
});
(Based on your fiddle, you can use #result instead of document.)
Fiddle
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Binding dynamically created elements in jQuery
Is there a way I can change the following code:
$('#city')
.focus(function () {
$('option[value="99"]', this).remove();
store.setItem($(this).attr('id'), $(this).val());
})
.change(function () {
store.setItem($(this).attr('id'), $(this).val());
$(this).attr("title", $("option:selected", this).attr("title"));
$('#detailData').html("");
});
So that it works for selects even if they have not yet been created as long as they have the class "update-title". for example:
<select class="update-title">
I saw some implementation using live but someone said it was not good to use. Also is there much of an overhead doing this. Would it be better for me to add the code after I am sure the selects have been created with document.ready() ?
Have a look at on. This is a replacement for live which would do this for you.
You need on:
$(document).on('change', '.update-title', function(event){
// your business here
});
This way the document listens for any events triggered on .update-title elements, wether they were there at document load or not.
Best way is to use delegation - so you bind the event handler to a parent element that exists at the time the dom is loaded - It will in turn listen for events on the given elements and handle them
ex with jQuery 1.7+
$('body').on('click','.update-title', function(){ // <-- all click events will now bubble
// up to body - and it will listen for events from .update-title
// code here
});
It is best practice to bind the event handler to the closest parent at dom load as you can see the overhead in binding to the body/document - all click events will bubble up - wheareas if you bind to a parent element only those inside that element will bubble up.
Yes,you sure thtat the selects have been created with document.ready(), if the html is not loaded in ajax
This question already has answers here:
How to disable all div content
(29 answers)
Closed 9 years ago.
I have the event onClick=window.location.href = 'some url stored in div.
Div contains images as well as text.
I want to show preview using this div, but want clicking disabled on this div because it is taking to the specified location.
I tried it like this:
("#preview").disabled= true;
("#preview").disabled= 'disabled';
("#preview").children().disabled= true;
("#preview").children().disabled= 'disabled';
But none of this is working in firefox 3.6. Somebody please help to solve this problem.
If you want to disable all the div's controls, you can try adding a transparent div on the div to disable, you gonna make it unclickable, also use fadeTo to create a disable appearance.
try this.
$('#DisableDiv').fadeTo('slow',.6);
$('#DisableDiv').append('<div style="position: absolute;top:0;left:0;width: 100%;height:100%;z-index:2;opacity:0.4;filter: alpha(opacity = 50)"></div>');
$('#preview').unbind('click');
First, why would you use an inline event handler while using a library like jQuery. Do it the unobtrusive way and bind all event handlers with Javascript.
This actually will also help you with your problem, because then you can unbind and rebind an event handler very easily:
function myclick() {
window.location.href = 'some url';
}
// bind the click event handler
$(function() {
$('#preview').bind('click', myclick);
});
// unbind the click event handler
$('#preview').unbind('click', myclick);
That way, you can add and remove the functionality, but it won't change any visible change to the div node. You would also have to add a style or css class to let an user know that something changed.
Ref.: .bind(), .unbind()
You should be able to simply do:
// Unbind all click events for all elements
("#preview *").unbind("click");
The other thing you could do is what modals often do with the background: place a non-clickable div on top of the other content.
$("#preview div").onClick = function(){};
Try
$('#the_div_id *').unbind('click');