How can you do something like the following?
$('.myDivs').ontouchstart(function(){
alert('touch');
})
the only way I appear to be able to implement touch events is using javascript.. like so
document.getElementById('singleDiv').addEventListener("touchstart",touchHandler, false);
However I would like to implement this to a class, rather than an id... therefore is there a way to do it using jquery like the above example?....
I have found the answer:
$('.myDivs').bind('touchstart', function (event) { alert('touch');});
Kind regards J
As of jQuery 1.4.2, the following works fine for me:
$('.classname').live('touchstart', function(e) {
// Do whatever you want here...
});
Or for the latest versions of jQuery:
$('.classname').on('touchstart', function(e) {
// Do whatever you want here...
});
just select the class instead of the id:
document.getElementsByClassName('myClass').addEventListener(...);
please not that this selector will not work in IE. For IE you could use jQuery:
$('.myClass').on("click",function(){});
Related
I want to be able to assign a function to keypress of elements that don't exist when the DOM loads. In jQuery the code I had is like this
$(document).on('keypress', '.sc-chat-window .sc-user-input--text, #waste-form input,#address,.waste-wise-container .form-control,.widget-box .form-control,#aria-main-search-form-field,#footer-search-field,#aria-feedback-form-field', function(e) {
updateLastTypedTime();
});
It worked fine, but the problem is I can't use jQuery anymore and I would like to use Pure JavaScript this is what I have. The issue is that some elements don't exist yet so when this runs, it doesn't add the eventListener to the selectors.
JS:
var keyPressElements = document.querySelectorAll('form[id="4840400"],#waste-form input,#address,#aria-main-search-form-field,#footer-search-field,#aria-feedback-form-field');
keyPressElements.forEach(function(elem) {
elem.addEventListener('keypress', function() {
updateLastTypedTime();
});
});
How can I fix this issue?
How can I manually re-enable links (not form elements) that get disabled with Rails' disable_with feature?
The call to reenable links is slightly different than form elements. It actually binds a handler to the click event that stops anything else from happening. I was able to figure this out by investigating how the jquery-ujs library.
To reverse this effect, simply use the enableElement method on your jQuery object:
$.rails.enableElement($('a[data-disable-with]'));
With Turbolinks, it also helps to watch for the 'page:change' event instead of window.unload:
$(document).on('page:change', function() {
$.rails.enableElement($('a[data-disable-with]'));
});
A solution I found here:
$(window).unload(function() {
$.rails.enableFormElements($($.rails.formSubmitSelector));
});
Rails has updated their javascript to no longer use jQuery.
You can now re-enable elements with the following (assuming you are still using jQuery):
var selectors = [Rails.linkDisableSelector, Rails.formEnableSelector].join(', ');
$(selectors).each(function() {
Rails.enableElement(this);
})
Hey its quite simple you just need to find button and do
$button = $('#someId')
$.rails.enableElement($button)
$button.removeAttr('disabled')
Based on #DGM solution I ended up with the following code:
$.rails.enableFormElements($disabled_button);
Where:
$disabled_button is the jQuery object for the button disabled by data-disable-with which could be selected like this:
$disabled_button = $('[data-disable-with]');
OK I found this interesting work around (apparently the problem is only in FF)
set :autocomplete => 'off' and now it works. Or one of the other answer might work as well.
ref: https://github.com/rails/jquery-ujs/issues/357
You can use jQuery to remove the data-disable-with attribute that Rails adds to the button:
$('#disabledbutton').removeAttr('data-disable-with');
I am using the Hammer.js library for mobile touch events and in their example for use with jQuery, they have the following:
$('#test_el').hammer().on("tap", ".nested_el", function(event) {
console.log(this, event);
});
This is straightforward; however, I would like to incorporate a toggle behavior to #test_el. In other words, if the above example was replaced with something like this:
$('button').hammer().on("tap", function() {
$('div').addClass('open');
}, function {
$('div').addClass('close');
});
How would I get this "toggle" behavior to work?
Initially, you could add a starting class to all buttons. Then on event, you can check if the class exists. This lets you know what state the element was in when you tapped it.
$('button').addClass('close');
$('button').hammer().on('tap', function() {
if ($(this).hasClass('close')) {
$(this).removeClass('close').addClass('open');
// Event code
}
else {
$(this).removeClass('open').addClass('close');
// Event code
}
});
jQuery also provides a toggleClass method.
There is already a toggleClass function available in JQuery, it seems that it does what you want.
Try:
$('#test_el').hammer().on("tap", ".nested_el", function(event) {
$(this).toggleClass("classnamehere");
});
Where classnamehere would be your class name.
On is not working as a replacement for live; as the new ON is NOT working for future elements. No problems in my implementations; I'm used to use live and I definitely know when something works or not with jquery.
haml part :
.field
%label Select a file
= file_field_tag 'post[image]', :class => :dashed
%span.adder + add another file
coffe part :
$("span.adder").on "click", (e) ->
new_field = $(this).closest(".field").clone()
$(new_field).insertAfter( $(this).closest(".field") )
Why the new span.adder added does not have the jquery behaviour attached to their class ?
Something like this shoudl work in that case.
Why the JQuery guys did remove it ?
I don't get it.
UPDATE
$("span.adder").on("click", function(){ });
Will not work as live.
It has to be
$(document).on("click", "span.adder", function(){ });
(thanks for everyone's answers.)
To work with future elements you must use on document like this
$(document).on('click', 'span.adder', function(){
//Code here
});
Before .on() ever came around, .live() was already considered an inefficient way to handle event binding, Because of that for future use you have to use .on()
e.g:-
$(document).on('click', '#yourElement', function() {
// your functions here
});
There is a better explanation here
It is a replacement. The direct translation would be:
$(document).on('click', '.my-selector', function() {});
They deprecated and remove it because they had better implementation. You see the documentation of .on()
$(ancestor).on(event, element, function);
You should use that as ancestor which is near to that element. There are some performance issues.
Upgrade jQuery version also.
On works asdelegate` used to do, not exactly as .live; you have to use it on a parent and then specify the event and the children that triggers it; something like.
$(window).on("click", ".button", function(){
alert("You clicked the button... and I hate alerts");
});
So I'm currently using .append() to add a feature to all of the posts on a webpage, but when additional posts are loaded on the page, the appended features aren't included in the new content — I'm trying to come up with a way to make sure all of the new content has the appended feature too.
$(this).append('<div id="new_feature></div>');
Something like this?
$(this).live().append('<div id="new_feature></div>');
Maybe there's a way to make it constantly appending in a loop perhaps?
There is DOMNodeInserted event:
$('button').click(function() {
$('#appendme').append($('<div class="inner">').text(Math.random()));
})
$('#appendme').on('DOMNodeInserted','.inner',function() {
console.log(this);
});
DEMO
update: this seems not works in IE, try propertychnage event handler also ($('#appendme').on('DOMNodeInserted,propertychange') but i not sure, have no IE to check this right now.
update2: Domnode* seems deprecated according to mdn, they tell to use MutationObserver object instead
update3: seems here is no very crossbrowser solution for MutationEvents, see this answer, so my suggestion would be use code above, if event supported and fallback to setTimeOut or livequery option.
update4:
If you depend only on .append() you can patch jQuery.fn.append() like this:
jQuery.fn.append=function() {
return this.domManip(arguments, true, function( elem ) {
if ( this.nodeType === 1 || this.nodeType === 11 ) {
this.appendChild( elem );
$(elem).trigger('appended');
}
});
};
$('button').click(function() {
$('#appendme').append($('<div class="inner">').text(Math.random()));
})
$('#appendme').on('appended','.inner',function() {
console.log(this);
});
DEMO2
may be more correct is to spoof jQuery.fn.domManip like here
jQuery documentation:
Use of the .live() method is no longer recommended since later versions of jQuery offer better methods that do not have its drawbacks.
You can use setTimeout() function that can check for new <div>s every n milliseconds.
$(function(){
setInterval("Check4NewDivs();",1000);
});
So say this is a div with class="comment newdiv", so when it appears on the page for the first time, it has the class newdiv that will let the function know it was just dynamically created.
function Check4NewDivs(){
$(".comment .newdiv").each(function(){
$(this).append('<div class="new_feature"></div>').removeClass("newdiv");
});
}
It's append not appened.
live is a deprecated event handler. It's not used this way. use on instead.
http://api.jquery.com/live/
So, the following code will run when you click selector.
$(document).on('click', 'selector', function() {
$(this).append('<div id="new_feature></div>');
});
No, there is no standard way to do it like that. There was a proposal of the events that would be fired whenever the DOM elements are inserted etc., but you cannot rely on that.
Instead rely on either:
(preferably) callbacks - just invoke function ensuring existence of such appended snippets, whenever you pull something (but after you successfully pull it from server and insert into DOM, not sooner), or
constant checks - like using in setInterval() or setTimeout(), but this would be unnecessary processing and you will never get instant append, unless you will perform processing-heavy checks all the time,
use the on load function:
$(item).on('load',function(){
$(this).append('<div id="new_feature"></div>');
});
This will add append the item as a callback once the item has been loaded. I would also choose some sort of dynamic ID creator rather than always append stuff with the same ID, but thats just me.
you must bind to an element that already exists on the page. i have written an example where i make appended content live.
DEMO on JSFiddle
HTML
<div id="container">
<div id="features">
</div>
<br />
<a href='#' id='clickme'>click me to add feature</a>
</div>
JS
$(function() {
$('#clickme').on('click', function(e) {
$('#features').append('<div class="new_feature">new feature</div>');
});
$('#features').on('click', '.new_feature', function() {
alert('i am live.');
});
});