catch paste event - javascript

I need a catch copy & paste event. I have a example. But paste event fires 4 times. Why? I need a it a one time. Here is the code? Please help me?
$(function() {
return $('#myform').bind('paste', function(e) {
return alert("123");
});
});

I'm not sure which browser your experience four events being fired, but I've jus tested your code for myself and could not reproduce the behaviour. That being said, there are a few issues with your code as it is...
There is no need to return the jQuery object after binding the event.
There is no need to return alert(), since alert returns undefined.
Take a look at these changes:
$(function() {
$('#myform').bind('paste', function(e) {
console.log(e.type);
});
});
See live: http://jsfiddle.net/rwaldron/6CKxM/

Related

How to raise an event click, have fields added to Ajax?

I have code that works correctly
$(document).on('click',"a.img,a.imgs",function() {
$(this).next().find('a:first').click();
return false;
});
But when I add new fields ajax ( for example show more), then with them this code does not work, and it's sad
Edited my answer as I misread your code and got everything mixed up.
Here's an explanation from another SO thread that might help you fix the problem:
It's probably not working due to one of:
Not using recent version of jQuery
Not wrapping your code inside of DOM ready
or you are doing something which causes the event not to bubble up to the listener on the document.
$(document).ready(function() {
// This WILL work because we are listening on the 'document',
// for a click on an element with an ID of #test-element
$(document).on("click","#test-element",function() {
alert("click bound to document listening for #test-element");
});
// This will NOT work because there is no '#test-element' ... yet
$("#test-element").on("click",function() {
alert("click bound directly to #test-element");
});
// Create the dynamic element '#test-element'
$('body').append('<div id="test-element">Click mee</div>');
});
$(document).on("click"... not working?

Why .trigger('change') is not working?

Got this piece of code, which works great. However the .trigger('change') is not working.
$(function () {
$('form').each(function () {
var form = $(this);
form.find('.cbox1').change(function () {
if (form.find('.cbox1:checked').length) {
form.find('.cbox2, .cbox3').button("enable");
} else {
form.find('.cbox2, .cbox3')
.prop("checked", false)
.trigger("change")
.button("refresh")
.button("disable", "disable");
}
});
});
});
I know this is probably something simple, but for a noob like me, it's killing me, been reading and studying for days...
Any knowledge/assistance is greatly appreciated,
Si
It works fine. Try adding this line and you'll see that cbox2 change is triggered.
$('form').find(".cbox2").on("change", function() {alert("cbox2 triggered")});
When you are triggering a change, you are triggering it on .cbox2 and .cbox3. However you have not added any listener for the change event on these elements. The listener for change event is attached only to .cbox1. If that is the listener you want to trigger, then call the the trigger("change") on .cbox1 or add event listeners for the other two elements.

jQuery executing both branches of an if-else statement in Rails

I have the following jQuery on a Rails page:
$(document).on('click','.reportsArrow', function() {
if ( $(this).parent().hasClass('reportCollapsed') ) {
console.log("A");
$(this).parent().removeClass('reportCollapsed');
}else{
$(this).parent().addClass('reportCollapsed');
console.log("B");
}
});
When I click on an element with reportsArrow and without reportCollapsed, the log shows
B
A
Meaning it is executing the else part and then executing the if part. I want the function to only be executed once per click, and to only follow one code path. Why is it being executed twice and how do I stop this? I should point out that this toggles correctly in the mockups created by the web designer (on HTML/CSS/JS only). It looks like the problem is Rails related.
EDIT:
We have found a working solution:
$('.reportsArrow').click(function() {
$(this).parent().toggleClass('reportCollapsed');
});
The event would be getting fired more then once and propagated up-ward in the DOM tree. Use event.stopPropagation(). You can also use the toggleClass instead of branching.
$(document).on('click','.commonClass', function(event) {
event.stopPropagation();
$(this).parent().toggleClass('newClass');
});
Not sure why, but my days in unobtrusive javascript have taught me to be as specific and as least fuzzy as I can.
Never worried why, as long as it worked. Having been asked why (just here), my answer is "I will have to look it up". Sorry.
Thus, I would avoid setting a catch method on THE document and then filter actions: I would directly point the event catches on the element (or set of elements) I want to watch.
So, instead of using:
$(document).on('click','.reportsArrow', function() {
//...
});
I would go the direct way:
$('.reportsArrow').click(function () {
//..
});
Having read the API documentation for jQuery .on(), it appears to me that it would be probably more suitable to use .one() instead, so there is no continuation after hit "#1". But I have not tested it, so I can't say for sure.
You need to stop event propogation to child elements.also you can use toggleClass instead:
$(document).on('click','.commonClass', function(e) {
e.stopPropagation();
$(this).parent().toggleClass('newClass')
});
Try this,
You need to avoid event bubbling up the DOM tree. There must be a parent causing the event to fire twice or more time.
To avoid this use event.stopPropagation()
$(document).on('click','.commonClass', function(event) {
event.stopPropagation();
$(this).parent().toggleClass('newClass');
});
I could not reproduce your problem. Your code is working fine in my Firefox on a simple HTML page.
Please try this piece of code and come back with the console output:
function onClick(ev) {
console.log(ev.currentTarget, '\n', ev.target, '\n', ev);
if(ev.target === ev.currentTarget)
console.log($(this).parent().toggleClass('newClass').hasClass('newClass') ? 'B' : 'A');
};
EDIT:
and of course:
$(document).on('click', '.commonClass', onClick);
For readability put the logic into the jQuery selector using the :not like this
$(document).on('click','.reportCollapsed > .reportsArrow', function() {
$(this).parent().removeClass('reportCollapsed')
console.log("A");
})
$(document).on('click','not:(.reportCollapsed) > .reportsArrow', function() {
$(this).parent().addClass('reportCollapsed')
console.log("B");
})
Given that this works one time (click > else > B) could it be that something listens for DOMSubtreeModified or other DOMChange Events which again trigger a click on the document ?
Have you tried debugging/following the calls after the inital click? Afaik chrome has a nice gui to do this.

Why Paste Event in jQuery fires on pre-paste?

I am trying to make textbox similar to the Twitter, for this I have written code for:
Word Count
Used Events Change, Keyup and Paste
Keyup and Change Events are working fine but paste event is little bit strange, when I paste something in textarea the word count doesn't change at that moment, after some debugging I found that paste event fires up before pasting something on textbox. I don't know how they handle this in Twitter.
Here is my code:
events:
'click #textboxId' : 'submitQuestion'
'keyup #textboxId' : 'wordCounter'
'change #textboxId' : 'wordCounter'
'paste #textboxId' : 'wordCounter'
wordCounter: ->
#Code for Word Count#
Due to pre-paste nature of paste event the work count doesn't changes on that instance.
Your suggestion and help will be appreciated.
See this example.
http://jsfiddle.net/urEhK/1
$('textarea').bind('input propertychange', function() {
$('#output').html($(this).val().length + ' characters');
});
That behavior was very weird. You would think that one of those events would catch this properly? I was surprised there weren't more answers to this via Google.
function update()
{
alert($textbox.val().length);
}
var $textbox = $('input');
$textbox.bind('keyup change cut paste', function(){
update(); //code to count or do something else
});
// And this line is to catch the browser paste event
$textbox.bind('input paste',function(e){ setTimeout( update, 250); });
You should now use on() instead of bind() see this post.
It's also unnecessary to create a named function, you can just create a anonymous function.
$('#pasteElement').on('paste', function() {
setTimeout(function(){
alert($('#pasteElement').val());
}, 100);
});
You can do one thing that firstly get original data . then you can get the event paste data and add them.
$("#id").on("paste keypress ",function(event){
// eg. you want to get last lenght
var length=$("#id").val().length;
if(event.type == "paste"){
//then you can get paste event data.=
length+=event.originalEvent.clipboardData.getData('text').length;
}
});`

JQuery effect working in firefox; not chrome / ie

This problem surprises me because it does not work in Chrome as well. Chrome!!
Anyways, I have 3 select boxes, A, B, C. On a page load, B and C are hidden. (This is fine in all browsers). Currently, I have an event handler attached to specific values in box A, so that if a value is clicked, B shows itself populated with results according to A. Same thing for C: if a value in B is clicked, C will show itself.
However, this "show" effect only occurs in firefox -- Chrome and IE are confused.
Any suggestions? hints?
Here is some code:
$(document).ready(function() {
$("#B").hide();
$("#C").hide();
$('select#A option').each(function() {
$(this).click(function() {
$.getJSON(stuff, callback(data));
});
});
});
function callback(data) {
// alert("hi"); // This isn't working for Chrome / IE! so the callback isn't called
$("#B").show(); // This isn't working for Chrome / IE!
};
EDIT: It Turns out, the 'select#A option' -- the 'option' tag was the buggy one. After changing my handler to "change", I was able to debug and debug till I just removed the option tag -- everything seems to work now.
Thanks,
Michael
The actual problem is in the following line:
//...
$.getJSON(stuff, callback(data));
//...
You are not passing the callback function, you are actually executing the function and passing undefined since it doesn't return anything.
You should pass only the reference of the function:
//...
$.getJSON(stuff, callback);
//...
Or use an anonymous function in place:
//...
$.getJSON(stuff, function(data){
$("#B").show();
});
//...
Edit: I haven't noticed about the click handler that you're trying to assign, I recommend you to use the change event on the select element, to ensure that an option has been selected:
$(document).ready(function() {
$("#B,#C").hide();
$('select#A').change(function() {
$.getJSON(stuff, function(data) { $("#B").show();});
});
});
I think that you might have extra closing brackets at the end of the callback function.
UPDATE:
It seems like firefox can pick the click event for the option but not IE. i don't know for chrome but it might be the same problem. Instead of listening to the click event on the option you could just use the change event to track a change in the select.
you could do the following if the change event does correspond to what you are trying to do.
$(document).ready(function() {
$("#B").hide();
$("#C").hide();
$('select#A').each(function() {
$(this).change(function() {
$.getJSON(stuff, callback(data));
});
});
});
function callback(data) {
$("#B").show();
};
Notice how i am listening to the change event on the Select itself.
I hope this helps!
If you put an alert in your callback function does it get shown?

Categories