Issue with clicking elements, that were added to page with .html() - javascript

So, I'm having trouble with clicking events on elements, that were rendered by .html() function of jQuery.
Here's my code I'm testing with:
<html>
<head>
<title>Test</title>
<script type="text/javascript" src="static/jquery-2.0.3.min.js"></script>
</head>
<body>
<div id="content">
<input type="submit" name="loginButton" id="loginButtonID"/>
</div>
<script>
$('#loginButtonID').click(function() {
$('#content').html('<button name="loginButton" id="newPasswordID">New Button</button>')
});
$('#newPasswordID').on('click', function() {
alert("alert");
});
</script>
</body>
</html>
As you can see, at the very beginning, I render a button with id="loginButtonID". I have .click() event on it, that creates in its turn another button by .html() (since .text() will return just HTML-code of that button) with id="newPasswordID" and for that button I have another event .on() as it should be (not .click()), but that event just doesn't work. So the question is: how to make that .on() event work for the second button?
Thanks.

The problem is that the #newPasswordID element doesn't exist as of when you try to hook the event. So since when you do $("#newPasswordID") it doesn't match anything, no handler is set up.
You can either do that after you render that element, or you can hook the event on some container that the element goes in (looks like #content) and use event delegation:
$("#content").on("click", "#newPasswordID", function() {
// ...
});
Since that really hooks click on #content, but then only fires it if the event travelled through an element matching #newPasswordID, it doesn't matter whether #newPasswordID exists as of when you hook up the event or not.

Try this:
$('#content').html(
$('<button />').attr('name',"loginButton")
.attr('id', "newPasswordID")
.click(function() {
alert('alert');
})
);

Related

Changed ID not being found by jQuery

Tough to come up with the title for this question.
More for proof of concept, I'm wondering why this doesn't work. What I'm attempting to do is use a jquery event to change the ID attribute, then use another jquery event bound to this newly changed ID.
For example:
<?php
echo <<<END
<html>
<head>
<style>
#before {
color:maroon;
}
#after {
color:blue;
}
</style>
<script type="text/javascript" src="http://code.jquery.com/jquery-2.1.1.min.js"></script>
<title>Test</title>
<script type="text/javascript">
$(document).ready(function(){
$("#before").hover(function() {
$(this).attr("id","after");
});
$( "#after" ).click(function() {
alert( "Handler for .click() called." );
});
});
</script>
</head>
<body>
<p id="before">TEST TEXT</p>
</body>
</html>
END;
?>
On hover over my test text, the color changes from maroon to blue, as expected. It is my understanding that the text would now have an ID of "after" and the click event handler function would apply when clicked. However that is not the case the quick event handler and its associated alert does not appear to trigger.
I am new to jquery is there perhaps an update handlers function I'm overlooking?
It works with the same principle as Event binding on dynamically created elements?.
When you add a event handler to an element where the element is found using a selector, the selector is executed only once when the code is executed after that the handler is added to the element. Once is has happend if you change the selector values associated with the element it will not reflect in the attached handlers.
For example in your case you are adding the a handler to the element with id before in dom ready handler, so once the dom ready event is fired your selector is evaluated and it returns a single element to which you are adding the handler. In the same dom ready handler you are trying to add a click handler to an element with id after, but at dom ready there are no elements with that id so that handler is not attached to any element.
Now at a later time you are changing the id of the elemnet, but it will not affect in the already attached handler nor will it add a new handler.
The solution here is to use a mechanism known as event delegation.
Demo:
$(document).ready(function() {
//there is no need to use hover as your want to add the class when the mouse enter the element and you don't want to do anything in mouseleave
$("#mytarget").mouseenter(function() {
$(this).addClass("after").removeClass('before');
});
//look at the use of event delegation
$(document).on('click', '.after', function() {
alert("Handler for .click() called.");
})
});
.before {
color: maroon;
}
.after {
color: blue;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<p id="mytarget" class="before">TEST TEXT</p>
You can fire the click event after the hover event
$(document).ready(function(){
$("#before").hover(function() {
$(this).attr("id","after");
$( "#after" ).click(function() {
alert( "Handler for .click() called." );
});
return false;
});
});

Access dynamically created items using jQuery?

I have a page where some html is being dynamically added to the page.
This is the html and javascript that is created:
<div>
<script type="text/javascript" language="javascript">
$('#btn').click(function() {
alert("Hello");
});
</script>
<a id="btn">Button</a>
</div>
Looking in my Firebug console, I get an error that says:
TypeError: $("#btn") is null
jQuery is being loaded on the page initially.
What am I doing wrong here?
You have to bind on() (or the events defined within the on() method, to an element that exists in the DOM at the point at which the jQuery was run. Usually this is on $(document).ready() or similar.
Bind to the closest element in which the $('#btn') element will be appended that exists in the DOM on page-load/DOM ready.
Assuming that you're loading the $('#btn') into the #container div (for example), to give:
<div id="container">
<div>
Button text
</div>
</div>
Then use:
$('#container').on('click', '#btn', function(){
alert('Button clicked!');
});
Use .on to wire up the event to your button. Check this SO answer:
Event binding on dynamically created elements?
$(document).ready(function() {
$('body').on('click', '#btn', function() {
alert("Hello");
});
})
Edit: I added the document ready code, you'll want to make sure you do that.
Fixed.
you are looking for .on here which will bind the click event to dynamically added nodes.
$("#parent_container").on("click", "#btn", function () {
alert("hello")
})
the docs: http://api.jquery.com/on/
Try
<div>
<a id="btn">Button</a>
</div>
<script>
$('#btn').on('click', function() {
alert("Hello");
});
</script>
The problem in your code is that you are attaching the event to the button before the button is being created.
Correct version is:
<div>
<a id="btn">Button</a>
<script type="text/javascript" language="javascript">
$('#btn').click(function() {
alert("Hello");
});
</script>
</div>
This should do the job.
Use the .live() function of jQuery

Scope in jQuery(javascript)

I simplified my code for next example. So, please don't be wondered why I'm using ajax here.
<!DOCTYPE>
<head>
<style>.not { background:yellow; }</style>
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script>
<script>
$(document).ready(function() {
$(".not").click(function(e){
e.stopPropagation();
alert('good');
});
$(".click").click(function(e){
$.post('page2.php', 'q=1', function(data){
$('body').append('<p class="click">Click here to add new paragraph <span class="not">[not here]</span></p>');
}, "json");
});
});
</script>
</head>
<body>
<p class="click">Click here to add new paragraph <span class="not">[not here]</span></p>
</body>
New rows don't make any alert for class=not! It is inexplicably for me :'(
Thanks for unswer!
Assuming jQuery 1.7.x, use this:
$(document).on('click', ".not", function(e){
alert('good');
}).on('click', ".click", function(e){
if(!$(e.target).is('.not')) {
$('body').append('<p class="click">Click here to add new paragraph <span class="not">[not here]</span></p>');
}
});
The problem is, .click will only bind to elements that exist when it's called. Using .on the way I'm suggesting delegates the click handling to the document element. By passing a selector as the second argument, you tell jQuery to run the event handler only if the event target matches the selector.
Put the $(".not")... part inside a function, such as disableNot = function() {$(".not").click......}. Then, after appending the new paragraph, call disableNot() to update the event handlers. (Also call disableNot immediately after defining it, so any .not elements already on the page are given their handlers.)
In your ready event handler, you use $('.not).click. click is an alias for bind, and bind only works on elements that are already in the DOM.
If you're using jQuery 1.7, you can use on instead, in its delegate-like form.

jQuery function not binding to newly added dom elements

Here's index.html:
<head>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.5.2/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$('.btn_test').click(function() { alert('test'); });
});
function add(){
$('body').append('<a href=\'javascript:;\' class=\'btn_test\'>test</a>');
}
</script>
</head>
<body>
test1
add
</body>
If I click on test1 link, it shows alert('test'), but if I click on add link then click on test, it doesn't show anything.
Could you explain it?
For users coming to this question after 2011, there is a new proper way to do this:
$(document).on('click', '.btn_test', function() { alert('test'); });
This is as of jQuery 1.7.
For more information, see Direct and delegated events
You need to use a "live" click listener because initially only the single element will exist.
$('.btn_test').live("click", function() {
alert('test');
});
Update: Since live is deprecated, you should use "on()":
$(".btn_test").on("click", function(){
alert("test");
});
http://api.jquery.com/on/
I have same problem like question I was just near to pulling my hair then i got the solution.
I was using different syntax
$(".innerImage").on("click", function(){
alert("test");
});
it was not working for me (innerImage is dynamically created dom)
Now I'm using
$(document).on('click', '.innerImage', function() { alert('test'); });
http://jsfiddle.net/SDJEp/2/
thanks #Moshe Katz
.click binds to what is presently visible to jQuery. You need to use .live:
$('.btn_test').live('click', function() { alert('test'); });
Use Jquery live instead. Here is the help page for it http://api.jquery.com/live/
$('.btn_test').live(function() { alert('test'); });
Edit: live() is deprecated and you should use on() instead.
$(".btn_test").on("click", function(){
alert("test");
});
This is because you click event is only bound to the existing element at the time of binding. You need to use live or delegate which will bind the event to existing and future elements on the page.
$('.btn_test').live("click", function() { alert('test'); });
Jquery Live
you need live listener instead of click:
$('.btn_test').live('click', function() {
alert('test');
});
The reason being is that the click only assigns the listener to elements when the page is loading. Any new elements added will not have this listener on them. Live adds the click listener to element when the page loads and when they are added afterwards
When the document loads you add event listeners to each matching class to listen for the click event on those elements. The same listener is not automatically added to elements that you add to the Dom later.
Because the event is tied to each matching element in the document ready. Any new elements added do NOT automatically have the same events tied to them.
You will have to manually bind the event to any new element, after it is added, or use the live listener.
$('.btn_test').click
will add the handler for elements which are available on the page (at this point 'test' does not exist!)
you have to either manually add a click handler for this element when you do append, or use a live event handler which will work for every element even if you create it later..
$('.btn_test').live(function() { alert('test'); });
After jquery 1.7 on method can be used and it really works nice
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js">
</script>
<script>
$(document).ready(function(){
$("p").on("click",function(){
alert("The paragraph was clicked.");
$("body").append("<p id='new'>Now click on this paragraph</p>");
});
$(document).on("click","#new",function(){
alert("On really works.");
});
});
</script>
</head>
<body>
<p>Click this paragraph.</p>
</body>
</html>
see it in action
http://jsfiddle.net/rahulchaturvedie/CzR6n/
Or just run the script at the end of your page
You need to add a proper button click function to give a proper result
$("#btn1").live(function() { alert("test"); });

Dynamically adding content to HTML page using JavaScript (and JQuery) - how to access new content?

I have a HTML file that contains only the basic elements (html, head, body, ...) and I want to fill it up with content stored in an external file ("content.html") in my case, using JavaScript (and JQuery). I have accomplished that with function $.get(), but I don't know, how to access the information I got with this function.
For example, I want to throw an alert if a link is clicked. My code looks like this:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN">
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$.get("content.html", addContent); // calls addContent
function addContent(data) // fills <div id='content'> with content.html
{
$("#content").html(data);
alert('Load was performed.');
}
$("a").click(function(event){ // !!!if any link is clicked, throw an alert
alert("Link clicked");
event.preventDefault();
});
});
</script>
</head>
<body>
<div id="content">
<!--CONTENT OF content.html WILL BE INSERTED HERE-->
</div>
</body>
</html>
This is how content.html looks like:
<h1>Band Creator Home</h1>
<p>Currently following apps are available:</p>
<ul>
<li>Bands</li>
<li>Instruments</li>
<li>Musicians</li>
<span></span>
</ul>
Since there is no element in the original HTML, alert "Link clicked" is never thrown. How can I access these elements collected by $.get() ?
You are looking for .live() bindings. Do it like:
$("a").live('click', function(event){ // !!!if any link is clicked, throw an alert
alert("Link clicked");
return false;
});
The event method .preventDefault() does not work within .live(), return false instead. Since .live() adds an even listener to the document.body, it's always a good idea to use .delegate() if possible. You can tell .delegate the closest parent node which all elements share you need to watch. In your instance:
$('ul').delegate('a', 'click', function() {
alert('Link Clicked');
return false;
});
Ref.: .live(), .delegate()
AJAX is asynchronous.
The server only sends a reply some time after the get method finishes.
Therefore, you end up adding the click handler before addContent is called, before the new elements exist.
If you add the handler inside addContent, it will work fine, since the new element will have already been added.
Alternatively, you can use jQuery's live method to add a handler to all elements that match the selector, no matter when they were created.
An alternative to the live method is using delegate on some parent of the newly created elements. This is useful if you don't want the event to be propagated to the top of the DOM hierarchy.
$("#parentofa").delegate("a", "click", function(event) {
// ... my handler
event.preventDefault();
})
The <a> element that was clicked is stored in event.target
Note that preventDefault is working here but that the event has already been propagated until the parent element (i.e. all elements in between have received the element already)
There are some different ways. You can set the events after loading the content:
function addContent(data) {
$("#content").html(data);
alert('Load was performed.');
$("#content a").click(function(event){
alert("Link clicked");
event.preventDefault();
});
}
You can use the live method to catch the even when it bubbles up:
$("a").live('click',function(event){
alert("Link clicked");
event.preventDefault();
});
If you are using version 1.4.2 or later of jQuery, you can use the delegate method, which is like the live method, but you can check for bubbling events in a closer scope than the body:
$("#content").delegate('a', 'click',function(event){
alert("Link clicked");
event.preventDefault();
});

Categories

Resources