I am dynamically creating a link, and I am trying to add a click function to it. The links are being added, but the click function is not working. I dont see anything in the console, nor do I get an alert.
var section = $('<section></section>').append('<a class="link" href="#"></a>');
section.find('a.link').attr('title', post.data.permalink)
.text(post.data.title)
.click(function()
{
console.log("function");
alert("hi");
getThread(post.data.permalink);
});
items.push(section[0].outerHTML);
$('#posts').empty().append(items.join(''));
One of the most common mistakes with jQuery. When dynamically adding elements, normal jQuery event handlers don't work, so you need to use .live() to be able to bind events to dynamic elements. This should work:
var section = $('<section></section>').append('<a class="link" href="#"></a>');
section.find('a.link').attr('title', post.data.permalink)
.text(post.data.title)
.live("click", function()
{
console.log("function");
alert("hi");
getThread(post.data.permalink);
});
items.push(section[0].outerHTML);
$('#posts').empty().append(items.join(''));
Notice the use of .live("click", function() { ... }); there? That should solve your problem.
That looks okay. You may try using each() to iterate over that collection. I'm not sure if you can bind even handlers to a jQuery collection like that.
section.find('a.link').each(function(){
$(this).attr('title', post.data.permalink)
.text(post.data.title)
.click(function()
{
console.log("function");
alert("hi");
getThread(post.data.permalink);
});
});
If running this in IE be sure that developer-tools (F12 )are present , otherwise console will be undefined and the call of console.log() will force an error and stops the function from executing.
What else: outerHTML is IE-only, you'll better forget it and never use it.
You don't need to manually join the HTML.
You're binding the event to an element, then taking the HTML of that element and just concatenting it into a string, which is then in turn inserted into the DOM as new elements when you append to #posts.
items is not defined here, but I'm going to go out on a limb and assume it's an array of generated <section>s and etc?
If that's the case, I might be missing something you're trying to do here, but it seems you could just eliminate the whole concatention of HTML and simply append the items array, which would preserve the bound click event.
// Push the element, don't stringify it.
items.push(section);
// Then simply append the "items" elements.
$('#posts').empty().append(items);
Sure, live would probably solve the problem as well, but you certainly can bind events to generated elements then insert them into the DOM. What you cannot do is bind an event to an element then print out it's HTML and insert that into the DOM. Any binding you made with the original element is lost.
Related
So I'm appending a row in a table and then upon clicking a button I want to remove that row.
However I can't do it in a way that seems natural, like:
$(".usun").on("click", function(){
$(this).parent().parent().remove();
});
where .usun is a class of buttons that remove a row in a table. Of course this fragment of code is inside of $(document).ready(.... What seems to work for me is this:
$(this).on("click", ".usun", function(){
$(this).parent().parent().remove();
});
and I don't understand why. Could someone explain me this?
There are several method signatures available for .on() which you can read about here.
Your first syntax ($(".usun").on() is, just one time, attaching click handlers to each individual .usun element. If more are added later, they don't have click handlers.
The second syntax ($(this).on("click", ".usun", function()...) attaches a single listener to the document, saying "any time a .usun inside me is clicked, do something". This covers a case where more matching elements are added after $(document).ready is fired.
That is because that specific .usun does not exist yet when you are registering the event.
You need to register the event to its parent element (prefereably the table id) like so:
$('#yourtableid').on("click", ".usun", function(){ //if table id does not exist, you can use $('body') instead
$(this).parent().parent().remove();
});
This will make sure that you are attaching the events even to 'unborn' elements.
Hope this helps!
So you're aware of this... your question is related to live and non-live lists (collections) in javascript;
review the following Javascript,
var queryStatic = document.querySelectorAll(".usun"); //non-live | static list
var queryLive = document.getElementsByTagName("div"); //live list
queryStatic will return a NodeList that statically references the nodes that satistifed the condition of the query.
If you were to alter/modify the properties/fields/members of a node or it's element that is referenced by this NodeList outside of using the queryStatic, it would be represented in the queryStatic instance;
you cannot, however, add a new element/node to the DOM that would have satisfied the query and expect it to be in that NodeList.
queryList (an HTML Collection), however, will represent both aspects. It is a live list.
The point is, the underline concept has little to nothing to do with method signatures.
Edit
However, in the case of jQuery's .on() method; there is support for attaching the listener to a parent element (like Document) and specifying an additional query criteria.
I have a dropdown ( < select > ) element and a container.
<div class='container' />
<script>
var dropdown = "<select class='multi-dropdown'> ... </select>"
</script>
When the value is changed, You get another of it.
It is logical, that this only happens when the document is ready ( the first one is made there ), and when the client modifies the last one.
$(document).ready( function(){
$('.container').append(dropdown);
$('.multi-dropdown:last').change(function(){
$('.container').append(dropdown);
});
});
Seems to be a working code for me. But what I noticed is, this is not working with the next appended dropdown element. Also if I change the original one, it fires.
My theory is, maybe jQuery already stored the original object as the :last , so it won't select a new element again even if I add new "last" ones.
or
The freshly created element ( this way ) isn't even selectable with jQuery.
Please argue in favor, or against, these are just my ideas.
The issue is that you're newly appended SELECT doesn't ever get an event bound to it. Just because you used the class to bind the change even for the initial SELECT, that doesn't automatically apply to every newly added element to the DOM.
Read up on delegated events, like for the on() function. Or use something like livequery.
Because you are binding the change handler to the :last element at page startup, if the last element changes dynamically it will not be changed accordingly; try and read deeply delegation using on method instead.
Like:
$(document).ready( function(){
$('.container').append(dropdown);
$('body').on('change','.multi-dropdown:last',function(){
$('.container').append(dropdown);
});
});
i made a fiddle with buttons. Now in the javascript, I'm trying to learn jquery and by doing so I'm converting old fiddles into jquery from javascript however I know how.
My problem is that in my function called init, I can't figure out how to convert the javascript way of get an html element with an id stored in a variable.
Old code in javascript:
var but = document.getElementById("but");
New code in jQuery:
var but = $('#but');
I think the problem is that I start with a javascript statement but then use jQuery. I don't know what to do in terms of variables in jQuery.
You need to add in [0] to your jquery code to get the document element, but that is rather pointless with the jquery method of adding event listeners. I would suggest either $('#but').mouseout(etc) or $('#but').on('mouseout', etc).
I've updated your jsfiddle to work as expected, though I'll attempt to give a short tut here:
There are two methods of adding event listeners you should familiarize yourself with per the jquery documentation; the .on() method, and the .(event)() method. The latter you can add to jquery ojects in lieu of object.(eventName)() as an example, adding the click handler to an object: object.click(function() { console.log('executed'); });
This method however is not 'live' it will not update itself if the elements are added dynamically, and the events are only attached when the document is ready($(document).ready(function() { do stuff });). In order to attach events to dynamically added elements, we need the .on() method.
Take for example the following html:
<div class="wrapper">
<span class="dynamically_added">stuff</span>
</div>
In order to attach an event listener to the dynamically added span, in your jquery, add the following:
$(".wrapper").on('click', '.dynamically_added', function() {
console.log('executed');
});
The first parameter of .on() is(are) the event(s). You can attach multiple events by delimiting them with spaces: .on('click hover'). The second parameter is either the function to execute, or the targeted element. In the case of the above example it is the span. The last parameter is of course the function to execute. As far as I am aware, you need to have an anonymous function to refer to the function to execute, instead of simply writing it there.
I hope this has helped.
$('#but') returns a jQuery object, not a DOM object. You can either call jQuery methods on that or you can get the DOM object out of it, but you can't use DOM methods directly on it. If you want the DOM object out of it, you can get it with:
$('#but')[0]
And, your method would be this:
function init() {
var but = $('#but')[0];
but.addEventListener("mouseover", butResult, false);
but.addEventListener("mouseout", reverse, false);
var button = $('#button')[0];
button.addEventListener("mouseover", buttonResult, false);
button.addEventListener("mouseout", reverse, false);
}
Or, instead of using native DOM methods, you can use jQuery methods on the jQuery object.
function init() {
$('#but').on("mouseover", butResult).on("mouseout", reverse);
$('#button').on("mouseover", buttonResult).on("mouseout", reverse);
}
Not sure if I understand you ? completely, but, is this what you're roughly looking for:
var b1 = document.getElementById('button');
var b2 = $(b1);
b2.click( function(){
alert('hi');
})
Wondered if there was good way to do this, thought I would post to the SO community...
There is a 3rd party web page that I have no control over how it renders, but they allow me to add JQuery.
Using the JQuery, I am creating a nav menu on the side of the page, it will be a list of links. The onclick event of these links I get from existing onclick events already on the page, but when I do a:
var linkLoc = $('#theLink').attr("onclick");
linkLoc returns:
function onclick(event) {
handleJumpTo("com.webridge.entity.Entity[OID[E471CB74A9857542804C7AC56B1F41FB]]", "smartform");
}
instead of what I would expect:
handleJumpTo("com.webridge.entity.Entity[OID[E471CB74A9857542804C7AC56B1F41FB]]", smartform");
I think JQuery is trying to get the event for binding, but I need the actual Javascript markup since I'm creating the HTML dynamically. I guess I could substring the "function onclick(event) {" out, but seems kind of hacky.
Any ideas of an elegant way I could get the onclick markup?
$("#theLink") would return a jQuery object whereas $("#theLink")[0] would give a DOM object. This is a resson that $("#thelink")[0].getAttributeNode('onclick').value would work.
The type of $('#theLink').attr("onclick") is a function, so you can just use that when you bind events to the links.
var linkLoc = $('#theLink').attr("onclick");
$('a#link1').live('click', linkLoc);
Example: http://jsfiddle.net/BdU6f/
You can also run other code in the click handler too, if you need:
var linkLoc = $('#theLink').attr("onclick");
$('a#link1').live('click', function(e){
// Code...
linkLoc(e);
});
Example: http://jsfiddle.net/BdU6f/1/
The "onfoo" attributes have values that are functions, not strings. The semantics of:
<whatever onclick='code code code'>
are that the browser constructs a function object as if you had code that did this:
document.getElementById('whatever').onclick = new Function("event", "code code code");
Thus you don't really need the raw string, since you've got something better: the function itself, ready to be called. You can then bind it as a handler to other elements via JavaScript code, not HTML (which is really a better way to do things anyway). You're using jQuery, you say, so you can use the jQuery ".bind()" API to bind those functions to whatever elements you need.
You should also be aware that there are other ways of binding event handlers to elements, ways that will leave the "onfoo" attributes completely unset.
If I understand where you're going with this, you should be able to assign the returned onclick function straight through to the onclick of your new nav element...
$('#NewNavElement').click($('#theLink').attr('onclick'));
If you need to add additional code to the handler, you can just bind another click handler.
try this;
$('#theLink').getAttributeNode('onclick').value
Revised as per comment:
$('#theLink').get().getAttributeNode('onclick').value
I have web layout, which can contains several links on it. Those links are dynamically created, using AJAX functions. And it works ok.
But, I don't know how can I work with those "dynamically created links" (ie. how to call some JS or jQuery function if I click on them). I guess that browser can not recognize them, since there are created after page is loaded.
Is there some function, that can "re-render" my page and elements on it?
Tnx in adv on your help!
You can use the 2 following methods jQuery provides:
The first one, is the .live() method, and the other is the .delegate() method.
The usage of the first one is very simple:
$(document).ready(function() {
$("#dynamicElement").live("click", function() {
//do something
});
}
As you can see, the first argument is the event you want to bind, and the second is a function which handles the event. The way this works is not exactly like a "re-rendering". The common way to do this ( $("#dynamicElement").click(...) or $("#dynamicElement").bind("click", ...) ) works by attaching the event handler of a determinate event to the DOM Element when the DOM has properly loaded ($(document).ready(...) ). Now, obviously, this won't work with dynamically generated elements, because they're not present when the DOM first loads.
The way .live() works is, instead of attaching the vent handler to the DOM Element itself, it attaches it with the document element, taking advantage of the bubbling-up property of JS & DOM (When you click the dynamically generated element and no event handler is attached, it keeps looking to the top until it finds one).
Sounds pretty neat, right? But there's a little technical issue with this method, as I said, it attaches the event handler to the top of the DOM, so when you click the element, your browser has to transverse all over the DOM tree, until it finds the proper event handler. Process which is very inefficient, by the way. And here's where appears the .delegate() method.
Let's assume the following HTML estructure:
<html>
<head>
...
</head>
<body>
<div id="links-container">
<!-- Here's where the dynamically generated content will be -->
</div>
</body>
</html>
So, with the .delegate() method, instead of binding the event handler to the top of the DOM, you just could attach it to a parent DOM Element. A DOM Element you're sure it's going to be somewhere up of the dynamically generated content in the DOM Tree. The closer to them, the better this will work. So, this should do the magic:
$(document).ready(function() {
$("#links-container").delegate("#dynamicElement", "click", function() {
//do something
});
}
This was kind of a long answer, but I like to explain the theory behind it haha.
EDIT: You should correct your markup, it's invalid because: 1) The anchors does not allow the use of a value attribute, and 2) You can't have 2 or more tags with the same ID. Try this:
<a class="removeLineItem" id="delete-1">Delete</a>
<a class="removeLineItem" id="delete-2">Delete</a>
<a class="removeLineItem" id="delete-3">Delete</a>
And to determine which one of the anchors was clicked
$(document).ready(function() {
$("#links-container").delegate(".removeLineItem", "click", function() {
var anchorClicked = $(this).attr("id"),
valueClicked = anchorClicked.split("-")[1];
});
}
With that code, you will have stored in the anchorClicked variable the id of the link clicked, and in the valueClicked the number associated to the anchor.
In your page initialization code, you can set up handlers like this:
$(function() {
$('#myForm input.needsHandler').live('click', function(ev) {
// .. handle the click event
});
});
You just need to be able to identify the input elements by class or something.
How are these links dynamically created? You can use use the correct selector, given that they are using the same class name or resides in the same tag, etc.
consider the html form
<form>
<input type="text" id="id" name="id"/>
<input type="button" id="check" name="check value="check"/>
</form>
jquery script
$('#check).click(function() {
if($('#id).val() == '') {
alert('load the data!!!!);
}
});
here on clicking the button the script check the value of the textbox id to be null. if its null it will return an alert message....
i thin this is the solution you are looking for.....
have a nice day..
Noramlly , the browser process response HTML and add it to DOM tree , but sometimes , current defined events just not work , simply reinitialize the event when u call the ajax request ..
All you need to do to work with dynamically created elements is create identifiers you can locate them with. Try the following code in console of Firebug or the developer tools for Chrome or IE.
$(".everyonelovesstackoverflow").html('<a id="l1" href="http://www.google.com">google</a> <a id="l2" href="http://www.yahoo.com">yahoo</a>');
$("#l1").click(function(){alert("google");});
$("#l2").click(function(){alert("yahoo");});
You should now have two links where the ad normally is that were dynamically created, and than had an onclick handler added to bring up an alert (I didn't block default behaviour, so it will cause you to leave the page.)
jQuery's .live will allow you to automatically add handlers to newly created element.
If your links are coming in via AJAX, you can set the onclick attributes on the server. Just output the links into the AJAX like this:
Holy crap I'm a link
The return false makes sure the link doesn't reload the page.
Hope this helps!