Using HammerJS with jQuery - javascript

Below I grab the container and on swipe left and right I trigger a click which is another function to do some fancy animation jazz.
var element = document.getElementsByClassName('container');
var hammertime = new Hammer(element);
hammertime.on('swiperight', function(ev) {
$('.btn-left').trigger('click');
});
hammertime.on('swipeleft', function(ev) {
$('.btn-right').trigger('click');
});
I keep getting this error about my Hammerjs library i've included (http://hammerjs.github.io/dist/hammer.min.js) Uncaught TypeError: a.addEventListener is not a function.
I did some research and found another stackoverflow question that says I can't pass jQuery through Hammerjs thus I should use jQuery Hammer. I took a look at the repo and it's not been updated in nearly two years.
Do I need to use the jQuery Hammer (https://github.com/hammerjs/jquery.hammer.js) extension, or can I pass through jQuery without needing it.

The problem is that new Hammer() is expecting a single element, and getElementsByClassName is returning a NodeList.
If you change it to
var hammertime = new Hammer(element[0])
that should work as expected, since you'll be passing the first element that matches .container. If you want to bind it to all elements that have the .container class, you'll need to loop through them on your own. I rarely use jQuery for anything, so I usually include this little helper function for looping through NodeLists
function doToAll(elems, fn){
var len = elems.length
while(--len > -1){
fn(elems[len])
}
}
In this case, you'd use it like this:
doToAll(document.getElementsByClassName('container'), function(element){
var hammertime = new Hammer(element)
//add in the rest of your functionality
})

Related

jQuery selector - select new elements too after append/load within variable

I have:
$elements = $('.elements');
$element = $('.element');
function appendText(element){
element.append('<em> appended text</em>');
}
appendText($element);
$('button').on('click', function(){
$elements.append('<span class="element">Span Element Appended after load</span>');
appendText($element);
});
The appendText function, after button click, appends only to the initial element and that is due to JS cache I presume.
I know that I can do appendText($('element')); and the problem will be solved, but I don't want to change all my code now.
Is there any way to make jQuery consider this $element variable as not a cached element and look into the full DOM each time I call that variable?
Please find the jsfiddle if you wish to play or understand better: http://jsfiddle.net/adyz/733Xd/
If you add this:
$element = $('.element:last-child')
before
appendText($element);
I think will solve your problem
jsFindle here: http://jsfiddle.net/733Xd/5/.
Best regards!
That is an expensive thing to do. I would advise against it for performance reasons.
I did this pluggin in the beggining of last year https://github.com/fmsf/jQuery-obj-update
It doesn't trigger on every call, you have to request the update yourself:
$element.update();
The code is small enough to be pasted on the answer:
(function ( $ ) {
$.fn.update = function(){
var newElements = $(this.selector),i;
for(i=0;i<newElements.length;i++){
this[i] = newElements[i];
}
for(;i<this.length;i++){
this[i] = undefined;
}
this.length = newElements.length;
return this;
};
})(jQuery);
I think below one will solve your problem
appendText($element); //here you always referring to the node which was there initial.
http://jsfiddle.net/s9udJ/
Possible Solution will be
$(function(){
$elements = $('.elements');
$element = $('.element');
function appendText(element){
element.append('<em> appended text</em>');
}
appendText($element);
$('button').on('click', function(){
$elements.append('<span class="element">Span Element Appended after load</span>');
appendText($elements.find('span').last());
});
})
I don't think what you're asking is easily possible - when you call $element = $('.element'); you define a variable which equals to set of objects (well, one object). When calling appendText($element); you're operating on that object. It's not a cache - it's just how JS (and other programming languages) works.
The only solution I can see is to have a function that will update the variable, every time jquery calls one of its DOM manipulation methods, along the lines of this:
<div class='a'></div>
$(document).ready(function()
{
var element = $('.a');
$.fn.appendUpdate = function(elem)
{
// ugly because this is an object
// also - not really taking account of multiple objects that are added here
// just making an example
if ($(elem).is(this.selector))
{
this[this.length] = $(this).append(elem).get(0);
this.length++;
}
return this;
}
element.appendUpdate("<div class='a'></div>");
console.log(element);
});
Then you can use sub() to roll out your own version of append = the above. This way your variables would be up to date, and you wouldn't really need to change your code. I also need to say that I shudder about the thing I've written (please, please, don't use it).
Fiddle

jquery offset method doesn't always work / exist

Good morning and happy new year everyone!
I've run into a snag on something and need to figure out a solution or an alternative, and I don't know how to approach this. I actually hope it's something easy; meaning one of you all have dealt with this already.
The problem is that I'm doing rollovers that contain information. They're divs that get moved to the absolute location. Now I've tried this with jquery 1.6 - 1.9.1. Of course this has to work in multiple browsers.
What needs to happen is on rollover show a div, and when you rollout of that div, make it hide.
...
// .columnItem is class level and works
$(".columnItem").mouseleave(function() {
$(this).css("display", "none");
});
...
$(".column").mouseenter(function() {
var currentItem = $(this)[0]; // this is where the problem is
// hide all .columnItems
$(".columnItem").css("display", "none");
// i get this error: Object #<HTMLDivElement> has no method 'offset' (viewing in chrome console)
var offsetTop = currentItem.offset().top;
var columnInfoPanel = $("#column" + currentItem.innerText);
});
So the immediate thought of some would be don't use $(this)[0]. Instead, I should use $(this), and you are correct! Where the other problem comes into play is by removing the array index, currentItem.innerText is now undefined.
The only thing I can think of is I'll have to mix both, but it seems like there should be a way to use the selector and get both options.
What have you all done?
Thanks,
Kelly
Replace:
var currentItem = $(this)[0];
With:
var currentItem = $(this).eq(0);
This creates a new jQuery object containing only the first element, so offset will work.
Then you can use either currentItem[0].innerText or currentItem.text(), whichever you prefer.
Skip the [0] at the beginning as you are saying.
But then change the last line to:
var columnInfoPanel = $("#column" + currentItem[0].innerText);
De-referencing the jQuery selector gives you the DOM-object.
If you want to stick to pure jQuery, the .text() / .html() methods will give you the same functionality.

my first jQuery plugin, only seems to bind to the first form of eight forms on the page

I'm writing a small jQuery plugin that binds to 8 divs on a page, each of which contains a form. There are two links for each widget that increment or decrement a field within the form and then POSTs the form. The problem is that all 16 links on the page all submit the first form on the page.
The source code is here:
http://pastie.org/657045
I'm a jQuery/JS newb and figure this is probably a variable scope issue, but I've tried everything and can't get the elements to operate independently.
At the very beginning, you need to iterate through the results of the $(containerobj) and run the rest of the code through that, replacing each reference, like this:
jQuery.RankWidget = function(containerobj, options) {
return $(containerobj).each(function() {
var $container = $(this);
var $form = $container.find('.rank_buttons form');
var $rank_up = $container.find('.rank.up');
var $rank_down = $container.find('.rank.down');
var $value_field = $container.find('input.rank_value');
var $comment_score = $container.find('.comment_score');
var $comment_rank = $container.find('.comment_rank');
...
};
};
At the moment, you're applying all the events to all of the links, rather than scoping it to each container object in turn.
I solved my problem by using .click() instead of .live()
Anyone know if there is away to use .live() and get the scope for each widget correct? I even tried passing in the variable as an argument to the clickRank() function, but it was still referencing the wrong form.

JavaScript moving element in the DOM

Let's say I have three <div> elements on a page. How can I swap positions of the first and third <div>? jQuery is fine.
There's no need to use a library for such a trivial task:
var divs = document.getElementsByTagName("div"); // order: first, second, third
divs[2].parentNode.insertBefore(divs[2], divs[0]); // order: third, first, second
divs[2].parentNode.insertBefore(divs[2], divs[1]); // order: third, second, first
This takes account of the fact that getElementsByTagName returns a live NodeList that is automatically updated to reflect the order of the elements in the DOM as they are manipulated.
You could also use:
var divs = document.getElementsByTagName("div"); // order: first, second, third
divs[0].parentNode.appendChild(divs[0]); // order: second, third, first
divs[1].parentNode.insertBefore(divs[0], divs[1]); // order: third, second, first
and there are various other possible permutations, if you feel like experimenting:
divs[0].parentNode.appendChild(divs[0].parentNode.replaceChild(divs[2], divs[0]));
for example :-)
Trivial with jQuery
$('#div1').insertAfter('#div3');
$('#div3').insertBefore('#div2');
If you want to do it repeatedly, you'll need to use different selectors since the divs will retain their ids as they are moved around.
$(function() {
setInterval( function() {
$('div:first').insertAfter($('div').eq(2));
$('div').eq(1).insertBefore('div:first');
}, 3000 );
});
.before and .after
Use modern vanilla JS! Way better/cleaner than previously. No need to reference a parent.
const div1 = document.getElementById("div1");
const div2 = document.getElementById("div2");
const div3 = document.getElementById("div3");
div2.after(div1);
div2.before(div3);
All modern browsers are supported!
Browser Support
jQuery.fn.swap = function(b){
b = jQuery(b)[0];
var a = this[0];
var t = a.parentNode.insertBefore(document.createTextNode(''), a);
b.parentNode.insertBefore(a, b);
t.parentNode.insertBefore(b, t);
t.parentNode.removeChild(t);
return this;
};
and use it like this:
$('#div1').swap('#div2');
if you don't want to use jQuery you could easily adapt the function.
var swap = function () {
var divs = document.getElementsByTagName('div');
var div1 = divs[0];
var div2 = divs[1];
var div3 = divs[2];
div3.parentNode.insertBefore(div1, div3);
div1.parentNode.insertBefore(div3, div2);
};
This function may seem strange, but it heavily relies on standards in order to function properly. In fact, it may seem to function better than the jQuery version that tvanfosson posted which seems to do the swap only twice.
What standards peculiarities does it rely on?
insertBefore
Inserts the node newChild before the existing child node refChild. If
refChild is null, insert newChild at
the end of the list of children.
If newChild is a DocumentFragment object, all of its children are
inserted, in the same order, before
refChild. If the newChild is already
in the tree, it is first removed.
Jquery approach mentioned on the top will work.
You can also use JQuery and CSS .Say for e.g on Div one you have applied class1 and div2 you have applied class class2 (say for e.g each class of css provides specific position on the browser), now you can interchange the classes use jquery or javascript (that will change the position)
Sorry for bumping this thread
I stumbled over the "swap DOM-elements" problem and played around a bit
The result is a jQuery-native "solution" which seems to be really pretty (unfortunately i don't know whats happening at the jQuery internals when doing this)
The Code:
$('#element1').insertAfter($('#element2'));
The jQuery documentation says that insertAfter() moves the element and doesn't clone it

Remove element created by JavaScript on load

How can I remove elements which are created by JavaScript, I tried using CSS by setting display:none; but that doesn't seem to solve my problem, also I can't remove them since I don't have them in HTML, any other ways? Thank you
UPDATE:
Can't use any JavaScript such as jQuery, MooTools, ExtJS etc, and actual elements I want to remove are divs, with a specified class so I can't use getElementById.
I found this script on Google, but it doesn't seem to work but this is what I need:
HERE
This is fairly simple to do this using jQuery.
$("#myId").remove();
will remove
<div id="myId"></div>
Edit: You can also do it with "old school" javascript.
The function you're looking for is removeChild()
Example:
function removeElement(divNum) {
var d = document.getElementById('myDiv');
var olddiv = document.getElementById(divNum);
d.removeChild(olddiv);
}
You will want something like this to take advantage of browser support where you can:
if(document.getElementsByClassName){
// Safari 3+ and Firefox 3+
var itms = document.getElementsByClassName('your_class');
for(var i = 0; i<itms.length; i++){
var it = itms[i];
if(it.tagName == "DIV"){
it.parentNode.removeChild(it);
i = i - 1; //It actually gets removed from the array, so we need to drop our count
}
}
} else {
// All other browsers
var itms = document.getElementsByTagName('div');
for(var i = 0; i<itms.length; i++){
var it = itms[i];
// Test that className contains your class
if(/your_class/.test(it.className)) it.parentNode.removeChild(it);
}
}
JavaScript handles all memory mangement for you using garbage collection so once all references to an object cease to exist that object will be handled by the browsers specific implementation.
If you have the dom element itself:
if(node && node.parentNode){
// return a ref to the removed child
node.parentNode.removeChild(node);
}
Since you say you can't use Javascript, you're pretty stuck. Have you tried this CSS:
.classname {
display: none !important;
}
It's possible that the created elements have inline styles set on them, in which case normal CSS is overridden. I believe the !important will override inline styles.
Of course, the best solution is not to add the element in the first place... but I'm guessing you're in one of those (unfathomably common) scenarios where you can't change or get rid of the JS?
Not all browsers have a
document.getElementsByClassName
method, but for your purpose you can
fake it well enough- This method does
not work like the native
HTMLElement.getElementsByClassName- it
returns an array, not a live nodelist.
You can specify a parent element and a
tag name to speed it up.
function getElementsByClass(css, pa, tag){
pa= pa || document.body;
tag= tag || '*';
css= RegExp('\\b'+css+'\\b');
var A= [], elements, L, i= 0, tem;
elements= pa.getElementsByTagName(tag);
L= elements.length;
while(i<L){
tem= elements[i++];
if(css.test(tem.className)) A[A.length]= tem;
}
return A;
}
// test
var A= getElementsByClass('removeClass'), who;
while(A.length){
who= A.pop(); // remove from the end first, in case nested items also have the class
if(who.parentNode) who.parentNode.removeChild(who);
who= null;
}
If you have assigned event handlers to
the elements being removed, you should
remove the handlers before the
elements.
You will probably have to be more specific.
The general answer is 'with JavaScript'. As long as you have a way of navigating to the element through the DOM, you can then remove it from the DOM.
It's much easier if you can use a library like jQuery or prototype, but anything you can do with these you can do with JavaScript.
marcgg has assumed that you know the ID of the element: if you don't but can trace it in the DOM structure, you can do something like this (in prototype - don't know jQuery)
var css_selector = 'table#fred tr td span.mydata';
$$(css).invoke('remove');
If you can't use a JS library, you'll have to do the navigation through the DOM yourself, using Element.getElementsByTagName() a lot.
Now you've specified your question a bit: use Element.getElementsByTagName, and loop through them looking at their className property.
Use:
document.removeChild('id_of_element');

Categories

Resources