How to create scroll event on dynamically (AJAX) generated element? - javascript

I need to do stuff when dynamically generated #random scrolls, but .on does not work
Doesn't work ->
$staticParent.on("scroll", #random, function()
{
//do stuff
});
Works ->
$staticParent.on("click", #random, function()
{
//do stuff
});
A) I would like to know why the first example (scroll) doesn't trigger the event and the second one (click) does.
B) Am I doing something wrong or is there any .on (non-deprecated) alternative I could use?
BTW - I have read and tried other related topics here, but nothing worked so far.

Keep it simple and stupid
$(document).on('ajaxComplete', function(){
/*Your code here*/
});
Docs here
EDIT
Possible Duplicate Of this

Scroll (as well as load and error) does not bubble up.
There are few approaches out there, but my personal favorite would be to rerun the on function after scroll. So basically:
function AddRandomEl()
{
// do your magic here
$staticParent.on("scroll", #random, function()
{
//do stuff
});
}
If your random is a class not an element then you would need ".off" before, or you would have it fire twice on those which pre-existed.

Related

JQuery click() event listener not working

im trying to get a lil project going but im stuck on a very annoying thing.
$(document).ready(function() {
$("#search-button").click(console.log('hello'))
});
as you can see im targeting a search button with the id search-button and as soon as i click it something should happen. in this case i put a console.log in to test if it works but it doesn't. it always logs it as soon as i load the page , not when i click the button i target. ... what am i doing wrong
if you need more info on this pls tell me i tried to keep it as simple as i could
ty for your help
O.k
The click handler needs a function argument, not just the console.log by itself. Try this:
$(document).ready(function() {
$("#search-button").click(function() {
console.log('hello');
});
});
Inside of .click should be a handler .click(handler) and the handler should be a function. The browser is reading the code and when it hits console.log('hello'), it does it! It's seeing .click etc, but it doesn't matter; it next sees console.log and does it.
Try
$(document).ready(function() {
$("#search-button").click(function() {
console.log('hello');
});
});
As others have mentioned, the click function requires its own callback function. You can also use this, without requiring the use of document:
$("#search-button").on('click', function() {
console.log('hello')
})
I hope You're using jQuery version 3 or up. if you use 3 or up jquery version the good practice is you use Document binding Example:
jQuery(document).on('click', '#search-button', function(event) {
//your Code here...
console.log('hello');
});

Run Jquery Function on Page Load and on Keyup

I have been googling this for a while, and can't seem to find an answer :( Simply I have two JQuery functions right now:
$('#textareainput').keyup(function(){
//Stuff
});
$(document).ready(function(){
//Stuff
});
And I would like to combine the two because they have the same exact contents. So how would I go about combining the two? Something like this?
$(document,'#textareainput').keyup(function(){
/stuff
});
You can trigger the event manually after registering the handler
$(document).ready(function () {
$('#textareainput').keyup(function () {
//Stuff
}).keyup();
});
But note that, the keyup event related specific properties of the event won't be populated

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

How to set the focus for a particular field in a Bootstrap modal, once it appears

