blur event doesn't trigger at first attempt - javascript

I'm trying to update the DOM based on the value entered in a text box.
HTML:
<input id="event-name" type="text"/>
JQUERY:
$('#event-name').on('blur',function(){
$.post("scripts/add-team-support.php",{eventName : eventName},function(minAndMaxString){
//my code here
});
});
this works on the first blur in Chrome. When I tried it in opera, mozilla and edge it doesn't worked on the first attempt.
It worked when I added this before the jquery.
$("#event-name").focus();
$("#event-name").blur();
$("#event-name").focus();
I did this to make the first $.post call to occur when the page opens.
Why is this problem happening?
How to solve this in a proper way?
Please help!

You can try this code:
var lazyTriggerEvent = function(id,event,callback){
var searchTrigger=null;
$("#"+id).bind(event,function(){
var text = $.trim($(this).val());
clearTimeout(searchTrigger);
searchTrigger = setTimeout(function(){
callback(text);
},500);
})
};
//use keyup event
lazyTriggerEvent("event-name","keyup",function(){})

It often happens with elements across browsers that consequent events do not work when binding an event to them through ID or class. The following solution should help you:
$(document).on('blur','#event-name', function(){
$.post("scripts/add-team-support.php",{eventName : eventName},function(minAndMaxString){
//my code here
});
});
Alternatively, you could use keyup event. You can do so following:
$(document).on('keyup','#event-name', function(){
var eventName = $(this).val();
$.post("scripts/add-team-support.php",{eventName : eventName},function(minAndMaxString){
//my code here
});
});
Also, using - in IDs is not a good approach. Rather, either stick to camelCase or underscore_format of naming convention.

Related

jQuery get attribute of clicked element when content is dynamically generated

I am working on a site where a lot of content is generated dynamically using AngularJS. I need to get the attribute of an element that is dynamically generated using jQuery, but I am having trouble doing so. I have already figured out that I need to use the .on method to click rather than .click. My issue is finding the equivalent of $(this) within the .on method.
Here is my code:
$(document.body).on('click', 'a.card-topic-link' ,function(e) {
e.preventDefault(); // Prevent default action - this works
console.log('The click works!'); // This fires and works just fine
var cardTopicLink = $(this).attr('data-topic-link'); // This is where the problem lies
console.log(cardTopicLink); // This is undefined
}); // End on click
As I stated before, this does not work as the .click does not work for dynamic content:
$('a.card-topic-link').click(function(e) {
e.preventDefault(); // Prevent default action
var cardTopicLink = $(this).attr('data-topic-link');
console.log(cardTopicLink);
});
I feel like there is a simple solution to this problem that I am having trouble finding. The key to this issue is that this is dealing with dynamic content.
Let me know if you have any ideas.
use e.currentTarget, instead of var cardTopicLink = $(this).attr('data-topic-link');, try var cardTopicLink = angular.element(e.currentTarget).attr('data-topic-link');
$(document).ready(function () {
$(document.body).on('click', 'a.card-topic-link' ,function(e) {
e.preventDefault(); // Prevent default action - this works
console.log('The click works!'); // This fires and works just fine
var cardTopicLink = $(e.currentTarget).attr('data-topic-link'); // This is where the problem lies
console.log(cardTopicLink);
}); // End on click
});
plunker with similar code, firing on async loaded content - http://plnkr.co/edit/02rqCrbBVwXiIYff8ktC?p=preview
It turns out that AngularJS was stripping out the attribute data-topic-link as it was parsed. This was happening because the HTML that contained the data-topic-link was passed as a part of the response that Angular was printing in an ng-repeat.
I updated the code so that the HTML with this attribute did not need to be served by AngularJS.

JavaScript alert callback not working inside a function

I am trying to make a image preview containing of about 5-6 images which will appear one after another when user hovers over it (not like a carousel with prev and next buttons). Here is the fiddle consisting of what I gathered so far.. i don't know if this approach is right or not.. but I am stuck as the alert callback is not working. Could someone please tell me what is wrong?
$(function()
{
var imageCount = $('#product_grid_list').find('figure')[0].getElementsByTagName('img');
for (var i = 0, n = imageCount.length; i < n; i++) {
imageCount[i].on('click', function(e)
{
alert('Everything is going fine!');
}
);
}
}
);
The root cause of click event callback can't be triggered is that you're trying to register a event handler on a "DOM" (in this case: imageCount[i]) element in jQuery way. Try to register the event handler like this if you want to use pure javascript solution:
imageCount[i].addEventListener('click', function(e){
alert('Everything is going fine!');
});
Here is a jsfiddle demo.
Note: I didn't consider the cross browser issue in this case.
BTW, try to cache the length of imageCount node list, it will improve the performance.
You are using js AND jQuery at same time. It's wrong. If you use jQuery, than click event will be like this:
$(document).('click', '#product_grid_list figure img', function(){
alert('Everything is going fine!');
});
You are using a mix of jQuery and standalone javascript. You might as well go all the way to jQuery, with something like:
$('#product_grid_list figure:first img').click(function(e) {
alert('Everything is going fine, hopefully!');
});
You did not send the corresponding HTML, so we cannot test whether the above is correct.
it's just a simple click event in jQuery, no need to use js: http://jsfiddle.net/wP3QQ/11/
$('#product_grid_list').find('figure img').click(function(e){
alert('Everything is going fine!');
e.preventDefault();
});
You want the hover effect, so click event should not be used over here. It should be mouseover.
Working Fiddle
Code Snippet:
$(document).on('mouseover','#product_grid_list figure img',function(e){
alert("now it is working");
});
You are attempting to call on(), a jQuery method, on an HTMLElement (a DOM element). You can't do that, jQuery methods can only be called on jQuery collections. It's easy to get a jQuery collection for the elements you desire:
Use .find() to match the images
There's no need for a for() loop, jQuery's .on() will handle looping for you.
You may also want to prevent the default behaviour of your anchors
$(function () {
var imageCount = $('#product_grid_list').find('figure img');
imageCount.on('click', function (e) {
e.preventDefault()
alert('Everything is going fine!');
})
});
JSFiddle

