In jquery I've appended a <li> element to an unordered list.
How do I focus on the newly created <li> ?
If I do the following:
$("ul").append('<li><input type="text" value="Hi!"></li>');
$("li:last").focus(); //doesn't work because new <li> isn't in dom yet
the focus doesn't work, as noted above.
I know jquery 1.4.2 has a live() event handler which allows you load event handlers to dynamically added elements, but I'm not sure what I'm doing wrong:
$(document).ready(function () {
$('li').live('load', function () {
alert("hi!");
$("li:last").focus();
});
});
You can only set the focus to elements which can hold the focus. By default a list item cannot. This is why your first example fails, not because it isn't in the DOM (it is in the DOM, that is what append does)
In general you should use elements designed to hold the focus (i.e. set the focus on the input not the list item). You can also (but this is less backwards compatible and less logical) use HTML5's tabindex (probably setting it to 0).
onload will not work because list items do not load external content.
You can try this, $(YourElement).trigger("focus").
This is an old post I know, but a simple way to solve this issue is to create a text input in your HTML and set its CSS to "display: none;". On the LI's click event, set the focus in this input and listen to its keypress events.
I've done it and it works like a charm.
Related
For each checkbox on the web page, I replace it with a slider that I borrowed from jsfiddle.net/gnQUe/170/
This is done by going through the elements when the document is loaded.
Now the problem is that when more content is loaded via ajax, the new checkboxes are not transformed.
To solve the problem, I used AjaxComplete event to go through all the elements again and replace the checkboxes with sliders.
Now the problem happens that elements that were already replaced, get two sliders. To avoid that I check if the checkbox is hidden and next element is div of class "slider-frame", then don't process the re-process the element.
But I have a lot of other such controls as well, and I am presume I am not the only one that has this problem. Is there another easy way around it?
There exists jQuery live/on( http://api.jquery.com/on/ ) event but it requires an event as an argument? whereas I would like to change the look of my controls when they are rendered.
Another example of the same problem is to extend some controls that are loaded via ajax with jQuerys autocomplete plugin.
Is there a better way to accomplish this other than changing some attributes on the element.
To summarize, on document load I would like to process every element in DOM, but when more elements are loaded via ajax then I want to change only the new elements.
I would assume that when the element's are transformed into a slider, a class is added to them. So just add a not clause.
$(".MySelector").not(".SomeClassThatSliderAddsToElement").slider({});
So in the case of your code do something like this
$('.slider-button').not(".sliderloaded").addClass("sliderloaded").toggle(function(){
$(this).addClass('on').html('YES');
$('#slider').val(true);
},function(){
$(this).removeClass('on').html('NO');
$('#slider').val(false);
});
Since you said you do not want to add anything else, how about you change the toggle function to click.
$(document).on("click", ".slider-button", function(){
var elem = $(this);
elem.toggleClass("on");
var state = elem.hasClass("on");
elem.text(state?"YES":"NO");
elem.parent().next().val(state);
});
Running fiddle: http://jsfiddle.net/d9uFs/
I have a problem, in my page, I have a div that contains lets say two hidden fields with the value 0 and 2. I have a button that trigger an ajax query and change the div contents with the same hidden fields but with the value 1 and 2 respectively. The problem is that it seems like my javascript (using JQuery) is not aware of theses changes. When I inspect my page to see the html source code I see the values have changed but in the script when I'm doing:
$("#btn").click(function() {
alert($("#hidden1").val());
alert($("#hidden2").val());
});
It still show me the old value (0 and 2) like if the DOM hasn't been updated. Can someone help me please or tell me if it is normal and how to fix it.
Thanks for your time
Me!
Try this:
$("#btn").on('click', function() {
alert($("#hidden1").val());
alert($("#hidden2").val());
});
It's not that the DOM is not being updated, it's probably because your jQuery event is bound to the particular element at the time .click() is called. Since the DOM changed(you likely removed and added a new element of the same id), the function returns the values of the elements you discarded(because it remains bound to it even if removed from DOM).
Use the live() method or on() as a replacement for your click() handler. This method provided by jQuery will not bind to a particular DOM element at the time it is called, but does a dynamic lookup every time a click is detected.
I want this webpage to highlight certain elements when you click on one of them, but if you click anywhere else on the page, then all of these elements should no longer be highlighted.
I accomplished this task by the following, and it works just fine except for one thing (described below):
$(document).click(function() {
// Do stuff when clicking anywhere but on elements of class suggestion_box
$(".suggestion_box").css('background-color', '#FFFFFF');
});
$(".suggestion_box").click(function() {
// means you clicked on an object belonging to class suggestion_box
return false;
});
// the code for handling onclicks for each element
function clickSuggestion() {
// remove all highlighting
$(".suggestion_box").css('background-color', '#FFFFFF');
// then highlight only a specific item
$("div[name=" + arguments[0] + "]").css('background-color', '#CCFFCC');
}
This way of enforcing the highlighting of elements works fine until I add more html to the page without having a new page load. This is done by .append() and .prepend()
What I suspected from debugging was that the page is not "aware" of the new elements that were added to the page dynamically. Despite the new, dynamically added elements having the appropriate class names/IDs/names/onclicks ect, they never get highlighted like the rest of the elements (which continue to work fine the entire time).
I was wondering if a possible reason for why my approach does not work for the dynamically added content is that the page is not able to recognize the elements that were not present during the pageload. And if this is a possibility, then is there a way to reconcile this without a pageload?
If this line of reasoning is wrong, then the code I have above is probably not enough to show what's wrong with my webpage. But I'm really just interested in whether or not this line of thought is a possibility.
Use .live to "Attach a handler to the event for all elements which match the current selector, now and in the future". Example:
$(".suggestion_box").live("click", function() {
// means you clicked on an object belonging to className
return false;
});
Also see .delegate, which is similar.
Since the .live() method handles events once they have propagated to the top of the document, it is not possible to stop propagation of live events. Similarly, events handled by .delegate() will always propagate to the element to which they are delegated; event handlers on any elements below it will already have been executed by the time the delegated event handler is called.
from the jQuery documentation =)
(only to explain better why #karim79 also suggested the delegate method ;P )
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!
I'm looking to determine which element had the last focus in a series of inputs, that are added dynamically by the user. This code can only get the inputs that are available on page load:
$('input.item').focus(function(){
$(this).siblings('ul').slideDown();
});
And this code sees all elements that have ever had focus:
$('input.item').live('focus', function(){
$(this).siblings('ul').slideDown();
});
The HTML structure is this:
<ul>
<li><input class="item" name="goals[]">
<ul>
<li>long list here</li>
<li>long list here</li>
<li>long list here</li>
</ul></li>
</ul>
Add another
On page load, a single input loads. Then with each add another, a new copy of the top unordered list's contents are made and appended, and the new input gets focus. When each gets focus, I'd like to show the list beneath it. But I don't seem to be able to "watch for the most recently focused element, which exists now or in the future."
To clarify: I'm not looking for the last occurrence of an element in the DOM tree. I'm looking to find the element that currently has focus, even if said element is not present upon original page load.
this image http://droplr.com/174l8H+
So in the above image, if I were to focus on the second element, the list of words should appear under the second element. My focus is currently on the last element, so the words are displayed there.
Do I have some sort of fundamental assumption wrong?
document.activeElement is what you want. It's part of HTML5 and supported by all modern browsers, including IE.
According to the documentation (see 'caveats'), .live() in jQuery 1.4.1 supports focus, mapping to focusin. I'd suggest creating an element in common scope to hold the last focused element. Perhaps like so:
var lastFocused;
$('input.item').live('focusin', function(){
lastFocused = $(this);
});
How to determine which html page element has focus?
Has your answer (using document.activeElement gets you there for many browsers, but to make the ones that don't support it work you'll want to add the Javascript from that question's answer).
In the end, it was an error in code elsewhere that was confusing the DOM about who had focus.
The line was this: $('#item-add').find('input.item').focus();
And it needed to be this: $('#item-add:last').find('input.item').focus();
Because the added item is always last in the list.
Much has been learned, and I've tried to start and upvote accordingly. Particularly of note to the question at large:
.live events are not cumulative. Only code cruft is.
Set a variable outside of your function and update it within your function so you can access it in other functions as well.
jsfiddle.net and jsbin.com are awesome.
Holy HTML5, document.activeElement is good to know.
Thanks so much, SO, for all your help on this issue.
You can use the :last selector to only handle the event on the last <input> in the document (last at the time that the event was fired)
$('input.item:last').live('focus', function(){
$(this).siblings('ul').slideDown();
});