jquery priority execution - javascript

Can anyone help me with this:
$('#n').click(function() {
$(this).parent().append(' delete');
$(this).next().click(function() {
alert('clicked'); //this not working
});
$(this).blur(function() {
$(this).next().remove();
});
});
JS Fiddle demo; the problem is that the blur() event is executed before click() event.

You can use a timeout to postpone the removal for some milliseconds.
example : http://jsfiddle.net/vkun9/7/
$(this).blur(function() {
var _this = this;
setTimeout(function(){$(_this).next().remove();},100);
});
I also moved the blur attaching to be outside of the click handler, as it was adding an additional one each time the element was clicked, and changed the click handler to the focus to avoid multiple remove buttons from repeated clicking on the input, as #dheerosaur noted.
so
$('#n')
.focus(function() {
$(this).parent().append(' delete');
$(this).next().click(function() {
alert('clicked'); //this not working
});
})
.blur(function() {
var _this = this;
setTimeout(function(){$(_this).next().remove();},100);
});
What you experience, though, is not a problem. It is the normal behaviour, as the element need to lose focus (fires the blur) before another element can have it.
You should also match the label for attribute with the id of the input element.

Use the outside events plugin and you can do something like this:
$('.input_field input').focus(function() {
var div = $(this).parent();
var link = $('delete').click(function(e) {
e.preventDefault();
alert('clicked');
}).appendTo(div);
$(this).data('delete', link);
}).bind('focusoutside clickoutside', function(e) {
var link = $(this).data('delete');
if (link && e.target != link[0]) {
link.remove();
}
});
First switch to using the focus event rather than the click event on your input field, some people actually use the keyboard to navigate through form fields ;-).
Then its creating the delete link, adding it to the page and storing a reference to it in on the input field.
Then with the outside event plugin we can bind focusoutside and clickoutside which get triggered when the user tabs or clicks outside the input field. By checking of the target of the event was the delete link or not we can tell if we should remove the link.
Example: http://jsfiddle.net/petersendidit/vkun9/6/

you can try setting a very short timeout in the blur event. this worked for me.
$(this).blur(function() {
setTimeout(function(){$(this).next().remove();}, 1);
});

Rather than using blur() I put together a hover()-based approach, though it does have a slightly clunky if/else statement:
$('.input_field').hover(
function(){
if ($(this).find('.delete').length) {
return false;
}
else {
$('delete')
.appendTo($(this));
}
},
function(){
if ($('#n').is(':focus')){
return false;
}
else {
$(this).find('.delete').remove();
}
}
);
JS Fiddle demo.
This approach does, however, ensure that there's only one delete link appended to the input_field (rather than the multiple links appended if the input is clicked multiple times in your original demo).

Related

EventListener not working with anchor tel:XXXXXXXXX