Cant select ids that I loaded with jQuery

I understand that you need to use ".on" to use code that you loaded with jquery after the page has loaded. (At least I think it works that way)
So I tried that but it somehow just doesn't do a thing at all. No errors in the console either.
$("#forgot_password").click(function(){
var forgot_password = '<div id="toLogin" style="cursor:pointer;">Prijava</div>'
$("#loginPopupForm").html(forgot_password);
});
$("#toLogin").on("click", function(){
alert("Hello");
});
So when I click on #forgot_password it does execute the first click function. But when I click on #toLogin it doesn't do anything and I think its because its loaded with jquery when I click on #forgot_password
Try this
$("#loginPopupForm").on("click", "#toLogin", function(){
alert("Hello");
});
You need to bind to an element that is present when the page loads, like body for example. Just change your code to what is shown below
$("body").on("click", "#forgot_password", function(){
var forgot_password = '<div id="toLogin" style="cursor:pointer;">Prijava</div>'
$("#loginPopupForm").html(forgot_password);
});
$("body").on("click", "#toLogin", function(){
alert("Hello");
});
You are setting the on to the wrong thing. You want it to be:
$(document).on('click', '#toLogin', function() {alert('hello') });
The id isn't there until you do the other click event, so jQuery is not finding any element to set the click event on. You need to have an element that has been rendered in the DOM to set the event on.
You are totally right about the problem : on() targets only elements that are already existing as it runs.
What you need in jQuery is called Delegated event and is well explained on the Jquery doc page.
The difference in the code is thin, but it's how you're supposed to do.
You have to specify the parent element
$("#toLogin").on("click","#loginPopupForm", function(){
alert("Hello");
});
in the 2nd argument of the on

jQuery plugin: add eventlistener to element

I'm creating a small jQuery plugin for personal use which adds some content to the document when you hover over an element.
Currently this is the (simplified) code:
(function($){
$.fn.tempFnName = function(options){
var element = $('<div />');
return this
.each(function(){
$(this)
.on('mouseenter',
function(){
$('body')
.append(element);
})
.on('mouseleave',
function(){
element.remove();
});
});
};
})(jQuery);
For some reason this doesn't work. Looking around on google and stackoverflow didn't provide an answer. What am I doing wrong?
edit: As pointed out by WTK, there's nothing wrong with this code. The following code shows how the plugin should be implemented.
function appendAddAnchor(){
return $('<a />').tempFnName();
}
//even if I try the following, the click event will not work!
function appendAddAnchor(){
return $('<a />')
.click(function(){console.log('test')});
.tempFnName();
}
This is really strange to me, because I used to have Bootstrap' .tooltip() chained to the same $('<a />') and this worked without any issues...
I tried this in this fiddle: http://jsfiddle.net/Gm4jk/2/
(function ($) {
$.fn.tempFnName = function(options){
var element = $('<div/>');
element.html('aTest');
return this.each( function(){
$(this).mouseenter(function(){
$('body').append(element);
});
$(this).mouseleave(function(){
element.remove();
});
});
};
})(jQuery);
$('#start').tempFnName();
and it is working just fine. It may be that you are running into compatibility issues.
from the jQuery documentation:
"The mouseenter JavaScript event is proprietary to Internet Explorer. Because of the event's general utility, jQuery simulates this event so that it can be used regardless of browser. This event is sent to an element when the mouse pointer enters the element. Any HTML element can receive this event."
I read that to mean if you are not using the shorthand bind method, you may not be getting the 'emulated' event instead jQuery may be looking for the actual event which, in all but IE, does not exist.
To be clear, I also got it to work with your code in jsFiddle. http://jsfiddle.net/zFKXx/2/

onkeypress textbox issue

I have this:
<input type="text" ID="txtMy" name="txtMy" onkeypress="initialize();"/>
And in my .js file I have:
initialize()
{
var x = $("#txtMy").val();
}
But, if I have '2' in my textbox, and then I enter 4, the value of x is still 2. How to resolve this?
Use keyup
Here is how you do that in the unobtrusive way.
HTML
<input type="text" id="txtMy" />
Script
$(function(){
$("#txtMy").keyup(function (event) {
alert($(this).val())
});
});
Working Sample : http://jsfiddle.net/VmELF/4/
If you want to bind the functionality to a text box which is being injected to the DOM after the dom load( possible by an Ajax call etc...), you may use jQuery on
$(function(){
$("body").on("keyup","#txtSearchKey",function (event) {
alert($(this).val())
});
});
Your spelling of initialize in the onkeypress does not match the declaration (inititalize).
keydown and keypress events both execute BEFORE the entered key has actually appeared in the text box. If you want to get the new value of the input after the key has appeared, use the keyup event instead.
<input type="text" ID="txtMy" name="txtMy" onkeyup="initialize();"/>
initialize()
{
var x = $("#txtMy").val();
}
You should consider binding your event handlers in javascript using .on(), since you're using the library anyways. Keeping your logic (javascript) seperated from your view (html) is a good habit to get in to.
instead of markup event handler you can use jquery:
var x;
$("#txtMy").on("keyup", function(){
x = $(this).val();
alert(x);
})
A few things:
Use the keyup event. keypress is firing before the character is recorded.
Your initialize() function is misspelled in your HTML snippet.
See the working jsfiddle at http://jsfiddle.net/8XTLW/1/

Categories

Resources