I've seen a couple of questions in regards to bootstrap modals, but none exactly like this, so I'll go ahead.
I have a modal that I call onclick like so...
$(".modal-link").click(function(event){
$("#modal-content").modal('show');
});
This works fine, but when I show the modal I want to focus on the first input element... In may case the first input element has an id of #photo_name.
So I tried
$(".modal-link").click(function(event){
$("#modal-content").modal('show');
$("input#photo_name").focus();
});
But this was to no avail. Lastly, I tried binding to the 'show' event but even so, the input won't focus. Lastly just for testing, as I had a suspiscion this is about the js loading order, I put in a setTimeout just to see if I delay a second, will the focus work, and yes, it works! But this method is obviously crap. Is there some way to have the same effect as below without using a setTimeout?
$("#modal-content").on('show', function(event){
window.setTimeout(function(){
$(event.currentTarget).find('input#photo_name').first().focus()
}, 0500);
});
Try this
Here is the old DEMO:
EDIT:
(Here is a working DEMO with Bootstrap 3 and jQuery 1.8.3)
$(document).ready(function() {
$('#modal-content').modal('show');
$('#modal-content').on('shown', function() {
$("#txtname").focus();
})
});
Starting bootstrap 3 need to use shown.bs.modal event:
$('#modal-content').on('shown.bs.modal', function() {
$("#txtname").focus();
})
Just wanted to say that Bootstrap 3 handles this a bit differently. The event name is "shown.bs.modal".
$('#themodal').on('shown.bs.modal', function () {
$("#txtname").focus();
});
or put the focus on the first visible input like this:
.modal('show').on('shown.bs.modal', function ()
{
$('input:visible:first').focus();
})
http://getbootstrap.com/javascript/#modals
I am using this in my layout to capture all modals and focus on the first input
$('.modal').on('shown', function() {
$(this).find('input').focus();
});
I had the same problem with bootstrap 3, focus when i click the link, but not when trigger the event with javascript.
The solution:
$('#myModal').on('shown.bs.modal', function () {
setTimeout(function(){
$('#inputId').focus();
}, 100);
});
Probably it´s something about the animation!
I had problem to catch "shown.bs.modal" event.. And this is my solution which works perfect..
Instead simple on():
$('#modal').on 'shown.bs.modal', ->
Use on() with delegated element:
$('body').on 'shown.bs.modal', '#modal', ->
Seems it is because modal animation is enabled (fade in class of the dialog), after calling .modal('show'), the dialog is not immediately visible, so it can't get focus at this time.
I can think of two ways to solve this problem:
Remove fade from class, so the dialog is immediately visible after calling .modal('show'). You can see http://codebins.com/bin/4ldqp7x/4 for demo. (Sorry #keyur, I mistakenly edited and saved as new version of your example)
Call focus() in shown event like what #keyur wrote.
I've created a dynamic way to call each event automatically. It perfect to focus a field, because it call the event just once, removing it after use.
function modalEvents() {
var modal = $('#modal');
var events = ['show', 'shown', 'hide', 'hidden'];
$(events).each(function (index, event) {
modal.on(event + '.bs.modal', function (e) {
var callback = modal.data(event + '-callback');
if (typeof callback != 'undefined') {
callback.call();
modal.removeData(event + '-callback');
}
});
});
}
You just need to call modalEvents() on document ready.
Use:
$('#modal').data('show-callback', function() {
$("input#photo_name").focus();
});
So, you can use the same modal to load what you want without worry about remove events every time.
I had the same problem with the bootstrap 3 and solved like this:
$('#myModal').on('shown.bs.modal', function (e) {
$(this).find('input[type=text]:visible:first').focus();
})
$('#myModal').modal('show').trigger('shown');
Bootstrap has added a loaded event.
https://getbootstrap.com/docs/3.3/javascript/#modals
capture the 'loaded.bs.modal' event on the modal
$('#mymodal').on('loaded.bs.modal', function(e) {
// do cool stuff here all day… no need to change bootstrap
})
Bootstrap modal show event
$('#modal-content').on('show.bs.modal', function() {
$("#txtname").focus();
})
A little cleaner and more modular solution might be:
$(document).ready(function(){
$('.modal').success(function() {
$('input:text:visible:first').focus();
});
});
Or using your ID as an example instead:
$(document).ready(function(){
$('#modal-content').modal('show').success(function() {
$('input:text:visible:first').focus();
});
});
Hope that helps..

Attach an event immediately after setting up the HTML content

This is an example of my jQuery code that I use in a function to do pagination:
// new_content is a variable that holds the html I want to add to a div
$('div#my_div').html(new_content);
$("div#my_div a.details").hover(function(){
$(this).fadeIn(); //code to execute when the mouse get in
}, function(){
$(this).fadeOut(); //code to execute when the mouse get out
});
BUT the hover event does not work at all, and I believe that this is caused because the DOM is not ready yet!
To get around this I used set up a timer like this:
$('div#my_div').html(new_content);
window.setTimeout(
$("div#my_div a.details").hover(function(){
$(this).fadeIn(); //code to execute when the mouse get in
}, function(){
$(this).fadeOut(); //code to execute when the mouse get out
});
,100);
I asked this question because I'm sure that this is not the right way to attach an event immediately after the html method (maybe it didn't it's work!).
si I hope someone show me the right way to do it.
You would want to use the live mouseover mouseleave events
$("div#my_div").live({
mouseenter: function()
{
},
mouseleave: function()
{
}
}
);
Alternately you could do:
$('div#my_div').live('mouseover mouseout', function(event) {
if (event.type == 'mouseover') {
// do something on mouseover
} else {
// do something on mouseout
}
});
UPDATE
In newer versions of jQuery you can do it like this
$('body').on('mouseover','#my_div', function(){});
$('body').on('mouseout', '#my_div', function(){});
Maybe you need to use the live() method. As you can read here, it seems that you will need to separate the two events:
.live("mouseenter", function() {...})
.live("mouseleave", function() {...});
UPDATE: Someone voted me up, so if someone gets here, I recommend to read the on() documentation (here) as live was deprecated long ago. Also, it may be interesting to see mouseenter()(link) and mouseleave() (link). The idea is the same as with live.
It is better to use a delegate rather than live, as live is essentially a delegate on the document.body causing it to have to bubble much longer.
Here is an example using a delegate: http://jsfiddle.net/Akkuma/wLDpT/
you can check out .live function of jquery. Here is the link
http://api.jquery.com/live/

Categories

Resources