I have a tag with href="tel:XXXXXXXXX", and I need catch the click event.
I have tested the following code on chrome: $(document).on('click',console.log). If i click on this tag browser it calls the application, but does not trigger a click event.
$("a[href^='tel']").on('click', console.log);
This is working, but I my have a problem with content load by ajax. My code has loaded a page and after some time application added content by ajax. When i use $(document).on('click', ("a[href^='tel']", console.log), there is a problem.
$("a[href^='tel']").on("click", function(e){
e.preventDefault(); e.stopPropagation();
console.log(this);
alert(this.getAttribute("href"));
})
//or if you want to delegate your function
$(document).on('click', "a[href^='tel']", function(e){
e.preventDefault(); e.stopPropagation();
console.log(this);
alert(this.getAttribute("href"));
});
This will bind an event listener to all click on a tags with a href attribute and prevent the click itself. After click, you'll be able to use your console to see which element was click and what href was used.
Ok, i found resolve.
I use earlier event "mousedown" and change attr "href" to "only number" for disable action click.
Code:
const click2dial_Event = function(e) {
e.preventDefault();
let a = $(this), number;
if (a.attr('href') !== '#') {
number = a.attr('href');
number = number.substr(4);
a.attr('href', '#');
a.attr('data-dial', number)
a.addClass('click-to-dial');
} else {
number = a.attr('data-dial');
}
//...
};
$(document).on('mousedown', "a[href^='tel']", click2dial_Event);
$(document).on('mousedown', '.click-to-dial', click2dial_Event);
This would get the phone number from the a tag starting with a value of tel upon clicking it.
$("a[href^='tel']").on("click", function(e) {
var hrefText = this.getAttribute("href");
var str = hrefText;
var res = str.split(":");
alert(res[1]);
});
On Initial Load
I would first recommend that you wait for the initial DOM to be ready before binding any events to elements.
// DOM ready shorthand
$(function() {
$("a[href^='tel']").on('click', function(e) {
// Do work here
});
});
AJAX Content
If you are adding additional elements after the initial load you will have to bind events to those new elements as well.
You could also do something like adding a data attribute to the elements that you've bound click events to and only add to ones that don't yet have that data attribute - but that's additional unnecessary work.
Full Example Code
// DOM Ready Shorthand
$(function() {
// Click Handler
function clickEvent(e) {
// Do work here
}
// Bind click event to initial tels
$("a[href^='tel']").on('click', clickEvent);
// Arbitrary AJAX request for demonstration (wherever yours may be)
$.ajax('/newContent')
.done(function(html) {
// Adding our response HTML to the page within #someElement
$('#someElement').append(html);
// Bind click event to the new tel elements scoped to the returned html
$("a[href^='tel']", html).on('click', clickEvent);
});
});

Detecting class on HTML element not working correctly

I have a button and when it is clicked it should add a class to the HTML element, but then when the .class is clicked, it isn't detected.
This is the use case:
Click button - "testerclass" will be added to HTML element
Click "testerclass" - removes that class from that element
The detection for when "testerclass" is clicked only seems to work when the class exists before the page load, not when I add the class manually after load. Is this something to do with the problem?
I have tried to recreate the problem on jsfiddle, but I can't recreate the use case where the class is already added to the HTML element, as I can't edit that on jsfiddle.
But here is jsfiddle one, In this one you can see that the buttonone adds a class to HTML, but the detection for clicks on .testerclass never come through.
And here is jsfiddle two. In this one, I have changed the .testerclass selector to html, and this shows that HTML clicks are bubbling through (which I was unsure of when I first hit this problem).
And offline I created a third testcase where the HTML element already had the testerclass, and it detected the clicks sent through to it.
$(document).ready(function() {
$('button.1').click(function() {
$('html').addClass('testerclass');
$('.test').append('"testerclass" added to html<br />');
});
$('.testerclass').click(function() {
$('.test').append('testerclass clicked and removed<br />');
$('html').removeClass('testerclass');
});
});
Edit: I also tried doing this with a slightly different method of:
$('html').click(function() {
if(this).hasClass('testerclass') {
//do stuff
}
});
but that didn’t work either.
Since the testerclass is dynamic, you need to use event delegation to handle events based on that. Which will require us to register the event handler to the document object that causes another problem because the click event from the button will get propagated to the document object which will trigger the testerclass click handler as well. To prevent this from happening you can stop the event propagation from the button.
$(document).ready(function () {
$('button.1').click(function (e) {
e.stopPropagation();
$('html').addClass('testerclass');
$('.test').append('"testerclass" added to html<br />');
});
$(document).on('click', '.testerclass', function () {
$('.test').append('testerclass clicked and removed<br />');
$('html').removeClass('testerclass');
});
});
Demo: Fiddle
You need to stop the propagation to the html so the other click handler does not pick it up.
$('button.1').on("click", function(evt) {
$('html').addClass('testerclass');
$('.test').append('"testerclass" added to html<br />');
evt.stopPropagation();
});
$(document).on("click", function() {
$('.test').append('testerclass clicked and removed<br />');
$('html').removeClass('testerclass');
});
Other option would be to add one event handler and use the event target to see if it is the button or not and change the content that way.
$(document).on("click", function (evt) {
var isButton = $(evt.target).is(".btn");
var message = isButton ? '<p>"testerclass" added to html</p>' : '<p>"testerclass" clicked and removed</p>'
$('html').toggleClass('testerclass', isButton);
$(".test").append(message);
});
JSFiddle: http://jsfiddle.net/69scv/
here's a neat way to do it
$('html').on('click', function(e) {
var state = !!$(e.target).closest('button.1').length;
var msg = state ? 'class added' : 'class removed';
$(this).toggleClass('testerclass', state);
$('.test').append(msg + '<br>');
});
FIDDLE
You add a class to html element, so when this class is clicked, it means the html element is click. Now the problem is when you click any where in page, it will remove this class away from html! Let try add this class to body element instead.
$(document).ready(function() {
$('button.1').click(function() {
$('body').addClass('testerclass');
$('.test').append('"testerclass" added to html<br />');
});
$('.testerclass').click(function() {
$('.test').append('testerclass clicked and removed<br />');
$('body').removeClass('testerclass');
});
});
And now you can check it:
$('html').click(function() {
if(this).hasClass('testerclass') {
//do stuff
}
});

jquery not function miss element

I use a tool-tip to display error message on the page, I need it to be closed when I click elsewhere within the view. I use the below codes to control this action:
$(':not(.qtip)').click(function(){
$('.qtip').hide();
});
The ".qtip" is used for marking the tool-tip area. The tool-tip itself creates a new one when it comes out, what happened here is when I click on the tool-tip, it disappears.
But when I use a smaller scale of the selector instead of the whole body, it works fine, which is a little weird, for example:
$("#id").not('.qtip').click(function (){
$('.qtip').hide();
});
It would be advisable to just target document for handling the click outside of your tooltip; the selector for :not(.qtip) potentially returns a very big result set.
$(document).on('click', function() {
$('.qtip').hide();
}
On the tooltip itself you would need to prevent the click event from bubbling to document level, if you're not doing so yet:
$('.qtip').on('click', false);
Use event bubbling to your advantage
$(document).on("mouseup", function (e) {
var target = e.target || e.srcElement;
var container = $(".qtip");
if (container.not(target) && container.has(target).length === 0)
{
container.hide();
}
});
I suggest you to do two things:
$(document).click(function() {
$('.qtip').hide();
});
$('.qtip').click(function(e){
e.stopPropagation();
});
click of document to hide the .qtip
stop the event bubbling on click of .qtip, here click won't traverse up to the parent.
Try
$(document).on("click", function(e) {
var qtip = $(e.target).closest('.qtip');
if(!qtip.length)
$('.qtip').hide();
});

jquery live return false on A tags

I have a click bound as live to an element. The handler returns false after execution, but if the element happens to be an A tag, then the link is also not followed, which is unacceptable...
$('*').live('click', function(){
// lots of code here
return false;
});
Now if the element that is clicked on has a path like A>img and the image is clicked on, the A will never be followed. I dont want the click event to propagate any further.
how do I achieve this?
Edit:
It is essential for my application to bind the event to *. Also, the clicks can be made on any element, not just A's. Thus none of the mentioned solutions are suitable for what I wish to achieve.
What you're looking for is preventDefault()
$('*').live('click', function(e){
// lots of code here
e.preventDefault();
return false; // Don't think this is necessary
});
I'd also like to say that attaching an event to all elements is probably Not A Good Idea.
You'd be better served by attaching to the A tags specifically:
$('a').click(function(e){
// lots of code here
e.preventDefault();
return false;
});
I would not bind a click function to *. You could bind it to the body element; the click will propagate from the element that was clicked to the body element. You can check the element that was originally clicked like this:
$("body").live("click", function (e) {
if ($(e.originalEvent.target).is("a")) {
return false;
}
});
Having said that, you can still do this:
$("*").live("click", function () {
if ($(this).is("a") == false) {
return false;
}
});
Try:
if($(this).tagName == 'A')
return true; // perhaps even { do nothing }
else
return false;
This might not be the exact code to get the tagname, see this How to extend jQuery to make it easier to retrieve the tagName.
Also see this: http://fuelyourcoding.com/jquery-events-stop-misusing-return-false/

jQuery - call a function anytime a user changes any form input?

I have a page that has multiple forms. Anytime the user clicks an input or modifies text in an input I would like a function to be called. Any ideas on how to do this efficiently and in a way where it doesn't require the form IDs?
JavaScript events bubble up. So how about:
$('form').change(function() {
// do something
}).click(function() {
// do something
});
In each case you can query for the element that triggered the event and do what you please.
$('form input').each(function() {
var val = this.value;
$(this).click(function() { }
$(this).blur(function() {
}
});
You can also use delegate for better performance. It would help seeing your source and your exact needs.

Categories