I have this line of JavaScript / jQuery that I'm attempting to use to append an element to the DOM and then attach an eventlistener to.
$('.faq_answer').prev().append(finalRender.cloneNode(true)).addEventListener("click", function () {toggle(this)}, false);
I know the appending part works perfectly but adding an event listener is giving me grief.
Is it possible / advisable to use jQuery and normal JavaScript together like this?
Or is there something in jQuery that would work better. (Very new to jQuery so bear with me).
If you want to use the native methods, then you need to call them against DOM elements, not jQuery objects
var clone = finalRender.cloneNode(true);
clone.addEventListener("click", function () {toggle(this)}, false);
$('.faq_answer')
.prev()
.append( clone );
If you want to use jQuery, then you need to wrap the DOM elements in a jQuery object.
// Drop your DOM element----v----into a jQuery object
var clone = $( finalRender.cloneNode(true) ).bind("click", function (){
toggle(this);
});
$('.faq_answer')
.prev()
.append( clone );
You could do something like this:
$('.faq_answer').prev().append(finalRender.cloneNode(true)).click(function () {toggle(this)});
which is pure jquery
I think you're wanting to add your event Listener to the cloned Node - not to the prev() of .faq_answer.
If you're importing jQuery, why not use the .click() method anyway instead of mixing? It's simpler! :)
$('.faq_answer').prev().append(finalRender.cloneNode(true).click(function(){
toggle(this)
}));
Yes, it's possible to use them "together" because jQuery is JavaScript. However in this case there's really no reason to bind event handlers directly like that if you are using the library. It already knows how to manage event handlers, and doing it outside of its control is probably not a good idea unless you really know what you're doing.
I find questions like this are strange, because jQuery is JavaScript.
Based on this mixing up the code that is just plain JavaScript with jQuery code is fine.
But if there is a simpler way of doing what you want in jQuery then I would say to just use jQuery alone.
Related
I have been searching this on internet, I have found some answers which were helpful like but they were not enough to solve my problem (e.g.
Similar Problem but no solution provided for my problem)
I am using JRate plugin, I am adding a div inside a div using jQuery. The problem is that when I add it using jQuery and use the JRate Functions then they are not working. But they are working without appending a new div.
I know how to make it work. I will have to use $(document) but I dont know how to use it with this code.
Here is HTML
<div class="jRate"></div>
Here is my Jquery
$(".jRate").jRate({
onSet: function(rating) {
alert(rating);
}
});
Here is my appending code
var divjRate = "<div class='jRate'></div>";
$(divjRate).appendTo('.fb-jRate');
Can any one tell me how can I use $(document) here or any other alternative solution you have.
You need to append the html element first so that it is registered in the DOM. Then, you can call jRate on it
var divjRate = "<div><div class='jRate'></div></div>";
// Append new element to container of choice
$(divjRate).appendTo('.fb-jRate');
// Use plugin on new element
$('.jRate').jRate({
onSet: function(rating) {
alert(rating);
}
});
The solution you have linked applies to binding event listeners, which is not the case with a typical jQuery plugin that usually involves DOM replacement and other things.
You will need to apply the method to newly added DOM elements. The DOM mutation event specification is deprecated due to performance issues, and it is not realistic to expect the browser to keep track of all changes (and what kind of changes) happening in the DOM.
For example, if you're adding new content with an AJAX call, you can apply the method to newly added content within the jqXHR.done() function.
Update: OP provided with some code, so I have adding a way to initialize the plugin for newly added DOM element:
// Declare new element
var divjRate = "<div><div class='jRate'></div></div>";
// Use plugin on new element
$(divjRate).find('.jRate').jRate({
onSet: function(rating) {
alert(rating);
}
});
// Append new element to container of choice
$(divjRate).appendTo('.fb-jRate');
I have the following set in my JS:
$('.selector').selectpicker();
When new DOM elements are added to the page, the above method doesn't work on the new DOM elements. I know that, in other cases, I can do the following such that newly added DOM elements work:
$(document).on("click", ".class-here", function() {
});
But how can a method like the first changed to work with new DOM elements (rather than calling that same method again)?
The answer will depend on the function you're calling (here selectpicker).
If you're talking about the bootstrap function, you would do:
$('.selector').selectpicker("refresh");
After having changed the DOM.
You might use the level 3 event for DOM node creation, like .on("DOMNodeInserted",(selector),(function)) to execute your function whenever an element fitting the selector is inserted. See How to catch creation of DOM elements and manipulate them with jQuery
Your problem is regarding binding new element in DOM, Prior version of jquery use bind and unbind method for new element in dom.
But If you use jQuery 1.3+ then you can write
$('selector').live('event',function (){ //do some action });
In above jquery, You didn't need to bind/unbind element on DOM.
But latest version of jQuery 1.7+, You can directly use .on() method which you mentioned above, It mean that you didn't care to bind, unbind on 'DOM change'.
On() is simple that you can write common callback for multiple events on particular selector.
I hope that this details is useful to you and you got your answer. If you use 'on()' then you not need to bind element in DOM.
I am just debugging jQuery in FireBug and wonderig about the return value of
$('.a-selector').attr('onclick');
It turns out to be an onclick(event), but I have read some code before and the author just uses it like this:
$('.a-selector').attr('onclick').replace(..., ...);
which means it can be treated as a String Object. But it reports an error when I use like this.
My jQuery version is 1.5.2. So I wonder when the jQuery changes the API and what is the best way to change the onclick event defined in the HTML.
When jQuery .attr('onclick') function return a event object?
In jQuery < 1.6. That's because prior to 1.6, .attr() did a mix between retrieving properties and attributes where it saw fit, newer versions removed that layer of witchery and now have proper methods for retrieving attributes (.attr) and properties (.prop).
Here's a fiddle demonstrating the above.
ps. BTW, it doesn't return an event object, but rather a function object that serves as event handler. =]
Also, 2 side notes: You should always upgrade your jquery to the latest version when viable (currently 1.8.3), it comes with more features, better performance and lots of bug fixes.
And you shouldn't really be using onclicks when you have jQuery, that goes against the Web 2.0 standards of separation of structure (html) and behavior (js) - jQuery itself provides cross-browser handler attaching with the methods .on() (for jQuery 1.7+), and .bind/.delegate/.live for older versions.
I assume that you want to change the value of your onclick attribute of some element.
$('.a-selector').attr('onclick',''); // leave 2nd parameter blank if you want to remove its value
OR
$('.a-selector').attr('onclick','myfunc()');
############################### Edit
You can define your function as below :
<script>
function myfunc(){
// Do stuff here
}
</script>
is it a possibility for you to reset the click event?
$('.a-selector').unbind('click').click(function() {
// new function
});
to replace text in an javascript-code is normally not that what javascript should do. I think there is a much better solution possible.
Whenever I want to find if an element exist in the DOM I use the following code.
if($('#target').length){
// do stuff.
}
This works well and I use it quite a lot on client sites.
Question:
How fast is this method? What are the speed implications when this is used a lot in a project?
You would be much better off using if(document.getElementById('target')) instead. JavaScript is always faster than jQuery (since jQuery is just a bunch of JavaScript hidden under the carpet)
EDIT: If you use it a lot, you can make a custom function:
function idExists(id) {return !!document.getElementById(id);}
Native JS is always faster than a query through jQuery. It just may not be as friendly.
After running a query through jsperf.com, native (querySelectorAll) is 57% faster than jQuery
However, if you use id, jQuery will be faster than querySelectorAll. In any case of id, use document.getElementById to test for an elements existence.
http://jsperf.com/jquery-obj-length
Try searching a DOM element with JQuery context say:
if an element u search say, an Input control, lies with in a table, pass table as your context:
A simple example:
$(function(){
var name= $('#Name','#mytab').val();
alert(name);
});
the jquery engine find the element 'Name' with in 'mytab' and not the entire form
follow this fiddle link : http://jsfiddle.net/NzbJr/10/
I've just started using jQuery, but am a bit stuck. I am building a table dynamically in Javascript and am adding classes all the time to cells (for styling), so I would like to use the addClass function:
var row = table.insertRow(-1);
var cell = row.insertCell(0);
cell.addClass('boldRow');
but this does not work. I know you can use the magic $('') function to be able to use jQuery, but can I use it on 'native' HTMLElement references?
$(cell).addClass should do the trick - why don't you try it and let us know.
In any case you have to use the $() to load the jQuery framework to get access to addClass.
You just place the element in like you would a string.
$(someElementReference).addClass('boldrow');
You can also pass in a collection of elements if that is what you have.
Here's an example: http://jsfiddle.net/qS473/
Yes, you can pass in native DOM objects into the jQuery function, and it will create a jQuery object from the DOM object:
$(cell).addClass('boldRow');
But you don't need jQuery to add a CSS class to a DOM object!:
cell.class += ' boldRow';
Yes, you can select all HTML elements with $() for example, $('body'), or $('html') etc. Since it's only a framework, you can also use any other Javascript you can think of to fix this.
Usually the first thing I do when creating a new element is something like this:
var newDivJQObject = $(document.createElement('div'))
.attr('id', '[uniqueID]')
.addClass('[className]');