Attach an event immediately after setting up the HTML content - javascript

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/

Related

jQuery trigger on page load

How can I make jQuery run when my webpage has finished loading?
This is not what I want. All that this does is wait for the page to finish loading before any Javascript CAN be run.
$(document).ready(function(){
//Code here
});
What I want is for this to run when the page loads. I don't want it to wait for 'click' or 'change'. Can I add a 'load' or something to this?
$(document).on("change", "#input", function(e) {
$("#output").val($(this).val());
});
A workaround I have been using is to use jQuery to "change" the selected option on a select box, thereby triggering the code I actually want to run.
I have seen a bunch of questions like this, but every time the answer just says to use $(document).ready(function(){//Code}); which is not what I'm looking for.
Any ideas?
EDIT: Here is a better example of what I'm looking for.
This code below will run when the element with the id of 'input' is clicked. That is the only time it will run. I would like for it to run as soon as it is ready - as soon as $(document).ready(function(){}); can run it.
$(document).ready(function(){
$(document).on("change", "#input", function(e) {
$("#output").val($(this).val());
});
});
I think that this would work, but I was hoping for a nicer solution and one that doesn't require me to rewrite everything as functions.
$(document).ready(function(){
function runWhenReady(){
$("#output").val($(#input).val());
}
$(document).on("change", "#input", function(e) {
runWhenReady();
});
runWhenReady();
});
I think that this will run runWhenReady() when #input is clicked, and when the page finishes loading. My question is, is there a simpler way to do this?
I think the only way to do what I want is to name the function and call it two different ways.
$(document).ready(function(){
function xyzzy(){
$("#output").val($(#input).val());
}
//Call the function when #input is clicked
$(document).on("change", "#input", function(e) {
xyzzy();
});
//Call the function when the page loads
xyzzy();
});
This will call the function when the page has finished loading, as well whenever #input is clicked.
I think you're looking for $(window).load()
$(window).load(function(e){
// code here
});
Answer to your question in the comments:
$(document).on('click', '#input', function(e){
$('#output').val($(this).val());
});
Can I add a 'load' or something to this?
yes you can which will like $(window).on( "load", handler )
Also there is not much difference between the above code and
$( window).load(function() {
// Handler for .load() called.
});
The first method is just short cut of the second one
$(document).ready happens when all the elements are present in the DOM, but not necessarily all content.
$(document).ready(function() {
alert("document is ready");
});
window.onload vs document.onload
window.onload or $(window).load()
happens after all the content resources (images, etc) have been loaded.
$(window).load(function() {
alert("window is loaded");
});
From your Example:
$(document).ready(function(){
function runWhenReady(){
$("#output").val($(#input).val());
}
$(document).on("change", "#input", function(e) {
runWhenReady();
});
runWhenReady();
});
You could write:
$("#input").on("change", function() {...});
which defines a handler for your input. Everytime you change the value in the input it will call the function passed as argument. That make the whole $(document)... unneccessary.
If you want to run the function just once, as soon as possible wrap it in a IIFE like:
(function(){...});
Here is a pretty good blog post about IIFE:
http://benalman.com/news/2010/11/immediately-invoked-function-expression/

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

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.

jQuery - Hover after DOM change

With $('#sidebar').toggleClass('small'); Im adding adding/removing specified class from #sidebar.
When #sidebar has class small I should be able to perform additional actions when user hover over #sidebar.small.
I have tried to accomplish that with code bellow:
$("#sidebar.small").on({
mouseenter: function () {
alert(1); //doesn't work
},
mouseleave: function () {
//stuff to do on mouse leave
}
});
But that doesn't work.
How should I perform hover function on changed DOM element?
You should be able to use the jquery hover method to do this: https://api.jquery.com/hover/
Update:
Sorry noticed one other thing... when you originally set your event handler, does #sidebar have the css tag or not? The way your code is written, if it doesn't, it will try to attach to the element $("#sidebar.small"), so if the css tag is not there it won't attach to anything.
I think you want more like this:
$("#sidebar").on({
mouseenter: function() {
if($('#sidebar').hasClass('small')) {
alert(1);
}
}
});
Update again for a typo, sorry...
Jquery only binds the handlers for the found elements at the time of binding.
The solution is to rebind the appropriate handlers when you add the class.
jsfiddle
code from the fiddle:
$('#foo').click(function(){
$('<span></span>')
.text('A Span')
.appendTo('#container');
});
$('#bar').click(function(){
$('span').first().toggleClass('small');
bindHover();
})
function bindHover(){
$('span.small').unbind('hover'); // Avoid re-binding something
$('span.small').hover(function(){
alert('a')
});
}
bindHover();

disable mouseenter on menu-aim

Using menu-aim:
https://github.com/hfknight/jQuery-menu-aim/blob/master/jquery.menu-aim.js
Having an issue going responsive with it. It uses mouseenter and I need to disable mousenter on with a click.function() {}. If you view the the code in the plugin (above) at the bottom you see these events:
$menu
.mouseleave(mouseleaveMenu)
.find(options.rowSelector) // here
.mouseenter(mouseenterRow) // and here
.mouseleave(mouseleaveRow)
.click(clickRow);
$(document).mousemove(mousemoveDocument);
I want to disable the mouseover event in this .click(function (){})
$('[data-toggle="offcanvas"]').click(function () {
});
Here is an incorrect code so you get a better understanding of what I am trying to achieve:
$('[data-toggle="offcanvas"]').click(function () {
$(".dropdown-menu").menuAim({
activate: function(){disable mouseenter here }
});
});
TL;DR
Didn't quite understand but this way you can off any event. You may give it a try:
// For all elements with an identifier
function(){ $('elementIdOrClass').off('mouseenter'); }
// For current element only
function(){ $(this).off('mouseenter'); }
Also you may use unbind('mouseenter').

jQuery .on('change', function() {} not triggering for dynamically created inputs

The problem is that I have some dynamically created sets of input tags and I also have a function that is meant to trigger any time an input value is changed.
$('input').on('change', function() {
// Does some stuff and logs the event to the console
});
However the .on('change') is not triggering for any dynamically created inputs, only for items that were present when the page was loaded. Unfortunately this leaves me in a bit of a bind as .on is meant to be the replacement for .live() and .delegate() all of which are wrappers for .bind() :/
Has anyone else had this problem or know of a solution?
You should provide a selector to the on function:
$(document).on('change', 'input', function() {
// Does some stuff and logs the event to the console
});
In that case, it will work as you expected. Also, it is better to specify some element instead of document.
Read this article for better understanding: http://elijahmanor.com/differences-between-jquery-bind-vs-live-vs-delegate-vs-on/
You can use any one of several approaches:
$("#Input_Id").change(function(){ // 1st way
// do your code here
// Use this when your element is already rendered
});
$("#Input_Id").on('change', function(){ // 2nd way
// do your code here
// This will specifically call onChange of your element
});
$("body").on('change', '#Input_Id', function(){ // 3rd way
// do your code here
// It will filter the element "Input_Id" from the "body" and apply "onChange effect" on it
});
Use this
$('body').on('change', '#id', function() {
// Action goes here.
});
Just to clarify some potential confusion.
This only works when an element is present on DOM load:
$("#target").change(function(){
//does some stuff;
});
When an element is dynamically loaded in later you can use:
$(".parent-element").on('change', '#target', function(){
//does some stuff;
});
$("#id").change(function(){
//does some stuff;
});
you can use:
$('body').ready(function(){
$(document).on('change', '#elemID', function(){
// do something
});
});
It works with me.
You can use 'input' event, that occurs when an element gets user input.
$(document).on('input', '#input_id', function() {
// this will fire all possible change actions
});
documentation from w3
$(document).on('change', '#id', aFunc);
function aFunc() {
// code here...
}

Categories

Resources