The following chain works:
$("</p>").html('message').hide().appendTo("#chat").fadeIn()
.parent().scrollTop($('#chat')[0].scrollHeight);
But this doesn't:
$("</p>").html('message').hide().appendTo("#chat").fadeIn()
.parent().scrollTop($(this)[0].scrollHeight);
this.scrollHeight doesn't work too.
How can i get current object reference in jquery chain?
You only get access to the current object inside of a callback. There's no way you can get access to the current object in your chain.
Try this:
var $parent = $("</p>").html('message').hide().appendTo("#chat").fadeIn().parent();
$parent.scrollTop($parent[0].scrollHeight);
If you really don't want to break out of you chain, you can re-select:
$("</p>").html('message').hide().appendTo("#chat").fadeIn()
.parent().scrollTop($("#chat")[0].scrollHeight);
But I'd strongly advise you against it. There's no need to select the same DOM element twice.
In your second code snippet this doesn't point to #chat that's why it doesn't work. this mostly points to the calling function instance or the object which triggered any event.
You can try something like this
var $p = $("</p>").html('message').hide().appendTo("#chat");
$p.fadeIn().parent().scrollTop($p[0].scrollHeight);
Well, it's obvious. The #chat element is a static element and you are dynamically appending paragraphs to it. Therefore, you want to get a reference to that element beforehand (for instance, on page initialization):
var chat = $( '#chat' )[0];
Now, you do this:
$( '<p />' ).html( 'message' ).hide().appendTo( chat ).fadeIn();
$( chat ).scrollTop( chat.scrollHeight );
So, the idea is to retrieve references to the main static elements (chat-box, toolbar, panel, navigation, etc.) on page initialization, and then use those references all over your application code.
Related
I need the id(and other attributes such as value) of a span i previously created on an ajax event.
Is there a way to do this?
This is how the span is created on php post:
echo "<span class='non-skin-symptom-choice disease_option' ".
"onclick='showinfo(".$var[0].");' id=".$var[0].">"
.$var[1]." -- ".number_format($var[3]*100, 2, '.', '')."%</span>";
and I want to get its id whenever a checkbox is clicked.
$(".chb").click(function(){
var id= $(this).attr('id');
var list=[];
$('.disease_option').each(function (){
alert("this.val=="+ $(this).attr("val")); //i need the value here
var str= $(this).attr("value").split(" -- ")[1];
alert(str);
str=str.slice(0,str.length - 1);
if(parseFloat(str) >=support)
list.push(id) //i need the id here
});
the checkbox is not dynamically created, so $(".chb").click(function(){} works.
somehow, $(this).attr("id") works but $(this).attr("val") returns undefined... i also tried $(this).attr("value") but same results. $(this).val returns empty.
use
$(document).on('click','.chb',function(){
var id = $(".non-skin-symptom-choice").attr("id");
})
as this have a high level event attachment and it can get the elements who have been created on a runtime
Try this
alert($(".non-skin-symptom-choice").attr("id"));
The click() binding you're using is called a "direct" binding which will only attach the handler to elements that already exist. It won't get bound to elements created in the future. To do that, you'll have create a "delegated" binding by using on()
$(document).on('click','.chb',function(){
var id = $(".non-skin-symptom-choice").attr("id");
})
possible duplicate: Click event doesn't work on dynamically generated elements
If your DOM node did not exist when the page loaded (ie. it was added to the page via AJAX after the page loaded), jQuery cannot see it if you try to update it or read it with jQuery methods. One way to overcome this is to set up your jQuery function to reference the class or ID of the parent of the node you want to target (assuming the parent class is loaded into the page on page load), along with the class of the node you want to target. For example:
$(".chb").click(function(){
var id = $(".your-parent-class .non-skin-symptom-choice").attr("id");
}
}
I am creating a variable that stores an elements ID in the variable. I could write it like this:
var webappData = document.getElementById('web-app-data');
If I wanted to do the same using jQuery I think I would write it like this:
var webappData = $('#web-app-data');
However, when I try that it doesn't work. (Script throws an error because the variable isn't selecting the div with that Id.)
How would I use jQuery to select an element and store it in a variable?
document.getElementById('web-app-data') isn't the same as $('#web-app-data'). The later returns jQuery object, which is kind of an array of HTMLElement objects (only one in your case).
If you want to get HTMLElement, use $('#web-app-data')[0]. Check:
document.getElementById('web-app-data') === $('#web-app-data')[0]; // true
It's ok.. Maybe something else is wrong in your code..
Example:
<div id="web-app-data">
Hello
</div>
<script type='text/javascript'>
var webappData = $('#web-app-data');
alert(webappData.text()); // Hello
</script>
Fiddle
Above code should work just fine. Your problem might be, that jQuery doesn't find any corresponding elements from the DOM since the element has been removed or hasn't been loaded there yet. If you try to
console.log($('#web-app-data'));
that variable, you can check if jQuery actually found anything. jQuery object should have lenght of (atleast) one if corrensponding element is indeed in DOM atm.
That will work and you use just like it was the full JQuery selector.
var elm = $('#webappData');
if (elm.hasClass('someClass')) elm.removeClass('someClass');
return;
Var divs = $(".txt"); this will return a list of divs with a class txt .
I want to add text to a selected div for example :
divs[4].html("Hello World"); this with return error saying divs[4].html is not a function. why ?
When you access a jQuery object by its DOM array index, you get the HTML element, not a jQuery object, which doesn't have the html() function. Use the eq(n) selector instead:
$(".txt:eq(4)").html("Hello World");
The divs[0] is giving you a DOM reference, not a jQuery object. So, pass that to the jQuery function ($() is shorthand for jQuery()):
$(document).ready(function(){
var divs = $('.txt');
$(divs[4]).html('this one');
});
http://jsfiddle.net/userdude/unu8g/
Note as well the use of $(document).ready(), which will wait until the DOM is accessible. $(window).load() will suffice for this as well, although it may fire after onDOMReady.
The non jQuery way:
document.getElementsByClassName("txt")[4].innerHTML = "banananana!";
Just a side note: I'd suggest learning basic browser javascript before moving to libraries.
It will give you an understanding of how such libraries work and will keep you from being 'locked in' to a specific few
I want to be able to link a javascript object with a dom element but cant find a way for this to be done properly. An example: say when opening a page with an inventory it loads all the items contained in it and when I hover over the images inside it creates a small tooltip with some information. Well there will be much of these items on the page and i want to be able to link the DOM element with an object so i can access its properties easily. I hope im explaining my self properly.
say I had this inside an inventory:
<div id="slot1"><img id="item1"></div>
<div id="slot2"><img id="item2"></div>
and say i have a javascript object called slot1 and slot2:
the object slot1 has all the properties that need to be shown in the tooltip so i would like to do something like this in the mouseover event:
this.showTooltip()
any help would be great ty if i need to explain it better just say!
-Thaiscorpion
Use jQuery data:
$("div.hasToolTip").hover(
function() {
//Get the associated data with the DOM element
//with $(this).data(someKey)
showToolTip($(this).data('toolTipInformation'));
},
function() {
//Here you can hide all tooltips
}
);
Obviously, before you can register this event, you have to assign the object to every DOM element with $(selector).data(key, value).
These example expects that every DOM element which should have a tooltip has a class named .hasToolTip.
Look at the jQuery documentation for more information about the .data() function.
Just have the javascript object know the ID of the object it's watching.
function Tooltipper(divID) {
this.id = divID;
}
Tooltipper.prototype.showTooltip = function () {
// do tooltip stuff
$('#' + this.id).tooltip(); // assuming that it has a tooltip thing
};
var slot1 = new Tooltipper('slot1'),
slot2 = new Tooltipper('slot2');
And then:
slot1.showTooltip();
Or better yet, instead of passing in the ID, pass in the object:
var slot1 = new Tooltipper($('#slot1'));
This way you don't have to do a DOM lookup each time.
I am not very sure with the use of "this" [current context] in jquery.What I know is- it prevents the dom from searching all the elements, it just work on that current element, which improve performance[correct me if I am wrong].Also I am not sure when to use this and when not.
lets say, should I go for
$("span",this).slice(5).css("display", "none")
or
$("span").slice(5).css("display", "none")
both will work, but I am not very clear as how really it works.can somebody explain it with a diff/proper example, and when to use what?
[EDIT]
$(function() {
$("#clickme").click(function() {
$("span",this).slice(5).css('display', 'block');//doesn't work ? why?
$("span").slice(5).css('display', 'block');//works..why?
});
});
enter code here <span id="clickme">Click me</span>
<span>itam1</sapn>
<span>itam2</sapn>
<span>itam3</sapn>
<span>itam4</sapn>
<span>itam5</sapn>
...upto10
Usually you can use the this keyword on event handlers since it will be a reference to the element that triggered the event and other jQuery functions like $.each.
For example when handling a click event lets say:
$('.parentElement').click(function () {
$('.foo', this).hide();
});
The above code, will hide all the elements with class foo that are descendants of the currently parentElement that was clicked.
The use of the context argument of the jQuery function is the equivalent of making a call to the find method:
$(expr, context);
// is just equivalent to:
$(content).find(expr);
EDIT: Looking at your example:
$("#clickme").click(function() {
$("span",this);//... (1)
$("span");//.. (2)
});
The first line, will look for all the span elements that are inside of #clickme (its descendants), since that element was the one that triggered the click event.
The second line, will look for all the span elements on the whole page.
How it works
Lets use this HTML for the examples:
<div id="container">
<div class="column">Link 1</div>
<div class="column">Link 2</div>
</div>
<div id="footer">
Link 3Link 3
</div>
The scoping parameter of the jQuery function should only be used if you already have a cached reference to a DOM element or jQuery wrapped element set:
var $set = $('#container');
$('a', $set).hide(); // Hides all 'a' tag descendants of #container
Or in an event:
$("#container").click(function(e){
$('a', this).hide(); // Same as call above
}
But it makes no sense to use it like this:
$('a', '#container').hide()
When it should be written like this:
$('#container a').hide();
Having said all that, it is generally cleaner and clearer to just use .find() instead of using the second parameter in the jQuery function if you already have the jQuery or DOM element. The first example I gave would be written this way instead:
var $set = $('#container');
$set.find('a').hide(); // Hides all 'a' tag descendants of #container
If this one call was the only reason you grabbed the #container object, you could also write it this way since it will still scope the search to the #container element:
$("#container a").hide(); // This is the same as $('a', "#container");
Why would you scope your selections
When jQuery looks for an unscoped selector, it will search through the entire document. Depending on the complexity of the selector, this could require a lot of searching. If you know that the element you are looking for only occurs within a specific parent, it will really speed up your code to scope the selection to that parent.
Regardless of what method of scoping you choose, you should always scope your selectors whenever possible.